0% found this document useful (0 votes)
10 views42 pages

Unit 3-Control Flow Lect 1

This document covers control flow in C programming, including decision-making statements like if, else-if, switch, and looping constructs such as while, do-while, and for loops. It provides syntax, examples, and practical applications for each control structure, along with explanations of break and continue statements. Additionally, it discusses the goto statement and provides various programming exercises to reinforce the concepts.

Uploaded by

adityavarpe69
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)
10 views42 pages

Unit 3-Control Flow Lect 1

This document covers control flow in C programming, including decision-making statements like if, else-if, switch, and looping constructs such as while, do-while, and for loops. It provides syntax, examples, and practical applications for each control structure, along with explanations of break and continue statements. Additionally, it discusses the goto statement and provides various programming exercises to reinforce the concepts.

Uploaded by

adityavarpe69
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/ 42

UNIT 3 : CONTROL FLOW

-Ujwala Wanaskar
CONTENTS:

Decision Making and Branching: Simple If Statement, If-Else, Else-


If, Switch Statement, goto Statement
Decision Making and Looping: While Statement, Do-While, For
Statement, Break and Continue
INTRODUCTION
Instructions of a program are executed either
Sequential manner
Branching
C language supports the following decision making statements.
if statement
switch statement
conditional operator
goto statement
DECISION MAKING WITH IF STATEMENT
Use to control flow of execution of statements Entry

Syntax: if(test expression)


Some examples:
Test expression ? False
1. if(Bank balance is low)
printf(“borrow money”);
2. if(Room is dark) True

printf(“put on lights”);
DIFFERENT FORMS OF IF STATEMENTS
1. simple if statement
2. if……else statement
3. Nested if…..else statement
4. else if ladder
SIMPLE IF STATEMENT

General form:
if(test expression)
{
Statement block;
}
Statement-x;
PROGRAM TO CHECK WHETHER TWO NUMBERS
ARE EQUAL OR NOT?
int main()
{
int num1,num2;
printf(“Enter any 2 numbers”);
scanf(“%d %d”,&num1,&num2);
if(num1==num2)
printf(“Two numbers are equal”);
return 0;
}
PROGRAM TO CHECK WHETHER THE WEIGHT OF A STUDENT IS LESS THAN
50KGS AND HEIGHT IS GREATER THAN 170CMS.
int main()
{
int wt,ht;
printf(“Enter Weight and height of a student”);
scanf(“%d %d”,&wt,&ht);
If(wt<50 && ht>170)
Printf(“You are inn………”);
Return 0;
}
THE IF……ELSE STATEMENT
REPRESENTATION USING FLOWCHART :
WAP TO FIND WHETHER A GIVEN NUMBER IS EVEN OR ODD
int main()
{
int num;
printf(“Enter any number”);
scanf(“%d”,&num);
If(num%2==0)
Printf(“Number is even”);
Else
Printf(“Number is odd”);
Return 0;
}
NESTING OF IF-ELSE STATEMENT
WRITE A PROGRAM IN C TO FIND A GREATEST NUMBER OUT OF THE THREE NUMBERS ENTERED BY
THE USER.

