[go: up one dir, main page]

0% found this document useful (0 votes)
71 views78 pages

FOP Unit 3

This document discusses decision and loop control statements in C programming, specifically if, if-else, and nested if statements. It provides examples of using if statements to check conditions like voter eligibility, find the maximum of two numbers, and determine if a number is positive, negative, or zero. It also demonstrates if-else statements, if-else ladders, and nested if statements with examples like checking even/odd numbers and student grades. The key aspects covered are the syntax, flow, and use of if statements and their extensions to control program flow based on multiple conditional checks.

Uploaded by

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

FOP Unit 3

This document discusses decision and loop control statements in C programming, specifically if, if-else, and nested if statements. It provides examples of using if statements to check conditions like voter eligibility, find the maximum of two numbers, and determine if a number is positive, negative, or zero. It also demonstrates if-else statements, if-else ladders, and nested if statements with examples like checking even/odd numbers and student grades. The key aspects covered are the syntax, flow, and use of if statements and their extensions to control program flow based on multiple conditional checks.

Uploaded by

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

Fundamentals of Programming

UNIT 3

Decision and Loop Control

Prof. S.G. Lande


Decision statements in C -
• Decision making is about deciding the order of
execution of statements based on certain
conditions or repeat a group of statements
until certain specified conditions are met.
• Lets take an example of a program
#include <stdio.h>
void main()
{
int a , b , sum;
printf(“enter a and b “);
scanf(“%d %d”,&a,&b);
sum = a+b;
printf(“sum=%d”,sum);
getch();
}
Types
• If statement
• If – else
• if – else – if ladder
• Nested if
If statements
Syntax -

if(expression)
{
statement inside;
}
statement outside;
If statement flow diagram
Example programs of if statement

Q .1). Write a program to input user age and


check if he is eligible to vote in India or not. A
person in India is eligible to vote if he is 18+.
#include <stdio.h>
int main()
{
/* Variable declaration to store age */
int age;
/* Input age from user */
printf("Enter your age: ");
scanf("%d", &age);
/* Use relational operator to check age */
if(age >= 18)
{
/* If age is greater than or equal 18 years */
printf("You are eligible to vote in India.");
}
return 0;
}
OUTPUT -

Enter your age: 24


You are eligible to vote in India.
Q.2.) Write a C program to find maximum between two numbers?

Example -
Input
Input num1: 10
Input num2: 20
Output
Maximum = 20
Logic –

• Input two numbers from user. Store it in some


variable say num1 and num2.
• Check if(num1 > num2) then print num1 is
maximum.
• Check if(num2 > num1) then print num2 is
maximum.
• Check if(num1 == num2) then both the
numbers are equal.
#include <stdio.h>
int main()
{
int num1, num2;
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
if(num1 > num2)
{
printf("%d is maximum", num1);
}
if(num2 > num1)
{
printf("%d is maximum", num2);
}
if(num1 == num2)
{
printf("Both are equal");
}
return 0;
}
Q.3.) C program to check whether a number is positive, negative or zero?

• A number is said negative if it is less than 0


i.e. num < 0.
• A number is said positive if it is greater than 0
i.e. num > 0.
• Step by step logic to check negative, positive
or zero -

1) Input a number from user in some variable


say num.
2) Check if(num < 0), then number is negative.
3) Check if(num > 0), then number is positive.
4) Check if(num == 0), then number is zero.
#include <stdio.h>
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
if(num > 0)
{
printf("Number is POSITIVE");
}
if(num < 0)
{
printf("Number is NEGATIVE");
}
if(num == 0)
{
printf("Number is ZERO");
}
return 0;
}
OUTPUT -

Enter any number: 10


Number is POSITIVE
Q.4.) Write a C program check whether a number is even or odd?

• Logic to check even or odd


- A number exactly divisible by 2 leaving no
remainder, is known as even number.
- if any number modulo divided by 2 equals to
0 then, the number is even otherwise odd.
• Step by step descriptive logic to check whether a
number is even or odd.
1) Input a number from user. Store it in some
variable say num.
2) Check if number modulo division equal to 0 or
not i.e. if(num % 2 == 0) then the number is even
otherwise odd.

• Important Note: Do not confuse modulo division


operator % as percentage operator. There is no
percentage operator in C.
#include <stdio.h>
int main()
{
int num;
printf("Enter any number to check even or odd: ");
scanf("%d", &num);
if(num % 2 == 0)
{
printf("Number is Even.");
}
else
{
printf("Number is Odd.");
}
return 0;
}
OUTPUT –

Enter any number to check even or odd: 11

Number is Odd
If – else statements

• Simple if works as "if some condition is true


then do some tasks". It doesn't specifies what
to do if condition is false. 
• if...else statement is an extension of simple if.
• It works as "If some condition is true then, do
some task otherwise do some other task".
Syntax -

