0% found this document useful (0 votes)
9 views36 pages

Module 2 Control Stmnts

Module-2 covers decision control and looping statements in C programming, including operators, type conversion, and various control statements like if, if-else, and switch-case. It provides examples of how to implement these statements through various programs, such as checking eligibility to vote, determining even or odd numbers, and finding the largest of three numbers. Additionally, it discusses iterative statements like while and do-while loops for executing code repeatedly based on conditions.

Uploaded by

Kangana W. M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views36 pages

Module 2 Control Stmnts

Module-2 covers decision control and looping statements in C programming, including operators, type conversion, and various control statements like if, if-else, and switch-case. It provides examples of how to implement these statements through various programs, such as checking eligibility to vote, determining even or odd numbers, and finding the largest of three numbers. Additionally, it discusses iterative statements like while and do-while loops for executing code repeatedly based on conditions.

Uploaded by

Kangana W. M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Module-2: Decision control and looping statements

Operators in C, Type conversion and typecasting.


Decision control and Looping statements: Introduction to decision control,
Conditional branching statements, iterative statements, nested loops, break
and continue statements, goto statement.
Textbook: Chapter 9.15-9.16, 10.1-10.6

Decision control statements:

 Decision control statements are used to alter the flow of a sequence of instructions.
 These statements help to jump from one part of the program to another depending
on whether a particular condition is satisfied or not.
 Generally C program statement is executed in a order in which they appear in the
program. But sometimes we use decision making condition for execution only a part of
program that is called control statement.
 Control statement defined how the control is transferred from one part to the other
part of the program.
 These decision control statements include
1. if statement
2. if else statement
3. if else if statement
4. switch statement

if-Statement

• If statement is the simplest form of decision control statements that is frequently


used in decision making.

• First the test expression is evaluated. If the test expression is true, the statement of
if block (statement 1 to n) are executed otherwise these statements will be skipped and
the execution will jump to statement x.
Start

False
Condition?

True

Statements inside
if block

Statements
outside if block

End

Nisha S K, Dept. of ECE, SVIT Page 1


Module-2: Decision control and looping statements

WAP to determine whether a person is eligible to vote or not.

#include<stdio.h>

void main()

int age;

printf("Enter the age\n");

scanf("%d",&age);

if(age>=18)

printf("He/she is eligible to vote");

WAP to determine the character entered by the user.

#include<stdio.h>

void main()

char ch;

printf("Enter the character\n");

scanf("%c",&ch);

if(ch>0)

printf("The character has been entered");

if-else Statement

In the if-else construct, first the test expression is evaluated. If the expression is true,
statement block 1 is executed and statement block 2 is skipped. Otherwise, if the

Nisha S K, Dept. of ECE, SVIT Page 2


Module-2: Decision control and looping statements

expression is false, statement block 2 is executed and statement block 1 is ignored. In


any case after the statement block 1 or 2 gets executed the control will pass to
statement x. Therefore, statement x is executed in every case.

WAP to find if the given number is even or odd.

#include <stdio.h>

void main()

int a;

printf("Enter the number\n");

scanf("%d",&a);

if(a%2==0)

printf("the number is even");

else

printf("the number is odd");


}

Nisha S K, Dept. of ECE, SVIT Page 3


Module-2: Decision control and looping statements

WAP to find if the given character is a vowel or a consonant.

#include <stdio.h>

void main()

char ch = 'C';

if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E'|| ch == 'i' || ch == 'I' || ch == 'o' ||


ch == 'O'|| ch == 'u' || ch == 'U')

printf("The character %c is a vowel.\n", ch);

else

printf("The character %c is a consonant.\n", ch);

WAP to find largest of 2 numbers.

#include <stdio.h>

void main()

int a=100,b=20;

if(a<b)

printf("b is largest of 2 numbers");

Else

Nisha S K, Dept. of ECE, SVIT Page 4


Module-2: Decision control and looping statements

printf("a is largest of 2 numbers");

WAP to enter any character. If entered in upper case then display in lower case
and vice versa.

#include<stdio.h>

void main()

char ch;

