POP Unit 2
POP Unit 2
PROGRAMMING IN C
22CS2ESPOP - UNIT 2
Prof. SNEHA S BAGALKOT
Assistant Professor, Dept. of CSE
UNIT – 2: Decision Control and Looping Statements
▪Introduction to Decision Control Statements
▪Nested Loops
▪Example Programs
Introduction to Decision Control Statements
• Programs seen till now were sequential in nature.
• In cases where we need to run only a selected set of statements
conditional processing helps.
• Helps to specify what statements to run what to skip.
• C supports two type of decision control statements:
▪Conditional type branching
▪Unconditional type branching
Conditional Branching Statements (if, if-else,
if-else-if, switch)
• Conditional branching statements help to jump from one part of the
program to another based on whether or not a condition is satisfied
or not.
▪if statement
▪if-else statement
▪if-else-if statement
▪switch statement
Branching Statements
Conditional branching statements
▪ if statement
▪ if-else statement
▪ if-else-if statement
▪ switch statement
if statement
• Simplest form of decision control statement
• Syntax:
#include<stdio.h>
int main()
int x=0;
if(x>0)
x++;
}
#include<stdio.h>
void main()
{
int x = 20;
int y = 18;
if (x > y)
{
printf("x is greater than y");
}
}
O/p: x is greater than y
Eg: Check if a person is eligible to vote
#include<stdio.h>
void main()
{
int age;
printf("Enter the age\n");
scanf("%d",&age);
if(age>18)
printf("You are eligible\n");
}
Cascade-if
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("Enter any key\n");
scanf("%c", &ch);
if(isalpha(ch)>0)
printf("User has entered a character\n");
if(isdigit(ch)>0)
printf("User has entered a digit\n");
if(ispunct(ch)>0)
printf("User has entered a punctuation mark \n");
if(isspace(ch)>0)
printf("User has entered a white space character\n");
}
if- else statement
• In case of if statement if the expression is true, a certain set of statements
are executed.
• If the expression of the if statement returns false, then we can guide the
compiler to execute a different set of statements using else.
• The expression is evaluated. If true, control is transferred to statement 1.
• If expression evaluates to false, control is transferred to statement 2.
• Either statement 1 or statement 2 will be executed but not both.
If-else statement
•Syntax:
• Example: to find largest of two numbers
#include<stdio.h>
main()
{
int a, b, large;
printf(“\n Enter the values of a and b:”);
scanf(“%d %d”, &a, &b);
if(a>b)
large=a;
else
large=b;
printf(“\n Large=%d”, large);
}
Eg: Check whether number is odd or even
#include<stdio.h>
void main()
{
int num;
printf("Enter the number\n");
scanf("%d", &num);
if(num%2==0)
printf("The number is even");
else
printf("The number is odd");
}
Eg: WAP to accept a character. If character is in
lower case, convert it to upper case and vice versa
#include<stdio.h>
void main(){
char ch;
printf("Enter any Alphabet\n");
scanf("%c",&ch);
if(ch>='A'&&ch<='Z'){
printf("The entered character is in upper case\n");
printf("In lower case it is %c", (ch+32));
}
else{
printf("The entered character is in lower case\n");
printf("In upper case it is %c", (ch-32));
}
}
Ref : Table of ASCII values
Ex: WAP to check if the entered
character is a vowel
#include<stdio.h>
void main(){
char ch;
printf("Enter a character\n");
scanf("%c", &ch);
if(ch=='a'||ch=='e'|| ch=='i'|| ch=='o'|| ch=='u'||ch=='A'||ch=='E'||
ch=='I'|| ch=='O'|| ch=='U')
printf("%c is a vowel\n", ch);
else
printf("%c is not a vowel\n",ch);
}
Eg: Profit or Loss
Eg: Pre-Increment, Post-Increment,
Pre-Decrement, Post-Decrement
Dangling Else Problem
• With nesting of if-else statements, we often encounter a problem known as
dangling else problem.
• This problem is created when there is no matching else for every if statement. In
such cases, C always pairs an else to the most recent unpaired if statement in the
current block.
Example:
if(a > b)
if(a > c)
printf(“a is greater than b and c\”);
else
printf(“a is not greater than b and c\n”);
Nested if… else statement
if( test condition 1)
{
if(test condition 2)
{
Statement 1;
}
else
{
Statement 2;
}
}
else
{
Statement 3;
}
Statement X;
C program to find largest of 3 numbers using nested if..else
void main()
{
int a=15,b=24,c=38;
if(a>b)
{
if(a>c)
{
printf("A is largest");
}
else
{
printf("C is largest");
}
}
else
{
if(b>c)
{
printf("B is largest");
}
else {
printf("C largest");
}
}
}
if-else-if statement
• Syntax:
if(test expression 1)
{
statement block 1;
}
else if(test expression 2)
{
statement block 2;
}
…
{
statement block x;
}
statement y;
Example: to test whether a number entered is positive, negative or equal to zero
#include<stdio.h>
main()
{
int num;
printf(“\nEnter any number:”);
scanf(“%d”,&num);
if(num==0)
printf(“the value is equal to zero”);
else if(num>0)
printf(“\n the number is positive”);
else
printf(“\n the number is negative”);
}
#include<stdio.h>
void main(){
int x, y;
printf("Enter two numbers\n");
scanf("%d%d", &x,&y);
if(x==y)
printf("The numbers are equal\n");
else if(x>y)
printf("%d is greater than %d", x, y);
else
printf("%d is lesser than %d", x, y);
}
Eg: Increment/Decrement Operator
Programs
▪ Write a C program to read an integer, check if its positive, if so increment
and print it.
▪ Write a C program to check if a given number is even or odd.
▪ Write a C program to read a character and check if it is a vowel or
consonant.
▪ Read 2 integers and check if they are equal or not.
▪ Check if given number is positive, negative or Zero.
▪ Find the largest of three integers.
Write a C program to read a character and
check if it is a vowel or consonant.
Read 2 integers and check if they are equal or not.
OUTPUT 1: OUTPUT 2:
Enter two numbers: 5 5 Enter two numbers: 2 8
5 and 5 are equal 2 and 8 are not equal
Write a C program to display the Grade as per the given table:
else if(marks>60 && marks<=70)
#include<stdio.h>
printf(“\n Grade is C”);
void main()
else if(marks>50 && marks<=60)
{
Marks Grade printf(“\n Grade is D”);
int marks;
> 90 O else if(marks>40 && marks<=50)
printf(“\n Enter the marks:”);
> 80 A printf(“\n Grade is E”);
scanf(“%d”, &marks);
> 70 B else
> 60 C
if(marks>90)
printf(“\n Grade is F”);
> 50 D printf(“\n Grade is O”);
}
> 40 E else if(marks>80 && marks<=90)
Else F printf(“\n Grade is A”);
OUTPUT:
else if(marks>70 && marks<=80)
Enter the marks: 70
printf(“\n Grade is B”);
Grade is C
Write a C program to simulate the Traffic signal.
OUTPUT:
Enter the colour of signal[r, y or g]: r
Red Signal: Stop
Enter a character: r
Lowercase letter
Enter a character: 6
Digit
Enter a character: #
Special character
PROGRAM
Bhagya
275
#include<stdio.h>
main()
{ // Program to print the day of the week
int num;
#include<stdio.h>
printf("\n Enter any number : ");
int main()
scanf("%d", &num);
{
if(num==0)
int day;
printf("\n The value is equal to zero");
printf(“\n Enter any number from 1 to 7 : “);
else if(num>0)
scanf(“%d”,&day);
printf("\n The number is positive");
switch(day)
else
{
printf("\n The number is negative");
case 1: printf(“\n SUNDAY”); break;
case 2 : printf(“\n MONDAY”); break;
}
case 3 : printf(“\n TUESDAY”); break;
case 4 : printf(“\n WEDNESDAY”); break;
case 5 : printf(“\n THURSDAY”); break;
case 6 : printf(“\n FRIDAY”); break;
case 7 : printf(“\n SATURDAY”); break;
default: printf(“\n Wrong Number”);
}
}
Comparison between the switch and if-else construct
Generalized switch statement Generalized if-else statement
switch(x) If(exp1)
{ {
case 1: // do this // do this
case 2: // do this }
case 3: // do this else if(exp2)
…….. {
default: // do this
// do this } else if(exp3)
} {
// do this
}
/*Write a program to demonstrate the use of /*Program to determine whether an entered character is a vowel or not.*/
switch statement without a break.*/
#include <stdio.h>
#include <stdio.h> int main()
main() {
{ char ch;
int option = 1; printf("\n Enter any character: ");
switch(option) scanf("%c", &ch);
{ switch(ch)
case 1: printf("\n In case 1"); {
case 2: printf("\n In case 2"); case 'A':
default: printf("\n In case default"); case 'a’: printf("\n % c is VOWEL", ch); break;
} case 'E':
return 0; case 'e’: printf("\n % c is VOWEL", ch); break;
} case 'I':
case 'i’: printf("\n % c is VOWEL", ch); break;
case 'O':
case 'o’: printf("\n % c is VOWEL", ch); break;
case 'U':
case 'u’: printf("\n % c is VOWEL", ch); break;
default: printf("%c is not a vowel", ch);
}
return 0;
}
Design and Develop a program to solve simple
computational problems using arithmetic
expressions and use of each operator leading to
simulation of a simple calculator.
Algorithm
Step 1: Start the program
Step 2: Read the two numbers and the operator
Step 3: Evaluate option based on the operator with case
statements
case ‘+’ : res = a + b
case ‘-’ : res = a - b
case ‘*’ : res = a * b
case ‘/’ : res = a / b
Step 4: if the entered case option is invalid code the print
“Wrong Choice”
Step 5: Print the res
Step 6: Stop the program
Flowchart
#include<stdio.h>
void main() case '/': if(b!=0)
{ res=a/b;
float a,b,res; else
char op; printf("Divide by zero error");
printf("Enter The Expression in form
of op1 operator op2\n"); break;
scanf("%f%c%f",&a,&op,&b);
switch(op)
{ default: printf("Illegal operator\n");
case '+': res = a + b; }
break; printf("Result is……\n");
case '-‘: res = a-b;
break; printf("%f%c%f=%f",a,op,b,res);
case '*‘: res = a*b; }
break;
OUTPUT
Enter The Expression in form of
op1 operator op2 :
4+5
Result is …….
4+5=9
Advantages of using a switch case statement
▪ Easy to debug
while (condition)
{
statement_block;
}
statement x;
While Loop
• A while loop in C programming
repeatedly executes a set of
statements as long as a given
condition is true
• When the condition is false the
loop will stop working
• SYNTAX:
while(expression)
{
Statements;
}
Program to print the numbers from 10 to
19
Output
#include <stdio.h>
int main () { value of a: 10
int a = 10; value of a: 11
while( a < 20 ) { value of a: 12
printf("value of a: %d\n", a); value of a: 13
a++; value of a: 14
} value of a: 15
return 0; value of a: 16
} value of a: 17
value of a: 18
value of a: 19
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 condition is
false).
● Test condition is enclosed in parentheses and followed by a semicolon.
● Statements in the statement block are enclosed within curly brackets.
● 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.
● Do-while loops are widely used to print a list of options for a menu-driven
program.
Do While Loop
Statement x
do
{ Update the condition expression
statement_block;
} while (condition); TRUE
Condition
statement y;
FALSE
Statement y
Program to print the value of a from 10 to 19
using do while
#include <stdio.h> value of a: 10
value of a: 11
int main () {
value of a: 12
int a = 10;
value of a: 13
do { value of a: 14
printf("value of a: %d\n", a); value of a: 15
a = a + 1; value of a: 16
}while( a < 20 ); value of a: 17
return 0; value of a: 18
value of a: 19
}
Program to demonstrate the use of while loop and do-while loop.
// Program to print numbers from 0 to 10 //Program to print numbers from 0-10
using while loop using do-while loop
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int i = 0; int i = 0;
while(i<=10) do
{ {
printf(“\n %d”, i); printf(“\n %d”, i);
i = i + 1; // condition updated i = i + 1;
} } while(i<=10);
} }
for loop
● For loop is used to repeat a task until a particular condition is true.
● Aka determinate or definite loop-programmer knows exactly how many times
the loop will repeat.
#include<stdio.h>
int main()
{
int i, n;
printf(“\n Enter the value of n :”);
scanf(“%d”, &n);
for(i=0; i<= n; i++)
printf(“\n %d”, i);
}
Examples
1. for(i=1; i<=3;i++)
{ 2. for(i=0; i<5;i++)
printf(“Welcome\n”); {
} printf(“%d\t”,i);
printf(“This is CSE”); }
Output: Output:
Welcome 0 1 2 3 4
Welcome
Welcome
This is CSE
3. for(i=5; i>0;i--)
{
printf(“%d\t”,i); 5. for(i=0; i<5;i++);
} {
Output: printf(“Hello\n”);
5 4 3 2 1
}
4. for(; ;) Output:
{ Nothing is printed
printf(“Infinite Loop\n”); Since there is a semicolon
} at the end of the loop
Prints “Infinite Loop” infinitely
without halting
Selecting an appropriate loop
Entry-controlled(Pre-test) Exit-controlled(Post-test)
Condition is tested before the Condition is tested after the
loop starts. loop is executed.
If the condition is not met, thenThe body of the loop is
loop will never execute. executed unconditionally for
the first time.
Can use either for or while loop Can use do-while.
Selecting an appropriate loop
Output: 1 2 3 4 6 7 8 9 10
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 (:).
• Label is placed immediately before the statement where the control has to be
transferred.
• 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 often combined with the if statement to cause a conditional transfer of
control.
Write a C program to find sum of 10
natural numbers using goto
#include<stdio.h>
void main()
{ Output :
int sum=0,i=0; Sum= 55
top : sum= sum+i;
i++;
if(i<=10)
goto top;
printf("sum = %d",sum);
}
Goto Statement (Contd..)
Example: Program to calculate the sum of all +ve nos. entered by the user.
#include<stdio.h>
int main() {
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);
return 0;
}
Example Programs
Write a program to demonstrate menu
based calculator using switch
#include<stdio.h>
case 3: product=a*b;
void main() printf("product of %d and %d is %d",a,b,product);
{ break;
int a ,b,choice,sum,diff,product,q,r; case 4: if(b==0)
printf("Welcome \n 1. ADDITION \n 2.SUBTRACTION \n {
3.MULTIPLICATION \n 4.DIVISION \n "); printf("division by zero not possible");
printf("Enter your choice :"); }
scanf("%d",&choice); else
{
printf("enter the two operands");
q=a/b;
scanf("%d%d",&a,&b);
r=a%b;
switch(choice) printf("Quotient when %d divided by %d is %d",a,b,q);
{ printf("\n Remainder when %d divided by %d is
case 1: sum=a+b; %d",a,b,r);
printf("Sum of %d and %d is %d",a,b,sum); }
break;
break;
}
case 2: diff=a-b; }
printf("Difference between %d and %d is %d",a,b,diff);
break;
Write a program to accept a name and print
the name for a specified number of times
#include<stdio.h>
void main()
{
char name[30]; enter name
int n ,i=0; jim
printf("enter name \n"); enter the number
scanf("%s",name); of times to print
printf("enter the number of times to print the name \n");
the name
scanf("%d",&n); 3
while(i<n) name is : jim
{ name is : jim
printf("name is : %s \n",name); name is : jim
i++;
}
}
Display all numbers in a given range of m to
n
// Using while loop
#include<stdio.h>
void main()
{
int m,n;
printf("Enter the value of m & n");
scanf("%d%d",&m,&n);
while(m<=n)
{
printf("\n %d",m);
m++;
}
}
Display all even numbers from a given range
of m to n
// Using while loop
#include<stdio.h>
void main()
{
int m,n;
printf("Enter the value of m & n");
scanf("%d%d",&m,&n);
while(m<=n)
{
if((m%2)==0)
printf("\n %d",m);
m++;
}
}
Compute and print the sum of natural
numbers from m to n
void main()
{
int m,n,sum=0;
printf("Enter the value of m & n");
scanf("%d%d",&m,&n);
while(m<=n)
{
sum=sum+m;
m++;
}
printf("sum is %d",sum);
}
Use do-while loop to print squares of first n
natural numbers
void main()
{
int n,i=1,s;
printf("enter n");
scanf("%d",&n);
do
{
s=i*i;
printf("\n square of %d is %d",i,s);
i++;
}while(i<=n);
}
Sample Output
C program to print the following pattern
*
**
***
****
*****
void main()
{
int i,j;
*
for(i=1;i<=5;i++)
**
{
***
printf("\n");
****
for(j=1;j<=i;j++) *****
printf("*");
}
}
Program to compute factorial of a given
number
void main()
{
int i, num,fact=1;
printf("Enter any number to calculate factorial: ");
scanf("%d", &num);
if(num==0)
fact=1;
else
{
for(i=1; i<=num; i++)
{
fact = fact * i;
}
}
printf("Factorial of %d = %d", num, fact);
}
C program to print reverse of a number
#include<stdio.h>
void main()
{
int num, reverse = 0,digit;
printf("Enter any number to find reverse: ");
scanf("%d", &num);
while(num != 0)
{
digit = num % 10;
reverse = (reverse * 10) + digit;
num /= 10;
}
printf("Reverse = %d", reverse);
}
Program to check if an entered number is
palindrome or not
if(rev == num)
void main()
{ {
int n, num, rev = 0; printf("%d is palindrome.", num);
printf("Enter any number to }
check palindrome: "); else
scanf("%d", &n); {
num=n; printf("%d is not palindrome.",
while(n != 0) num);
{ }
rev = (rev * 10) + (n % 10);
}
n /= 10;
}
Program to read a number and print the
sum of digits in a number (using while loop)
#include<stdio.h>
void main()
{
int n, sum=0, digit;
printf("Enter a number: ");
Output:
scanf("%d", &n);
Enter a number: 512
while(n != 0)
{ Sum = 8
digit = n % 10;
sum = sum + digit;
n = n / 10;
}
printf(“Sum=%d”,sum);
}
Check if given number is divisible by 3 or 5 or not
Print the number of days in the given month
#include<stdio.h>
void main()
{
int n;
printf("\n Enter a number for month[1 to 12]: ");
scanf("%d", &n);
if(n==4 || n==6 || n==9 || n==11)
printf("\n There are 30 days in the month");
else if (n==2)
printf("\n There are either 28 or 29 days in the month");
else if (n==1 || n==3 || n==5 || n==7 || n==8 || n==10 || n==12)
printf("\n There are 31 days in the month");
else
printf("\n Invalid Input");
}
Write a C program to find out if a triangle is equilateral or
isosceles given the 3 sides of the triangle. Use Logical
operator
Hint :
Eg :
#include<stdio.h>
#include<math.h>
void main()
{
int n,sum,d1,d2,d3; OUTPUT:
printf(“Enter the number \n"); Enter the number :
scanf("%d", &n); 153
d3= n%10; //Units digit Armstrong number
d2= (n/10)%10; //Tens digit
d1=n/100; //Hundreds digit
sum= pow(d1,3)+pow(d2,3)+pow(d3,3);
if(sum==n)
printf(“Armstrong number");
else
printf(" Not an armstrong number");
}
THANK
YOU