if(boolean expression)
{
// Body of if
// If expression is true then execute this
}
else
{
// Body of else
// If expression is false then execute this
}
Flowchart of if...else statement
Write a program to input two numbers from user. Print
maximum between both the given numbers?
#include <stdio.h>
int main()
{
int num1, num2;
printf("Enter two numbers: "); Output of the above program
scanf("%d%d", &num1, &num2);
if(num1 > num2) Enter two numbers: 10 20
{ Second number is maximum.
printf("First number is maximum.");
}
else
{
printf("Second number is maximum.");
}
return 0; }
Q) C program to check whether a number
is divisible by 5 and 11 or not?
•  Number is exactly divisible by some other
number if it gives 0 as remainder. To check if a
number is exactly divisible by some number we
need to test if it leaves 0 as remainder or not.
• C supports a modulo operator %, that evaluates
remainder on division of two operands. You can
use this to check if a number is exactly divisible
by some number or not.
• For example - if(8 % 2), if the given expression
evaluates 0, then 8 is exactly divisible by 2.
Step by step logic -
1)Input a number from user. Store it in some variable
say num.
2)To check divisibility with 5, check if(num % 5 ==
0) then num is divisible by 5.
3)To check divisibility with 11, check if(num % 11 ==
0) then num is divisible by 11.
4)Now combine the above two conditions using 
logical AND operator &&. To check divisibility with 5 and
11 both, check if((num % 5 == 0) && (num % 11 == 0)),
then number is divisible by both 5 and 11.
#include <stdio.h>
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
if((num % 5 == 0) && (num % 11 == 0))
{
printf("Number is divisible by 5 and 11");
}
else
{
printf("Number is not divisible by 5 and 11");
}
return 0;
}
Output -

Enter any number: 55


Number is divisible by 5 and 11
Ladder if...else...if statement

• if...else..if is an extension of if...else statement.


• It specifies "If some condition is true then
execute some task; otherwise if some other
condition is true, then execute some different
task; if none conditions are true then execute
some default task.“
• Simple if statement gives ability to execute
tasks based on some condition. 
• Its extension if...else takes both sides of the
condition and execute some statements if
conditions is true or if the condition
is false then, execute some other statement.
Syntax -
if (boolean_expression_1)
{
// If expression 1 is true then execute
// this and skip other if
}

else if (boolean_expression_2)
{
// If expression 1 is false and
// expression 2 is true then execute
// this and skip other if
}
else if (boolean_expression_n)
{
// If expression 1 is false,
// expression 2 is also false,
// expression n-1 is also false,
// and expression n is true then execute
// this and skip else.
}

else
{
// If no expressions are true then
// execute this skipping all other.
}
Ladder if...else...if statement flowchart
 Write a simple C program to input an integer from user. Check if the given 
integer is negative, zero or positive?

#include <stdio.h>
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
if(num < 0)
{
printf("NUMBER IS NEGATIVE.");
}
else if(num == 0)
{
printf("NUMBER IS ZERO.");
}
else
{
printf("NUMBER IS POSITIVE.");
}
return 0;
}
Output of the above program -

Enter any number: -22


NUMBER IS NEGATIVE.
C program which display the grade of student using else
if ladder ?
#include<stdio.h>
int main()

 int marks;
    printf("Enter the marks of a student:\n");
    scanf("%d",&marks);
if(marks <=100 && marks >= 90)      
printf("Grade=A");  
 else if(marks < 90 && marks>= 80)
      printf("Grade=B");
else if(marks < 80 && marks >= 70)      
printf("Grade=C");
else if(marks < 70 && marks >= 60)    
  printf("Grade=D");  
 else if(marks < 60 && marks > 50)      
printf("Grade=E");  
 else if(marks == 50)  
    printf("Grade=F");  
 else if(marks < 50 && marks >= 0)
      printf("Fail");
 else    
  printf("Enter a valid score between 0 and 100");
   return 0;
}
OUTPUT –

Run 1:
Enter the marks of a student:78
Grade=C
Run 2:
Enter the marks of a student:98
Grade=A
Nested if…else statement in C

• Nested if...else statements has ability to control program