printf("Enter the character\n");

scanf("%c",&ch);

if(ch>='A'&&ch<='Z')

printf("The entered character in lower case is %c",(ch+32));

else

printf("The entered character in upper case is %c",(ch-32));

WAP to find if the given year is leap year or not.

The year number must be divisible by four – except for end-of-century years, which
must be divisible by 400.

Example: This means that the year 2000 was a leap year, although 1900 was not

#include<stdio.h>

void main()

Nisha S K, Dept. of ECE, SVIT Page 5


Module-2: Decision control and looping statements

int year;

printf("Enter any year\n");

scanf("%d",&year);

if((year%4==0)&&(year%100!=0)||(year%400==0))

printf("Leap year");

else

printf("Not a leap year");

if-else-if Statement

 C language supports if else if statements to test additional conditions apart from


the initial test expression. The if-else-if construct works in the same way as a normal if
statement.
 This process continue until there is no if statement in the last block. if one of the
condition is satisfy the condition other nested “else if” would not executed. But it has
disadvantage over if else statement that, in if else statement whenever the condition is
true, other condition are not checked. While in this case, all condition is checked.

WAP to demonstrate if-else-if statement.

Nisha S K, Dept. of ECE, SVIT Page 6


Module-2: Decision control and looping statements

void main()

int a,b;

printf("Enter the value of a and b\n");

scanf("%d,%d",&a,&b);

if(a==b)

printf("a and b are equal");

else if(a>b)

printf("a is greater than b");

else

printf("a is less than b");

Condition called Pitfall

It is a condition where in while using if statement, instead of using equal to(==)


assignment operator, we use = to sign. Here instead of checking the condition, the
value is assigned to the variable.

Example:

void main()

int a;

printf("Enter the value\n");

Nisha S K, Dept. of ECE, SVIT Page 7


Module-2: Decision control and looping statements

scanf("%d",&a);

if(a=10)//The condition should e a==10. Here instead of checking the condition ,the
value is being assigned to a.

printf("Equal");

else

printf("not equal");

WAP to check if the number is positive,negative, or equal to zero

void main()

int a;

printf("Enter the value of a and b\n");

scanf("%d",&a);

if(a>0)

printf("The number is positive");

else if(a<0)

printf("The number is negative");

else

printf("The numer is eqaul to zero");

WAP to find largest of 3 numbers.

Nisha S K, Dept. of ECE, SVIT Page 8


Module-2: Decision control and looping statements

