0% found this document useful (0 votes)
52 views

2.conditional & Loops

Conditionals allow performing different computations or actions depending on whether a condition is true or false. The if statement executes code if an expression evaluates to true, and optionally includes an else clause to execute code if the expression is false. Logical operators like &&, ||, and ! are used to combine multiple conditions. Loops like while, do-while, and for repeatedly execute code as long as or for as long as a condition is true.

Uploaded by

Sukamal Dash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

2.conditional & Loops

Conditionals allow performing different computations or actions depending on whether a condition is true or false. The if statement executes code if an expression evaluates to true, and optionally includes an else clause to execute code if the expression is false. Logical operators like &&, ||, and ! are used to combine multiple conditions. Loops like while, do-while, and for repeatedly execute code as long as or for as long as a condition is true.

Uploaded by

Sukamal Dash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Conditionals

Conditionals are used to perform different computations or actions depending on


whether a condition evaluates to true or false.

The if Statement
The if statement is called a conditional control structure because it executes
statements when an expression is true. For this reason, the if is also known as a decision
structure. It takes the form:
if (expression)
statements
The expression evaluates to either true or false, and statements can be a single
statement or a code block enclosed by curly braces { }.
For example:
#include <stdio.h>
int main() {
int score = 89;
if (score > 75)
printf("You passed.\n");
return 0;
}
In the code above we check whether the score variable is greater than 75, and print a
message if the condition is true.

Relational Operators
There are six relational operators that can be used to form a Boolean expression, which
returns true or false:
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
For example:
int num = 41;
num += 1;
if (num == 42) {
printf("You won!");
}
An expression that evaluates to a non-zero value is considered true. For example:
int in_stock = 20;
if (in_stock)
printf("Order received.\n");

The if-else Statement


The if statement can include an optional else clause that executes statements when an
expression is false. For example, the following program evaluates the expression and
then executes the else clause statement:
#include <stdio.h>
int main() {
int score = 89;
if (score >= 90)
printf("Top 10%%.\n");
else
printf("Less than 90.\n");
return 0;
}

Conditional Expressions
Another way to form an if-else statement is by using the ?: operator in a conditional
expression. The ?: operator can have only one statement associated with the if and the
else.
For example:
#include <stdio.h>
int main() {
int y;
int x = 3;
y = (x >= 5) ? 5 : x;
/* This is equivalent to:
if (x >= 5)
y = 5;
else
y = x;
*/
return 0;
}

Nested if Statements
An if statement can include another if statement to form a nested statement. Nesting
an if allows a decision to be based on further requirements. Consider the following
statement:
if (profit > 1000)
if (clients > 15)
bonus = 100;
else
bonus = 25;
Appropriately indenting nested statements will help clarify the meaning to a reader.
However, be sure to understand that an else clause is associated with the closest if
unless curly braces { } are used to change the association. For example:
if (profit > 1000) {
if (clients > 15)
bonus = 100;
}else
bonus = 25;

The if-else if Statement


When a decision among three or more actions is needed, the if-else if statement can be
used. There can be multiple else if clauses and the last else clause is optional.
For example:
int score = 89;
if (score >= 90)
printf("%s", "Top 10%\n");
else if (score >= 80)
printf("%s", "Top 20%\n");
else if (score > 75)
printf("%s", "You passed.\n");
else
printf("%s", "You did not pass.\n");
Carefully consider the logic involved when developing an if-else if statement.
Program flow branches to the statements associated with the first true expression
and none of the remaining expressions will be tested.
Although indents won't affect the compiled code, the logic of the if-else if will be
easier to understand by a reader when the else clauses are aligned.
When possible, an if-else if statement is preferred over nested if statements for
clarity.

The switch Statement


The switch statement branches program control by matching the result of an expression
with a constant case value. The switch statement often provides a more elegant
solution to if-else if and nested if statements. The switch takes the form:
switch (expression) {
case val1:
statements
break;
case val2:
statements
break;
default:
statements
}
For example, the following program outputs "Three":
int num = 3;
switch (num) {
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
case 3:
printf("Three\n");
break;
default:
printf("Not 1, 2, or 3.\n");
}
There can be multiple cases with unique labels. The optional default case is executed
when no other matches are made. A break statement is needed in each case to
branch to the end of the switch statement. Without the break statement, program
execution falls through to the next case statement. This can be useful when the same
statement is needed for several cases. Consider the following switch statement:
switch (num) {
case 1:
case 2:
case 3:
printf("One, Two, or Three.\n");
break;
case 4:
case 5:
case 6:
printf("Four, Five, or Six.\n");
break;
default:
printf("Greater than Six.\n");
}
Caution must be used when constructing the switch this way. Modifications later can
lead to unexpected outcomes.

