0% found this document useful (0 votes)
18 views53 pages

Structured Programming in C Language

The document provides an overview of control structures in C programming, focusing on branching statements such as if, if-else, and switch statements. It explains how these structures alter the flow of execution based on conditions, including one-way, two-way, and multi-way decisions. Additionally, it includes examples and syntax for implementing these control structures in programs.

Uploaded by

nanditasingh1709
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)
18 views53 pages

Structured Programming in C Language

The document provides an overview of control structures in C programming, focusing on branching statements such as if, if-else, and switch statements. It explains how these structures alter the flow of execution based on conditions, including one-way, two-way, and multi-way decisions. Additionally, it includes examples and syntax for implementing these control structures in programs.

Uploaded by

nanditasingh1709
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/ 53

Structured Programming using C

Unit 3: Control Structures


Control Structures, Branching
Statement – If-else
Control Structure

▪ A program is usually not limited to a linear sequence of


instructions.

▪ During its process it may bifurcate, repeat code or take decisions.

▪ C provides control structures that serve to specify what has to be


done by the program, when and under which circumstances.

▪ Control structures are used to alter the flow of execution of the


program.

3 Control Structure - Branching: if, if..else


Control Statements/Constructs in ‘C’

Program Control
Statements/Constructs

Selection/Branching Iteration/Looping

do-
Conditional Unconditional for while
while
Type Type

if- if-
if switch
else else-
if
break continue goto

4 Control Structure - Branching: if, if..else


Operators Used in Control Statements

<
! >

!= ==
Operators
<=
||
>=
&& !=

5 Control Structure - Branching: if, if..else


Selection Structure or Decision Making
• Selection Statements
– One-way decisions using if statement

– Two-way decisions using if-else statement

– Multi-way decisions USING if-else-if ladder

– Nested if-else

• The switch Statement

6 Control Structure - Branching: if, if..else


if Statement
▪ To run a block of code only when a certain condition is met.
▪ For example, assigning grades (A, B, C) based on marks obtained by a
student.
- if the percentage is above 90, assign grade A
- if the percentage is above 75, assign grade B
- if the percentage is above 65, assign grade C
▪ Syntax :
if (condition)
{ // body of if statement }
▪ Explanation : The if statement evaluates the condition inside the
parentheses ( ).
- If the condition evaluates to true, the code inside the body of if is
executed.
- If the condition evaluates to false, the code inside the body of if is
skipped.

7 Control Structure - Branching: if, if..else


Working of if Statement

8 Control Structure - Branching: if, if..else


One-way decisions using if statement

• Flowchart

T F
TestEx
pr

stmtT

9 Control Structure - Branching: if, if..else


Program to Demonstrate if Statement
Q. Write an algorithm and program to print the largest among three numbers.

1. Start
2. Print “Enter three numbers”
3. Input A, B, C
4. Max=A
5. If B>Max Then Max=B
6. If C>Max Then Max=C
7. Print “Largest number is”, Max
8. Stop

10 Control Structure - Branching: if, if..else


Program to Demonstrate if Statement (cont..)
#include <stdio.h> if(c>max)
#include<conio.h> {
max=c;
void main()
}
{ printf(“Largest No is %d”, max);
int a, b, c, max; getch();
printf(“\nEnter 3 numbers”); }
scanf(“%d %d %d”, &a, &b, &c);
max=a; Output:
if(b>max) Enter 3 numbers
{ 10
12
max=b;
5
} Largest No is 12

11 Control Structure - Branching: if, if..else