flow based on multiple levels of condition.
• Consider a situation, where you want to execute a
statement based on multiple levels of condition check.
• For example –
At airport there are multi-levels of checking before boarding.
First you go for basic security check, then ticket check. If you
have valid ticket, then you go for passport check. If you have
valid passport, then again you will go for security check. If all
these steps are completed successfully, then only you can
board otherwise actions are taken by the authority.
Syntax of nested if...else statement
if (boolean_expression_1)
{
if(nested_expression_1)
{
// If boolean_expression_1 and
// nested_expression_1 both are true
}
else
{
// If boolean_expression_1 is true
// but nested_expression_1 is false
}
// If boolean_expression_1 is true
}
else
{
if(nested_expression_2)
{
// If boolean_expression_1 is false
// but nested_expression_2 is true
}
else
{
// If both boolean_expression_1 and
// nested_expression_2 is false
}
// If boolean_expression_1 is false
}
Flowchart of nested if...else statement
Write a program to input three numbers from user. Find
maximum between given three numbers?
#include <stdio.h>
int main()
{
int num1, num2, num3;
printf("Enter three numbers: ");
scanf("%d%d%d", &num1, &num2, &num3);
if(num1 > num2)
{
if(num1 > num3)
{
printf("Num1 is max.");
}
else
{
printf("Num3 is max.");
}
}
else
{
if(num2 > num3)
{
printf("Num2 is max.");
}
else
{
printf("Num3 is max."); Output of the above program –
}
Enter three numbers-
}
10
return 0; 20
} 30

Num3 is max
Logic of the program -

• Suppose user inputs three numbers as num1=10, num2=20 and num3=30.

• .The first outer if condition if(num1 > num2) is false since 10 > 20 is false.
Hence, outer if statement is skipped, executing the outer else part.

• Inside the outer else, condition if(num2 > num3) is also false, since 20 > 30
is false. Hence, the inner if statement is skipped, executing inner else part.

• Inside the inner else there is nothing much to do. Just a simple printf()
statement, printing "Num3 is max."
Switch case statement in C

• Switch case statement gives ability to make decisions from fixed


available choices. Rather making decision based on conditions.
• Using switch we can write a more clean and optimal code, that
take decisions from available choices.
• For example –
- Select a laptop from available models
- Select a menu from available menu list etc.
Syntax of switch...case statement
switch(expression)
{
case 1:
/* Statement/s */
break;
case 2:
/* Statement/s */
break;
case n:
/* Statement/s */
break;
default:
/* Statement/s */
}
Rules for working with switch case

• Expression inside switch must evaluate to integer, character or constant.


switch...case only works with integral, character or constant.
• The case keyword must follow one constant of type evaluated by expression.
The case along with a constant value is known as switch label.
• You can have any number of cases.
• Each and every case must be distinct from other. For example, it is illegal to
write two case 1 label.
• You are free to put cases in any order. However, it is recommended to put
them in ascending order. It increases program readability.
• You can have any number of statement for a specific case.
• The break statement is optional. It transfers program flow outside
of switch...case. 
• The default case is optional. It works like an else block. If no cases are
matched then the control is transferred to default block.
Flow chart of switch case statement
Write a C program to input week number from user and
print the corresponding day name of week?
#include <stdio.h>
int main()
{
int week;
printf("Enter week number (1-7): ");
scanf("%d", &week);

switch(week)
{
case 1:
printf("Its Monday.\n");
printf("Its a busy day.");
break;
case 2:
printf("Its Tuesday.");
break;
case 3:
printf("Its Wednesday.");
break;
case 4:
printf("Its Thursday.\n");
printf("Feeling bit relaxed.");
break;
case 5:
printf("Its Friday.");
break;
case 6:
printf("Its Saturday.\n");
printf("It is weekend.");
break;
case 7:
printf("Its Sunday.\n");
printf(" Its holiday.");
break;

default:
printf(" Please enter week number between 1-7.");

}
return 0;
}

Enter week number (1-7) = 6


Its Saturday
It is weekend
Program to print number of days in month
using switch...case?

Step by step descriptive logic to print number of days in a month


using switch case

1) Input month number from user. Store it in some variable say month.


2) Switch the value of month i.e. switch(month) and match with cases.
3) There can be 12 possible values (choices) of month i.e. from 1 to 12. Hence,
write 12 cases inside switch and one default case as else block.
4) Print 31 for case 1, 3, 5, 7, 8, 10, 12.
5) Print 30 for case 4, 6, 9, 11.
6) Print 28/29 for case 2.
7) Print invalid input for default case.
Program to print number of days in month using switch...case?

#include <stdio.h>
int main()
{
int month;
printf("Enter month number(1-12): ");
scanf("%d", &month);

switch(month)
{
case 1:
printf("31 days");
break;
case 2:
printf("28/29 days");
break;
case 3:
printf("31 days");
break;
case 4:
printf("30 days");
break;
case 5:
printf("31 days");
break;
case 6:
printf("30 days");
break;
case 7:
printf("31 days");
break;
case 8:
printf("31 days");
break;
case 9:
printf("30 days");
break;
case 10:
printf("31 days");
break;
case 11:
printf("30 days");
break;
case 12:
printf("31 days");
break;
default:
printf("Invalid input! Please enter month number between 1-12");
}
return 0;
}
What is loop and why to use loops ?
• In real life we come across situations when we need to perform a set of
task repeatedly till some condition is met.
• For example - sending email to all employees, deleting all files, printing
1000 pages of a document. All of these tasks are performed in loop. To do
such task C supports looping control statements.
• In programming, a loop is used to repeat a block of code until the
specified condition is met.
• C programming has three types of loops:-
1) for loop
2) while loop
3) do...while loop
For loop in C programming

