Decision & Looping
Decision & Looping
Switch statement
Looping
Example :
To find whether a number is even or odd we proceed as follows :
1. Accept a number
2. Find the remainder by dividing the number by 2
3. If the remainder is zero, the number is “EVEN”
4. Or if the remainder is not zero the number is “ODD”
The if statement
Syntax:
#include <stdio.h>
void main()
{
int x, y;
char a = ‘y’;
x = y = 0;
Example
if (a == ‘y’)
{
x += 5;
printf(“The numbers are %d and \t%d”, x, y);
}
}
Syntax:
#include <stdio.h>
void main()
{
int num , res ;
Syntax:
#include <stdio.h>
void main ()
{
int x, y;
x = y = 0;
clrscr ();
printf (“Enter Choice (1 - 3) : “);
scanf (“%d”, &x);
Example
if (x == 1)
{
printf(“\nEnter value for y (1 - 5) : “);
scanf (“%d”, &y);
if (y <= 5)
printf(“\nThe value for y is : %d”, y);
else
printf(“\nThe value of y exceeds 5 “);
}
else
printf (“\nChoice entered was not 1”);
}
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 09e-BM/DT/FSOFT v1/1
The switch statement-1
contd…….
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 09e-BM/DT/FSOFT v1/1
The switch statement-3
if (ch < ‘a’ || ch > ‘z’)
printf(“\nCharacter not a lower cased alphabet”);
else
switch (ch)
{
case ‘a’ :
case ‘e’ :
case ‘i’ :
case ‘o’ :
case ‘u’ :
printf(“\nCharacter is a vowel”);
break;
case ‘z’ :
printf (“\nLast Alphabet (z) was entered”);
break;
default :
printf(“\nCharacter is a consonant”);
break;
}
}
main()
{
int count;
printf(“\tThis is a \n”);
#include <stdio.h>
main()
{
int i, j , max;
printf(“Please enter the maximum value \n”);
printf(“for which a table can be printed: “);
scanf(“%d”, &max);
#include <stdio.h>
main()
{
int count = 1;
while( count <= 10)
{
printf(“\n This is iteration %d\n”,count);
count++;
}
do{
statement;
} while (condition);
expression
The return statement is used to return from a function
label
The goto statement transfers control to any other
statement within the same function in a C program
statement
The break statement is used to terminate a case in a
switch statement
statement
The continue statement causes the next iteration of the
enclosing loop to begin
#include <stdio.h>
main ()
{
int num;
for(num = 1; num <=100; num++)
{
if(num % 9 == 0)
continue;
printf("%d\t",num);
}
}
function
The exit() is used to break out of the program