Logical Operators
Logical operators && and || are used to form a compound Boolean expression that tests
multiple conditions. A third logical operator is ! used to reverse the state of a Boolean
expression.

The && Operator


The logical AND operator && returns a true result only when both expressions are true.
For example:
if (n > 0 && n <= 100)
printf("Range (1 - 100).\n");
The statement above joins just two expressions, but logical operators can be used to
join multiple expressions. A compound Boolean expression is evaluated from left to
right. Evaluation stops when no further test is needed for determining the result, so
be sure to consider the arrangement of operands when one result affects the
outcome of a later result.

The || Operator
The logical OR operator || returns a true result when any one expression or both
expressions are true. For example:
if (n == 'x' || n == 'X')
printf("Roman numeral value 10.\n");
Any number of expressions can be joined by && and ||. For example:
if (n == 999 || (n > 0 && n <= 100))
printf("Input valid.\n");
Parentheses are used for clarity even though && has higher precedence than || and
will be evaluated first.

The ! Operator
The logical NOT operator ! returns the reverse of its value. NOT true returns false, and
NOT false returns true. For example:
if (!(n == 'x' || n == 'X'))
printf("Roman numeral is not 10.\n");
In C, any non-zero value is considered true and a 0 is false. The logical NOT operator
therefore, converts a true value to 0 and a false value to 1.

The while Loop


The while statement is called a loop structure because it executes statements
repeatedly while an expression is true, looping over and over again. It takes the form:
while (expression) {
statements
}
The expression evaluates to either true or false, and statements can be a single
statement or, more commonly, a code block enclosed by curly braces { }. For example:
#include <stdio.h>
int main() {
int count = 1;
while (count < 8) {
printf("Count = %d\n", count);
count++;
}
return 0;
}
The code above will output the count variable 7 times. The while loop evaluates a
condition before the loop is entered, making it possible that the while statements
never execute. An infinite loop is one that continues indefinitely because the loop
condition never evaluates to false. This may cause a run-time error.

The do-while Loop


The do-while loop executes the loop statements before evaluating the expression to
determine if the loop should be repeated. It takes the form:
do {
statements
} while (expression);
The expression evaluates to either true or false, and statements can be a single
statement or a code block enclosed by curly braces { }.
For example:
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Count = %d\n", count);
count++;
} while (count < 8);
return 0;
}
Note the semicolon after the while statement. The do-while loop always executes at
least once, even if the expression evaluates to false.

break and continue


The break statement was introduced for use in the switch statement. It is also useful for
immediately exiting a loop. For example, the following program uses a break to exit a
while loop:
int num = 5;
while (num > 0) {
if (num == 3)
break;
printf("%d\n", num);
num--;
}
This program displays:
5
4
and then exits the loop.
When you want to remain in the loop, but skip ahead to the next iteration, you use
the continue statement.
For example:
int num = 5;
while (num > 0) {
num--;
if (num == 3)
continue;
printf("%d\n", num);
}
The program output displays:
4
2
1
0
As you can see, the value 3 is skipped.
In the code above, if num was decremented after the continue statement an infinite
loop would be created. Although the break and continue statements can be
convenient, they should not be a substitute for a better algorithm.

The for Loop


The for statement is a loop structure that executes statements a fixed number of times.
It takes the form:
for (initvalue; condition; increment) {
statements;
}
The initvalue is a counter set to an initial value. This part of the for loop is performed
only once.
The condition is a Boolean expression that compares the counter to a value after each
loop iteration, stopping the loop when false is returned.
The increment increases (or decreases) the counter by a set value.
For example, the program below displays 0 through 9:
int i;
int max = 10;
for (i = 0; i < max; i++) {
printf("%d\n", i);
}
The for loop can contain multiple expressions separated by commas in each part. For
example:
for (x = 0, y = num; x < y; i++, y--) {
statements;
}
Also, you can skip the initvalue, condition and/or increment. For example:
int i=0;
int max = 10;
for (; i < max; i++) {
printf("%d\n", i);
}
Loops can also be nested. When writing a program this way, there is an outer loop
and an inner loop. For each iteration of the outer loop the inner loop repeats its
entire cycle. In the following example, nested for loops are used to output a
multiplication table:
int i, j;
int table = 10;
int max = 12;
for (i = 1; i <= table; i++) {
for (j = 0; j <= max; j++) {
printf("%d x %d = %d\n", i, j, i*j);
}
printf("\n"); /* blank line between tables */
}
A break in an inner loop exits that loop and execution continues with the outer loop.
A continue statement works similarly in nested loops.

You might also like