If(a>b) else
{ {
if(a>c) if(b>c)
printf(“a is greatest”); printf(“b is greatest”);
else else
printf(“”c is greatest”); printf(“c is greatest”);
} }
ELSE-IF LADDER
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
EXAMPLE :
#include<stdio.h> else if(number==100){
int main(){ printf("number is equal to 100");
int number=0; }
printf("enter a number:"); else{
scanf("%d",&number); printf("number is not equal to 10, 50 or 100");
if(number==10){
}
printf("number is equals to 10");
return 0;
}
}
else if(number==50){
printf("number is equal to 50");
}
YOU ARE WORKING ON AN E-COMMERCE WEBSITE. THE COMPANY HAS A SPECIAL OFFER WHERE:
IF A CUSTOMER BUYS MORE THAN 10 ITEMS OF A SINGLE PRODUCT, THEY GET A 5% DISCOUNT.
IF A CUSTOMER BUYS MORE THAN 50 ITEMS OF A SINGLE PRODUCT, THEY GET A 10% DISCOUNT.
#include <stdio.h> if(itemsPurchased > 10 && itemsPurchased <=
int main() { 50) {
int itemsPurchased = 25; // Fixed value for discountedPrice = totalPrice * 0.95; // 5%
this scenario discount
double originalPrice = 2.0; // Example price
per item printf("You get a 5%% discount! Total price
after discount: $%.2lf\n", discountedPrice);
double discountedPrice;
}

// Calculate the total price without discount if(itemsPurchased <= 10) {


double totalPrice = itemsPurchased * printf("No discount. Total price: $%.2lf\n",
originalPrice; totalPrice);
if(itemsPurchased > 50) { }
discountedPrice = totalPrice * 0.90; // 10%
discount return 0;
printf("You get a 10%% discount! Total price }
after discount: $%.2lf\n", discountedPrice);
}
TRY……….
WAP to find sum of digits of 2 digit number.
(ex. if number is 23,sum=5)

WAP to find sum of digits of 3 digit number.


(ex. if number is 323,sum=8)
BREAK STATEMENT:
•The break in C is a loop control statement that breaks out of the
loop when encountered.
•It can be used inside loops or switch statements to bring the control
out of the block.
•The break statement can only break out of a single loop at a time.
// C PROGRAM TO DEMONSTRATE BREAK STATEMENT WITH FOR
LOOP
#include <stdio.h> }
int main() else
{
printf("%d ", i);
// using break inside for loop to
terminate after 2 }
// iteration Return 0;
printf("break in for loop\n"); }
for (int i = 1; i < 5; i++) {
if (i == 3) {
break;
CONTINUE STATEMENT:
•The C continue statement resets program control to
the beginning of the loop when encountered.

•As a result, the current iteration of the loop gets skipped and the
control moves on to the next iteration.

•Statements after the continue statement in the loop are not


executed.
C PROGRAM TO EXPLAIN THE USE OF CONTINUE STATEMENT
#include <stdio.h>
int main()
{
// for loop to print 1 to 8
for (int i = 1; i <= 8; i++) {
// when i = 4, the iteration will be skipped
if (i == 4) {
continue;
}
printf("%d ", i);
}
Return 0;
}
SWITCH STATEMENT:
A Menu Driven program is a program that represents a menu of options to the user
and different actions are performed based on different options
SWITCH STATEMENT
The switch statement
selects one of many code blocks
to be executed:
Syntax:
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
IMPLEMENTATION STEPS
Initialize Variables and Display Menu: Declare variables for user choice and
other program-related data. Present the available choices on the menu to the
user.
Accept User’s Choice: Prompt the user to enter their choice and capture it
using input functions like scanf().
Utilize Switch-Case to Process Choice: Use the switch-case statement to
compare the user’s choice against the available options.
Perform Actions Accordingly: Write code within each case to perform the
specific action associated with the user’s choice.
Display Outputs: Provide meaningful outputs or messages based on the user’s
choice.
Handle Invalid Choices or Default Cases: Use the default case to handle
situations where the user’s choice doesn’t match any predefined cases.
EXAMPLE
int day = 4; case 4:
printf("Thursday");
switch (day) { break;
case 1: case 5:
printf("Monday"); printf("Friday");
break; break;
case 2: case 6:
printf("Tuesday"); printf("Saturday");
break; break;
case 3: case 7:
printf("Wednesday"); printf("Sunday");
break; break;
}
// Outputs "Thursday" (day 4)
EXAMPLE 1: LIBRARY MANAGEMENT SYSTEM
#include <stdio.h> case 2:
int main() { printf("Book borrowed successfully.\n");

int choice; break;

printf("Library Management System\n"); case 3:

printf("1. Add Book\n"); printf("Book returned. Thank you!\n");


break;
printf("2. Borrow Book\n");
default:
printf("3. Return Book\n");
printf("Invalid choice.\n");
printf("Enter your choice: ");
}
scanf("%d", &choice);
return 0;
switch (choice) {
}
case 1:
Output:
printf("Book added to the library.\n"); Library Management System
break; 1. Add Book
2. Borrow Book
3. Return Book
Enter your choice: 2
Book borrowed successfully.
EXAMPLE 2: COFFEE SHOP ORDER SYSTEM
#include <stdio.h> case 3:
int main() { printf("Cappuccino is ready. Enjoy!\n");
int choice; break;
printf("Coffee Shop Order System\n"); default:
printf("1. Espresso\n"); printf("Invalid choice.\n");
printf("2. Latte\n");
}
printf("3. Cappuccino\n");
return 0;
printf("Enter your choice: ");
}
scanf("%d", &choice);
switch (choice) {
case 1:
Output:
printf("Enjoy your Espresso!\n");
break;
Coffee Shop Order System
case 2: 1. Espresso
2. Latte
printf("Here's your Latte. Enjoy!\n"); 3. Cappuccino
Enter your choice: 3
break; Cappuccino is ready. Enjoy!
EXAMPLE 3: FILE MANAGEMENT UTILITY
#include <stdio.h> case 3:
int main() {
printf("Data written to the file.\n");
int choice;
break;
printf("File Management Utility\n");
printf("1. Create File\n"); default:
printf("2. Read File\n"); printf("Invalid choice.\n");
printf("3. Write to File\n"); }
printf("Enter your choice: "); return 0;
scanf("%d", &choice);
}
switch (choice) {
Output:
case 1:
printf("File created successfully.\n"); File Management Utility
break; 1. Create File
case 2: 2. Read File
3. Write to File
printf("File content: This is some data.\n"); Enter your choice: 2
break; File content: This is some data.
TRY………
WAP using switch to print the days in month entered by
user.
(ex. 5 -31 days)
GOTO STATEMENT
•The goto statement is known as jump statement in C.
•As the name suggests, goto is used to transfer the program control to a
predefined label.
•The goto statement can be used to repeat some part of the code for a particular condition.
•It can also be used to break the multiple loops which can't be done by using a single break
statement.
•However, using goto is avoided these days since it makes the program less readable and
complicated.
•Syntax :
goto label;
... .. ...
... .. ...
label:
statement;
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}
O/P:
O/P:
Enter the number whose table you want to print?10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100
while STATEMENT:
•A while loop is a loop that continues to run and execute a while statement as long as
a predetermined condition holds true.
•After each iteration, the loop checks that the condition remains true.
•If the condition is now false, the loop terminates.
•Flowchart of while loop in C
•Syntax:
•while(test condition)
{
Body of the loop
}
WAP TO PRINT NUMBERS FROM 0 TO 10 USING WHILE
LOOP
# include<stdio.h> Return 0;
Int main() }
{
Int i; O/P:0 1 2 3……..10
i=0;
While(i<=10)
{
Printf(“%d\t”,i);
i++;
}
WAP TO EVALUATE THE FOLLOWING EQUATION
USING WHILE LOOP

Y=xn
do while STATEMENT:
•The do/while loop is a variant of the while loop.
•This loop will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the condition
is true.
Syntax:
do {
// code block to be executed
}
while (condition);
WAP TO PRINT NUMBERS FROM 0 TO 10 USING DO
WHILE LOOP
# include<stdio.h> return 0;
Int main() }
{
int i; O/P:0 1 2 3……..10
i=0;
do
{
Printf(“%d\t”,i);
i++;
}while(i<=10);
TRY…
WAP in C to print sum of numbers from 1 to 10.
for LOOP:
•The for loop is an entry-controlled loop that executes the
statements till the given condition.
•All the elements (initialization, test condition, and increment) are
placed together to form a for loop inside the parenthesis with
the for keyword.
•Syntax:
•for (init; condition; increment)
•{
•statement(s);
•}
WAP TO PRINT NUMBERS FROM 0 TO 10 USING FOR
LOOP
# include<stdio.h>
Int main()
{
int i;
For(i=0;i<=10;i++)
{
Printf(“%d\t”,i);
}
Return 0;
}
TRY….
WAP in C to print all even numbers from 1 to 50 using for loop.
WAP to find factorial of a given number
WAP to Fibonacci series upto n terms.
WAP to find sum of digits of a number.
WAP to check number is palindrome or not(ex 121)
WAP to check number is Armstrong number or not (ex.
153=1*1*1+5*5*5+3*3*3,370,371,407)
WAP to check number is prime or not.

You might also like