• Syntax of for loop

for(variable-initialization ; condition ; variable-update)


{
// Body of for loop
}
• Parts of for loop
• Variable-initialization contain loop counter variable
initialization statements. It define starting point of the
repetition (where to start loop).
• Condition contain boolean expressions and works like if...else. If
boolean expression is true, then execute body of loop
otherwise terminate the loop.
• Body of loop specify what to repeat. It contain set of
statements to repeat.
• Variable-update contains loop counter update (
increment/decrement) statements.
How for loop works?
• Initially variable-initialization block receive program control. It is non-
repeatable part and executed only once throughout the execution
of for loop. After initialization program control is transferred to loop
condition.
• The loop condition block evaluates all boolean expression and determines
loop should continue or not. If loop conditions are met, then it transfers
program control to body of loop otherwise terminate the loop. In C we
specify a boolean expression using relational and logical operator.
• Body of loop execute a set of statements. After executing all statements it
transfer program control to variable-update block.
• Variable-update block updates loop counter variable and transfer program
control again back to condition block of loop.
Flowchart of for loop
Write a C program to print natural numbers from 1 to 10?
#include <stdio.h>
int main()
{
int count;
for(count=1; count<=10; count++)
{
printf("%d ", count);
}
return 0;
}

Output
1 2 3 4 5 6 7 8 9 10
C program to print all Odd numbers from 1 to n?
#include <stdio.h> short hand assignment operator
int main() i+=2 means i = i+2
{
int i, n;
printf("Print odd numbers till: ");
scanf("%d", &n);
printf("All odd numbers from 1 to %d are: \n", n);

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


{
printf("%d\n", i);
}
return 0;
}
While loop in C programming
Syntax of while loop

while(condition)
{
// Body of while loop
}
Parts of while loop

Unlike for loop, while does not contain initialization and update part. It


contains only two parts - condition and body of loop.

• condition is a boolean expression evaluating an integer value. It is similar to 


if...else condition and define loop termination condition.
• Body of loop contains single or set of statements. It define statements to
repeat.
How while loop works?
• Initially program control is received by condition block. It contains set
of relational and logical expressions .
- If result of the conditional expression is 1 (true) then while transfers
program control to body of loop.
- Else if result of conditional expression is 0 (false) then it exits from loop.

• Body of loop contain single or set of statements to repeat. It execute all


statements inside its body and transfer the program control to
loop condition block.

• Step 1 and 2 are repeated until the loop condition is met.


• The above two steps are repeated, until loop condition is true.
Flowchart of while loop
C program to print natural numbers using while loop ?
#include <stdio.h>
int main()
{
int n = 1;
while(n <= 10)
{
printf("%d ", n);
n++;
}
return 0;
}
Output -
1 2 3 4 5 6 7 8 9 10
Do…while loop in C programming

Syntax of do...while loop –

do
{
// Body of do while loop
} while (condition);
Flowchart of do...while loop
C program to print natural numbers using do while
loop?
#include <stdio.h>
int main()
{
int n=1;

do
{
printf("%d ", n);
n++;
} while(n <= 10);
return 0;
}
OUTPUT -
1 2 3 4 5 6 7 8 9 10
Jump statements in C
Types of jump statements in C language –
1) break statement
2) continue statement

• break is jump statement used to terminate a switch or loop on some


desired condition. On execution, it immediately transfer program control
outside the body of loop or switch.
 break ;

• continue is a jump statement used inside loop. It skips loop body and
continues to next iteration. continue statement on execution immediately
transfers program control from loop body to next part of the loop. It works
opposite of break statement.
 continue ;
How to use break statement
You must follow some rules while using break statement.

• You must write break statement inside a loop or switch. Use of break
keyword outside the switch or loop will result in compilation error.
• break statement is generally used with condition(if statements) inside
loop.
• In case of nested loop or switch, break only terminates the innermost loop
or switch.
• Use of break inside switch...case will transfer the program control outside
the switch.
• break statement only terminate program control from nearest matched
loop or switch.
How break statement works inside a switch case –

How break statement work inside a for loop -


How to use continue statement
Rules to use continue statement in C programming.

• You must use continue keyword inside a loop. Use of continue outside
loop will result in compilation error .
• continue is not used with switch...case statement.
• In case of nested loop, continue will continue next iteration of nearest
loop.
• Do not confuse that continue transfer program control to loop condition.
It transfer program control to next part of the loop.
• Use of continue statement without condition is worthless. Hence it is
often used with if statements.
How continue statement works with for loop –

How to use continue statement with while loop -

You might also like