More On Decision Making and Loops in C
More On Decision Making and Loops in C
Lecture 4
More on Decision
s
Making and Loops in C
s
The If Statement
Equal to if (x==10)
Not equal to if (x!=10)
Less than if (x<10)
Greater than if (x>10)
Less than / equal to if (x<=10)
Greater than / equal to if (x>=10)
Compound Operators
if (condition) {
if (condition)
……
true_statement;
}
else
else {
false_statement;
……
}
Nested If Statements
void main(void)
{
int winner =3;
printf(“…and the winner of ICC is ”);
if (winner==1) printf(“Pakistan”);
else if (winner==2)
printf(“England”);
else if (winner==3)
printf(“WI”);
else
printf(“Australia”);
}
Conditional Statement
void main(void)
{
int num;
printf("Enter a value:");
scanf("%d", &num);
if (num < 0)
printf("The value is negative\n");
else if (num == 0)
printf("The value is zero\n");
else
printf("The value is positive\n");
return 0;
}
Switch Statements
Switch statements look like this
example:
switch (expression) {
value_1 : statements_1; break;
value_2 : statements_2; break;
...
value_n : statements_n; break
default
switch (winner) {
case 1 : printf(“Pakistan”);
break;
case 2 : printf(“England”);
break;
.
value_n : statements_n; break
default:
Loops
Syntax:
for (initialization; test; increment)
{
statements;
}
The for loop will first perform the
initialization. Then, as long test is TRUE,
it will execute statements. After each
execution, it will increment.
For loop
for(count=1;count<=10;count++)
{
body of loop
}
For loop examples
degree =0;
while (degrees <= 360)
{
decree += increment;
}
The While Loop
An example while loop looks like this:
void main(void)
{
char ch;
do {
statements;
} while (cond_expr);
A ‘while’ for ‘for’
i=0;
while(i<10)
{
body of the loop;
i++;
}
is equivalent to
for(i=0; i<10; i++)
{
body of the loop;
}
A ‘for’ for ‘while’
for(; degree<360;)
{
degree += increment;
}
Special Cases