if .. else Statement
▪ The if statement can have an optional else clause.
▪ Syntax :
if (condition)
{ // block of code if condition is true }
else
{ // block of code if condition is false }
▪ Explanation : The if statement evaluates the condition inside the
parentheses ( ).
- If the condition evaluates to true, the code inside the body
of if is executed
and else block is skipped from execution.
- If the condition evaluates to false, the code inside the body
of else is executed
and if block is skipped from execution.

12 Control Structure - Branching: if, if..else


Working of if..else Statement

13 Control Structure - Branching: if, if..else


Two-way decisions using if..else statement

• Flowchart

T F
TestEx
pr

stmtT stmtF

14 Control Structure - Branching: if, if..else


Program to Demonstrate if…else Statement
#include<stdio.h> if(c>max)
#include<conio.h> {
void main() max=c;
{ }
int a, b, c, max; else
printf("\nEnter 3 numbers"); {
scanf("%d %d %d", &a, &b, max=max;
&c); }
if(b>a) printf("Largest No is %d", max);
{ getch();
max=b; }
} Output:
else Enter 3 numbers
10
{
12
max=a; 5
} Largest No is 12

15 Control Structure - Branching: if, if..else


Program 1: (Exp-2)
Q. Write a program to check given number is even or Output:
odd. Enter any number
#include <stdio.h> 10
void main() 10 is EVEN number
{
int a ;
printf(“\nEnter any number”);
Enter any number
scanf(“%d”, &a); 13
if(a%2==0) 13 is ODD number
{
printf(“%d is EVEN number”,a);
}
else
{
printf(“%d is ODD number”,a);
}
}

16 Control Structure - Branching: if, if..else


Program 2 : (Exp-3)
Q. WAP to check whether the year entered is Output:
leap year or not.
#include<stdio.h> Enter year 2020
#include<conio.h> 2020 is leap year
void main ()
{
int year;
clrscr(); Enter year 2015
printf(“Enter year”); 2015 is not leap year
scanf(“%d”, &year);
if(year%4==0)
printf(“%d is leap year\n“, year);
else
printf(“%d is not leap year\n“, year);
getch();
}

17 Control Structure - Branching: if, if..else


Practice Program

1. WAP to check whether the number entered is divisible by


10 or not.

2. WAP to find minimum number from given three numbers.

3. WAP to find maximum number from given two numbers.

18 Control Structure - Branching: if, if..else


Multiway Decision Statement
Multi-way Decision Statement

• When a series of decisions are involved we have to use


more than one if – else statement called as multiple if’s.

• if-else-if statement is also known as if-else-if ladder.

• It is used when there are more than two possible action


based on different conditions.

• Multiple if – else statements are much faster than a series


of if – else statements, since the if structure is exited when
any one of the condition is satisfied.

20 Multiway Decision Statement


if...else...else if Statement
• If we need to make a choice between more than two alternatives,
we can use the if...else if...else statement.
• Syntax :
if (condition1)
{ // code block 1 }
else if (condition2)
{ // code block 2 }
else { // code block 3 }
• Explanation :
- If condition1 evaluates to true, the code block 1 is executed.
- If condition1 evaluates to false, then condition2 is evaluated.
- If condition2 is true, the code block 2 is executed.
- If condition2 is false, the code block 3 is executed.

21 Multiway Decision Statement


Working of if...else...else if Statement

22 Multiway Decision Statement


Flowchart of if-else-if Construct
No
TestExpr

No
TestExpr2
Yes
No
Yes TestExpr3
stmtT1
No
stmtT2 Yes TestExprN

stmtT3 Yes stmt


TF
stmtTN

23 Multiway Decision Statement


Program 1 :
Q. Write a program to find largest from three else
numbers.
{
#include<stdio.h>
#include<conio.h> printf("Largest = %d", c);
void main() }
{ getch();
int a, b, c; }
printf("Enter three numbers: \n");
scanf("%d%d%d", &a, &b, &c);
if(a>b && a>c)
Output:
{
Enter three numbers:
printf("Largest = %d", a);
10
}
15
else if(b>a && b>c)
32
{
Largest= 32
printf("Largest = %d", b);
}
24 Multiway Decision Statement
Nested if-else
▪ Sometimes, we need to Construct 1 Construct 2
use an if statement if(TestExprA) if(TestExprA)
inside { { if(TestExprB)
another if statement. if(TestExprB) { stmtBT; }
This is known as {stmtBT;} else
nested if statement. else { stmtBF; }
▪ There is a first, {stmtBF;} }
outer if statement, and } else {
inside it is another, else if(TestExprC)
inner if statement i.e. { { stmtCT; }
multiple layers stmtAF; else
of if statements. } { stmtCF; }
▪ The syntax for the }
nested is given here:

25 Multiway Decision Statement


Program 1 :
Q. Write a program to find the largest among three numbers using the
nested loop.

26 Multiway Decision Statement


Program 1 : (cont..)
#include <stdio.h> else {
#include <conio.h> if(b > c)
void main() { printf(“Largest= %d”, b); }
{ else
int a, b, c; { printf(“Largest= %d”, c); }
printf(“\nEnter three }
numbers:\n”); getch();
scanf(“%d %d %d”, &a, &b, &c); }
if(a > b)
{ Output:
if(a > c) Enter three numbers:
{ printf(“Largest= %d”, a); } 45
15
else
32
{ printf(“Largest= %d”, c); }
Largest= 45
}

27 Multiway Decision Statement


Program 2 :
Q. WAP to find if an integer is even or odd or neither (0) using
nested if statements.
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
printf("Enter an integer: ");
scanf("%d",&num);
// outer if condition
if (num != 0)
{ // inner if condition
if ((num % 2) == 0)
{ printf("The number %d is even.", num); }
// inner else condition
else
{ printf("The number %d is odd.", num); } } // end of outer if

28 Multiway Decision Statement


Program 2 : (cont..)
// outer else condition
else
{
printf("The number %d is 0 and it is neither even nor odd.", num);
}
getch();
}

Output:
Enter an integer: 0
The number 0 is 0 and it is neither even nor odd.

Enter an integer: 24
The number 24 is even.

29 Multiway Decision Statement


Program 3 :
Q. WAP to implement arithmetic operations.
#include <stdio.h>
void main()
{
char operator;
int num1, num2, result;
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
if (operator == '+’)
{
result = num1 + num2;
printf("Result = %d\n", result);
}
else if (operator == '-’)
{
result = num1 - num2;
printf("Result = %d\n", result);
}
30 Multiway Decision Statement
Program 3 :
else if (operator == '*’)
{
result = num1 * num2;
printf("Result = %d\n", result);
}
else if (operator == '/’)
{
if (num2 != 0)
result = num1 / num2;
else
{
printf("Error! Division by zero is not allowed.\n");
}
printf("Result = %d\n", result);
}
else
{
printf("Invalid operator!\n");
}
getch();
}

31 Multiway Decision Statement


Summary of Decision Making Statement

• Decision making or branching statements are used to


select one path based on the result of the evaluated
expression.
• It is also called as control statements because it controls
the flow of execution of a program.
• We can also nest if-else within one another when multiple
paths have to be tested.
• The else-if ladder is used when we have to check various
ways based upon the result of the expression.

32 Multiway Decision Statement


Switch Case Statement
The Switch Statement
• The switch case statement is used when we have multiple
options and we need to perform a different task for each
option.
• The switch statement allows us to execute one code block
among many alternatives.
• The expression is evaluated once and compared with the
values of each case label. If there is a match, the
corresponding statements after the matching label are
executed.
• If there is no match, the default statements are executed.
• The syntax of the switch statement is much easier to read
and write.

34 switch case statement


Syntax for switch statement
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
...
default:
// default statements
}

35 switch case statement


Flowchart for switch statement
Flowchart

36 switch case statement


Few points to remember about the switch statement

• The switch expression must be of an integer or character type.


• The case value must be an integer or character constant.
• The expression provided in the switch should result in a
constant value otherwise it would not be valid.
• Duplicate case values are not allowed.
• Break statements are useful when you want your program-flow
to come out of the switch body.
• Whenever a break statement is encountered in the switch body,
the control comes out of the switch case statement.
• If we do not use break, all statements after the matching label
are executed.

37 switch case statement


Few pointes o remember about the switch statement

• The default statement is optional, if you don’t have a


default in the program, it would run just fine without any
issues.
• However it is a good practice to have a default statement
so that the default executes if no case is matched.

38 switch case statement


Program 1 : (Exp-7)
Q. Write a menu driven program to perform all arithmetic operations
based on user choice.
#include<stdio.h>
#include<conio.h>
void main()
{
int no1,no2,result,choice;
clrscr();
printf("Enter two numbers:");
scanf("%d %d",&no1,&no2);
printf("1.Add\n2.Subtract\n3.Multiply\n4.Divide\n5.Modulus\nEnter
your choice:");
scanf("%d", &choice);

39 switch case statement


Program 1 : (cont..)
switch(choice)
{
case 1: result=no1+no2;
printf(“ Sum= %d", result);
break;
case 2 : result=no1-no2;
printf("Difference= %d", result);
break;
case 3 : result=no1*no2;
printf("Product= %d", result);
break;

40 switch case statement


Program 1 : (cont..)
case 4: result=no1/no2; Output :
printf("Quotient= %d", result); Enter two numbers:4
7
break;
1.Add
case 5: result=no1%no2; 2.Subtract
printf("Remainder= %d", 3.Multiply
result); 4.Divide
break; 5.Modulus
Enter your choice:3
default : printf("Invalid choice");
Product= 28
} //end of switch
getch();
}

41 switch case statement


Program 2 :
Q. Write a program to print week day name using switch case.
#include <stdio.h>
#include <conio.h>
void main()
{
int day;
printf("Enter a number(1-7): ");
scanf("%d", &day);
switch(day)
{
case 1 : printf("Monday");
break;
case 2 : printf("Tuesday");
break;
case 3 : printf("Wednesday");
break;

42 switch case statement


Program 2 : (cont..)
case 4 : printf("Thursday");
break;
Output :
case 5 : printf("Friday"); Enter a number(1-7):
break; 5
case 6 : printf("Saturday"); Friday
break;
case 7 : printf("Sunday");
break;
default : printf("Invalid input! Please enter week number between 1-7.");
} //end of switch
getch();
}

43 switch case statement


switch vs nested if
 The switch differs from the else-if in that switch can test
only for equality, whereas the if conditional expression
can be of a test expression involving any type of
relational operators and/or logical operators.

 The switch statement can always be replaced with a


series of else-if statements.

44 switch case statement


Program 1 :
Q. Write a C program to input a character from user and
check whether the given character is alphabet or not
#include<stdio.h> Output :
#include<conio.h>
Enter any character: g
void main()
Character is an ALPHABET.
{
char ch;
printf("Enter any character: ");
scanf("%c", &ch);
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
printf("Character is an ALPHABET.");
else
printf("Character is NOT ALPHABET.");
getch(); }
45 Practice Programs
Program 2 :
Q. Write a C program to input cost price and selling price of a
product and check profit or loss.
#include<stdio.h>
#include<conio.h>
void main()
{
int cp,sp, amt;
clrscr();
printf("Enter cost price: ");
scanf("%d", &cp);
printf("Enter selling price: ");
scanf("%d", &sp);
if(sp > cp)
{ amt = sp - cp;
printf("Profit = %d", amt); }
46 Practice Programs
Program 2 : (cont..)
else if(cp > sp)
{ Output :
amt = cp - sp; Enter cost price: 5000
printf("Loss = %d", amt); Enter selling price: 8000
} Profit = 3000
else
{
printf("No Profit No Loss.");
}
getch();
}

47 Practice Programs
Program 3 :
Write a program to input basic salary of an employee and calculate
gross salary according to given conditions.
Basic Salary <= 10000 : HRA = 10%, DA = 80%
Basic Salary is between 10001 to 30000 : HRA = 20%, DA = 90%
Basic Salary >= 30001 : HRA = 30%, DA = 95%
#include <stdio.h>
#include<conio.h>
void main()
{
float basic, gross, da, hra;
clrscr();
printf("Enter basic salary of an employee: ");
scanf("%f", &basic);
if(basic <= 10000) {
da = basic * 0.8;
hra = basic * 0.1;
}
48 Practice Programs
Program 3 : (cont..)
else if(basic <= 30000)
{ Output :
da = basic * 0.9; Enter basic salary of an employee: 10000
hra = basic * 0.2; GROSS SALARY OF EMPLOYEE = 19000.000000
}
else
{
da = basic * 0.95;
hra = basic * 0.3;
}
gross = basic + hra + da;
printf("GROSS SALARY OF EMPLOYEE = %f",
gross);
getch();
}

49 Practice Programs
Program 4 :
Q. Write a program to input an alphabet and check whether it is vowel or
consonant using switch case. case 'u‘ :
#include <stdio.h> case 'A‘ :
#include <conio.h>
case 'E‘ :
void main()
{
case 'I‘ :
char ch; case 'O‘ :
printf("Enter any character: "); case 'U‘ : printf("Vowel");
ch=getchar(); // reads char input break;
switch(ch) default:
{ printf("Consonant");
case 'a‘ : }
case 'e‘ : getch();
case 'i‘ : }Output:
case 'o‘ :
Enter any character: g
Consonant
50 Practice Programs
Program 5 :
Q. Write a program to display grade of a student base on marks.
Grade A : 80-100 , Grade B: 60-79, Grade C : 40-59 Fail: 0-39
#include<stdio.h>
void main()
{
int marks, n;
printf("\nEnter The Marks Between 0 To 100:");
printf("\nEnter The Mark: ");
scanf("%d", &marks);
n=marks/10;
switch(n)
{
case 10 :
case 9 :
case 8 : printf("\n Your Grade is: A");
break;

51 Lecture No: 15: Practice Programs


Program 5 : (cont..)
case 7 :
case 6 : printf("\n Your Grade is: B" );
break;
case 5 : Output :
case 4 : printf("\n Your Grade is: C" ); Enter The Marks Between 0 To 100:
break; Enter The Mark: 89
case 3 : Your Grade is: A
case 2 :
case 1 :
case 0 : printf("\n Your Grade is: F or
Fail\n");
break;
default : printf("\n Enter proper marks \n");
}
getch();
}

52 Lecture No: 15: Practice Programs


Thank
You

You might also like