void main(){

int a,b,c;

printf("Enter a,b,c\n");

scanf("%d,%d,%d",&a,&b,&c);

if(a>b)

if(a>c)

printf("a is greater");

else

printf("c is greater");

else if(b>c)

printf("b is greater");

else

printf("c is greater");

WAP to find largest of 3 numbers using logical and operator

#include<stdio.h>

void main()

int a,b,c;

printf("Enter a,b,c\n");

scanf("%d,%d,%d",&a,&b,&c);

if(a>b&&a>c)

printf("a is greater");

if(b>a&&b>c)

Nisha S K, Dept. of ECE, SVIT Page 9


Module-2: Decision control and looping statements

printf("b is greater");

if(c>a&&c>b)

printf("c is greater");

Rules to use Decision control statements

• Rule 1: The expression must be enclosed in parentheses.

• Rule 2: No semicolon is placed after the if/if-else/if-else-if statement.


Semicolon is placed only after inside the statement block if required.

• Rule 3: A statement block starts and ends with curly braces. No


semicolon is placed after the opening/closing of braces.

Switch case

A switch case statement is a multi-way decision statement.

• Switch statements are used:

 When there is only one variable to evaluate in the expression

 When many conditions are being tested for

• Switch case statement advantages include:

1. Easy to debug, read, understand and maintain

2. Execute faster than its equivalent if-else construct

How switch case works?

Step 1: The switch variable is evaluated.

Step 2: The evaluated value is matched against all the present cases.

Step 3A: If the matching case value is found, the associated code is executed.

Step 3B: If the matching code is not found, then the default case is executed if
present.

Step 4A: If the break keyword is present in the case, then program control breaks
out of the switch statement.

Step 4B: If the break keyword is not present, then all the cases after the
matching case are executed.

Step 5: Statements after the switch statement are executed.

Nisha S K, Dept. of ECE, SVIT Page 10


Module-2: Decision control and looping statements

Example:

char grade=‘C’;

switch(grade)

{ case 'A':

printf("\n Excellent");

break;

case 'B':

printf("\n Good");

break;
case 'C':

Nisha S K, Dept. of ECE, SVIT Page 11


Module-2: Decision control and looping statements

printf("\n Fair");

break;

default:

printf("\n Invalid Grade");

break;

WAP to check if character is vowel or not.

char ch;

printf("Enter the character\n");

scanf("%c",&ch);

switch(ch)

case 'A':

case 'a':printf("%c is vowel",ch);

break;

case 'E':

case 'e':printf("%c is vowel",ch);

break;

case 'I':

case 'i':printf("%c is vowel",ch);

break;

case 'O':

case 'o':printf("%c is vowel",ch);

break;

case 'U':

case 'u':printf("%c is vowel",ch);

Nisha S K, Dept. of ECE, SVIT Page 12


Module-2: Decision control and looping statements

break;

default:printf("%c is not a vowel",ch);

WAP to enter a number from 1-7 and display the corresponding day of the week
using switch case.

void main() {

int day;

printf("Enter any number from 1 to 7: \n");

scanf("%d",&day);

switch(day) {

case 1:printf("\nSunday");

break;

case 2:printf("\nMonday");

break;

case 3:printf("\nTuesday");

break;

case 4:printf("\nWednesday");

break;

case 5:printf("\nThursday");

break;

case 6:printf("\nFriday");

break;

case 7:printf("\nSaturday");

break;

default:printf("You have entered wrong number");

WAP to check if the number is even or odd.

Nisha S K, Dept. of ECE, SVIT Page 13


Module-2: Decision control and looping statements

#include<stdio.h>

void main()

int num,rem;

printf("Enter any number: \n");

scanf("%d",&num);

rem=num%2;

switch(rem)

case 0:printf("\nEven");

break;

case 1:printf("\nOdd");

break;

Advantages of using SWITCH case:

• Easy to debug.

• Easy to read and understand

• Ease of maintenance as compared with its equivalent if-else.

• switch case can also be nested.

• Executes faster than if-else.

Iterative statements

Iterative statements are used to repeat the execution of a list of statements, depending
on the value of an integer expression. In this section, we will discuss all these
statements.

Nisha S K, Dept. of ECE, SVIT Page 14


Module-2: Decision control and looping statements

• While loop

• Do-while loop

• For loop

while loop

The while loop is used to repeat one or more statements while a particular condition is
true.

In the while loop, the condition is tested before any of the statements in the statement
block is executed.

If the condition is true, only then the statements will be executed otherwise the control
will jump to the immediate statement outside the while loop block.

We must constantly update the condition of the while loop.


Start

False
Condition?

True

Statements inside
while block

Updating

Statements
outside while
WAP to calculate the sum of first 10 numbers. block
#include<stdio.h> End

void main()

int i=1,sum=0;

while(i<=10)

sum=sum+i;

Nisha S K, Dept. of ECE, SVIT Page 15


Module-2: Decision control and looping statements

i++;

printf("\nsum=%d",sum);

WAP to print 20 horizontal asterisks.

#include<stdio.h>

void main()

int i=1;

while(i<=20)

printf("*");

i++;

WAP to calculate the sum of numbers from m to n

#include<stdio.h>

void main()

int i,j,sum=0;

printf("Enter value of i: ");

scanf("%d",&i);

printf("Enter value of j: ");

scanf("%d",&j);

while(i<=j)

Nisha S K, Dept. of ECE, SVIT Page 16


Module-2: Decision control and looping statements

sum=sum+i;

i++;

printf("\nsum=%d",sum);

WAP to display the largest of 5 numbers using ternary operator.

#include<stdio.h>

void main()

int i=1,large,num;

while(i<=5)

printf("Enter the number");

scanf("%d",&num);

large=num>large?num:large;

i++;

printf("\n The largest of 5 numbers is:%d",large);

do-while loop

The do-while loop is similar to the while loop. The only difference is that in a do-while
loop, the test condition is tested at the end of the loop.

The body of the loop gets executed at least one time (even if the condition is false).

The do while loop continues to execute whilst a condition is true. There is no choice
whether to execute the loop or not. Hence, entry in the loop is automatic there is only a
choice to continue it further or not.

The major disadvantage of using a do while loop is that it always executes at least
once, so even if the user enters some invalid data, the loop will execute.

Nisha S K, Dept. of ECE, SVIT Page 17


Module-2: Decision control and looping statements

do-while loops are widely used to print a list of options for a menu driven program.

WAP to calculate the average of first n numbers.

#include<stdio.h>

void main()

int n,i=1,sum;

float avg;

printf("\nEnter the value of n:");

scanf("%d",&n);

do

sum+=i;

i++;

}while(i<=n);

avg=(float)sum/n;

printf("Sum=%d\n",sum);

printf("Avg=%f",avg);

Nisha S K, Dept. of ECE, SVIT Page 18


Module-2: Decision control and looping statements

WAP to display square and cube of first n natural numbers.

#include<stdio.h>

void main()

int i,n;

printf("Enter the value of n:");

scanf("%d",&n);

i=1;

do

printf("\n|\t%d\t|\t%d\t|\t%d\t|",i,i*i,i*i*i);

i++;

}while(i<=n);

WAP to list the leap year between 1900 to 1920.

#include<stdio.h>

void main()

int m=1900,n=1920;

do

if(((m%4==0)&&(m%100!=0))||(m%400==0))

printf("%d is Leap year\n",m);

m++;

}while(m<=n);

Nisha S K, Dept. of ECE, SVIT Page 19


Module-2: Decision control and looping statements

for loop

• For loop is used to repeat a task until a particular condition is true.

• The syntax of a for loop

for (initialization; condition; increment/decrement/update)

statement block;

Statement Y;

Flow chart

• When a for loop is used, the loop variable is initialized only once. With every
iteration of the loop, the value of the loop variable is updated and the condition is
checked. If the condition is true, the statement block of the loop is executed else, the
statements comprising the statement block of the for loop are skipped and the control
jumps to the immediate statement following the for loop body. Updating the loop
variable may include incrementing the loop variable, decrementing the loop variable or
setting it to some other value like, i +=2, where i is the loop variable.

WAP to print n natural numbers

#include<stdio.h>

void main()
{

Nisha S K, Dept. of ECE, SVIT Page 20


Module-2: Decision control and looping statements

int i,n;

printf("Enter the value of n: ");

scanf("%d",&n);

for(i=1;i<=n;i++)

printf("%d\t",i);

WAP to print n whole numbers

#include<stdio.h>

void main()

int i,n;

printf("Enter the value of n: ");

scanf("%d",&n);

for(i=0;i<=n;i++)

printf("%d\t",i);

WAP to print multiples of 4 until 40.

#include<stdio.h>

void main()

Nisha S K, Dept. of ECE, SVIT Page 21


Module-2: Decision control and looping statements

int i,n;

printf("Enter the value of n: ");

scanf("%d",&n);

for(i=4;i<=n;i+=4)

printf("%d\t",i);

WAP to print following pattern.

**********

**********

**********

**********

**********

#include<stdio.h>

void main()

int i,j;

for(i=1;i<=5;i++)

printf("\n");

for(j=1;j<=10;j++)

printf("* ");

Nisha S K, Dept. of ECE, SVIT Page 22


Module-2: Decision control and looping statements

WAP to print the following pattern.

**

***

****

*****

#include<stdio.h>

void main()

int i,j;

for(i=1;i<=5;i++)

printf("\n");

for(j=1;j<=i;j++)

printf("*");

WAP to print following pattern

12

123

Nisha S K, Dept. of ECE, SVIT Page 23


Module-2: Decision control and looping statements

1234

12345

#include<stdio.h>

void main()

int i,j;

for(i=1;i<=5;i++)

printf("\n");

for(j=1;j<=i;j++)

printf("%d",j);

WAP to print following pattern

22

333

4444

55555

#include<stdio.h>

void main()

int i,j;

Nisha S K, Dept. of ECE, SVIT Page 24


Module-2: Decision control and looping statements

for(i=1;i<=5;i++)

printf("\n");

for(j=1;j<=i;j++)

printf("%d",i);

WAP to print following pattern.

12

345

6789

#include<stdio.h>

void main()

int i,j,count=0;

for(i=1;i<=4;i++)

printf("\n");

for(j=1;j<=i;j++)

printf("%d",count++);

Nisha S K, Dept. of ECE, SVIT Page 25


Module-2: Decision control and looping statements

WAP to print following pattern.

AB

ABC

ABCD

ABCDE

ABCDEF

#include<stdio.h>

void main()

char i,j;

for(i=65;i<=70;i++)

printf("\n");

for(j=65;j<=i;j++)

printf("%c",j);

WAP to print following pattern.

12

123

Nisha S K, Dept. of ECE, SVIT Page 26


Module-2: Decision control and looping statements

1234

12345

void main()

int N = 5,i,j,k;

for (i = 0; i < N; i++)

for (j = 0; j < 2 * (N - i) - 1; j++)

printf(" ");

for (k = 0; k <= i; k++)

printf("%d ",k+1);

printf("\n");

break statement

• The break statement is used to terminate the execution of the nearest enclosing
loop in which it appears.

• When compiler encounters a break statement, the control passes to the statement
that follows the loop in which the break statement appears. Its syntax is quite simple,
just type keyword break followed with a semi-colon.

break;

• In switch statement if the break statement is missing then every case from the
matched case label to the end of the switch, including the default, is executed.

Nisha S K, Dept. of ECE, SVIT Page 27


Module-2: Decision control and looping statements

while(…) do

{ {

….. …..

if(condition) if(condition)

break; break;

….. …..

} }while(…);

Transfers the control out of the Transfers the control out of the
while loop do-while loop

for(…) for(…)

{ {

….. …..

if(condition) for(…)

break; {

….. if(condition)

} break;

Transfers the control out of the for …..


loop
}

Stmnt y

Transfers the control out of the


continue statement inner for loop

• The continue statement can only appear in the body of a loop.

• When the compiler encounters a continue statement then the rest of the
statements in the loop are skipped and the control is unconditionally transferred

Nisha S K, Dept. of ECE, SVIT Page 28


Module-2: Decision control and looping statements

to the loop-continuation portion of the nearest enclosing loop. Its syntax is quite
simple, just type keyword continue followed with a semi-colon.

continue;

• If placed within a for loop, the continue statement causes a branch to the code
that updates the loop variable. For example,

int i;

for(i=1;i<=10;i++)

{ if(i==5)

continue;

printf("\t %d",i); }

while(…) do

{ {

….. …..

if(condition) if(condition)

continue; continue;

….. …..

} }while(…);

Transfers the control to Transfers the control to the


the condition expression of condition expression of the do-
the while loop while loop

Nisha S K, Dept. of ECE, SVIT Page 29


Module-2: Decision control and looping statements

for(…) for(…)

{ {

….. …..

if(condition) for(…)

continue; {

….. if(condition)

} continue;

Transfers the control to the …..


condition expression of the
}
for loop
}

Transfers the control to the condition


expression of the inner for loop

goto statement

• The goto statement is used to transfer control to a specified label.

• Here label is an identifier that specifies the place where the branch is to be
made. Label can be any valid variable name that is followed by a colon (:).

• Note that label can be placed anywhere in the program either before or after the
goto statement. Whenever the goto statement is encountered the control is
immediately transferred to the statements following the label.

• Goto statement breaks the normal sequential execution of the program.

• If the label is placed after the goto statement then it is called a forward jump
and in case it is located before the goto statement, it is said to be a backward
jump.

• It is not necessary to use goto statement as it can always eliminated by


rearranging the code.

• Using the goto statement violates the rules of structured programming.

Nisha S K, Dept. of ECE, SVIT Page 30


Module-2: Decision control and looping statements

• It is a good programming practice to use break, continue statements in


preference to goto whenever possible.

• Goto statements make the program code complicated and render the program
unreadable.

Example:

int num, sum=0;

read: // label for go to statement

printf("\n Enter the number. Enter 999 to end : ");

scanf("%d", &num);

if (num != 999)

if(num < 0)

goto read; // jump to label- read

sum += num;

goto read; // jump to label- read

printf("\n Sum of the numbers entered by the user is = %d", sum);

Important programs:
Write a C program to find factorial of a number.

Nisha S K, Dept. of ECE, SVIT Page 31


Module-2: Decision control and looping statements

#include <stdio.h>

void main()

int n, i,fact = 1;

printf("Enter an integer: ");

scanf("%d", &n);

if (n < 0)

printf("Error! Factorial of a negative number doesn't exist.");

else

for (i = 1; i <= n; ++i)

fact *= i;

printf("Factorial of %d = %d", n, fact);

WAP to generate the Fibonacci series.

#include <stdio.h>

Nisha S K, Dept. of ECE, SVIT Page 32


Module-2: Decision control and looping statements

void main()

int i, n;

int t1 = 0, t2 = 1;

int nextTerm = t1 + t2;

printf("Enter the number of terms: ");

scanf("%d", &n);

printf("Fibonacci Series: %d, %d, ", t1, t2);

for (i = 3; i <= n; ++i)

printf("%d, ", nextTerm);

t1 = t2;

t2 = nextTerm;

nextTerm = t1 + t2;

WAP to check if the given number is Palindrome or not.

#include <stdio.h>

Nisha S K, Dept. of ECE, SVIT Page 33


Module-2: Decision control and looping statements

void main()

int n, reversed = 0, rem, original;

printf("Enter an integer: ");

scanf("%d", &n);

original = n;

while (n != 0)

rem = n % 10;

reversed = reversed * 10 + rem;

n /= 10;

if (original == reversed)

printf("%d is a palindrome.", original);

else

printf("%d is not a palindrome.", original);

WAP for Simple calculator using switch statement.

#include<stdio.h>

Nisha S K, Dept. of ECE, SVIT Page 34


Module-2: Decision control and looping statements

void main()
{
float num1, num2, result;
int num3, num4, result_Q, result_R,choice;
printf("Enter the value of num1: ");
scanf("%f",&num1);
printf("Enter the value of num2: ");
scanf("%f",&num2);
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Quotient & Remainder\n");
printf("6. Exit\n\n");
printf("Enter Your Choice (1-6) : ");
scanf("%d", &choice);
num3 = num1;
num4 = num2;
switch(choice)
{
case 1:
result = num1+num2;
printf("\nAddition of Two Numbers Result =%0.2f",result);
break;
case 2:
result = num1-num2;
printf("\nSubtraction of Two Numbers Result = %0.2f",result);
break;
case 3:
result = num1*num2;
printf("\nMultiplication of Two Numbers Result=%0.2f",result);
break;
case 4:
result = num1/num2;
printf("\nDivision of Two Numbers Result=%0.2f",result);
break;
case 5:
result_Q = num3 / num4; result_R = num3 % num4;

Nisha S K, Dept. of ECE, SVIT Page 35


Module-2: Decision control and looping statements

printf("\nQuotient of Two Numbers Result %d / %d = %d\n", num3,


num4, result_Q);
printf("\nRemainder of Two Numbers Result %d %% %d = %d\n", num3,
num4, result_R);
break;
case 6:
return 0;

default:
printf("\nWrong Choice!");
break;
}
printf("\n \n");
}

Result:

Enter the value of num1: 3


Enter the value of num2: 2
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Quotient & Remainder
6. Exit

Enter Your Choice (1-6) : 1


Addition of Two Numbers Result =5.00

*****End*****

Nisha S K, Dept. of ECE, SVIT Page 36

You might also like