[go: up one dir, main page]

0% found this document useful (0 votes)
12 views58 pages

Unit 3

The document discusses control flow statements in C programming, specifically focusing on iterative and conditional statements. It provides detailed explanations and examples of various types of loops, including for, while, and do-while loops, along with algorithms and C code snippets for practical applications. Additionally, it covers decision-making structures like if-else statements and includes examples for displaying natural numbers, calculating factorials, and generating multiplication tables.

Uploaded by

nayna sawant
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)
12 views58 pages

Unit 3

The document discusses control flow statements in C programming, specifically focusing on iterative and conditional statements. It provides detailed explanations and examples of various types of loops, including for, while, and do-while loops, along with algorithms and C code snippets for practical applications. Additionally, it covers decision-making structures like if-else statements and includes examples for displaying natural numbers, calculating factorials, and generating multiplication tables.

Uploaded by

nayna sawant
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/ 58

Control

CONTROL Flow
FLOW
Control Flow
Unit-3
UNIT-3
Computer DEPARTMENT
COMPUTER Department
• In Programming we need to sometimes control the flow of
operation other than just the sequential statements.in this
case we need the control flow statements.
• Control Statements are Classified into two types:
1)Iterative Statements
2)Conditional Statements
1)Iterative statements (also known as loops) in C allow you to
repeatedly execute a block of code as long as a specified
condition remains true. There are three types of iterative
statements in C:
a.for Loop
b.while Loop
c.do-while Loop
• 1. for Loop
• The for loop is commonly used when the number of iterations
is known in advance. It is a compact and versatile control
structure, allowing initialization, condition-checking, and
incrementing/decrementing to be handled in one line.
• Syntax:
for (initialization; condition; increment/decrement)
{
// Code to be executed
}
• The initialization statements are executed first.
• The Second step is checking the Condition
specified.
• The third step is to execute all the statements
inside the curly braces.
• The fourth step is the increment/decrement
or updating operations.
• Finally the control goes back to the second
step.
• Algorithm to Display the Word "Computer" Five
Times Using a for Loop:
• Start
• Initialize a loop control variable i to 0.
• Set the condition to repeat the loop while i < 5.
• Inside the loop, display the word "Computer".
• Increment the value of i by 1 after each iteration.
• Repeat steps 3–5 until the condition i < 5 becomes
false.
• End the program.
Flowchart:
flowchart for displaying the word "Computer" five
times using a for loop:
Start
Initialize i = 0
Check i < 5
If true, go to step 4.
If false, go to step 6.
Print "Computer"
Increment i = i + 1, then go back to step 3.
End
• C Program to Display the Word "Computer" Five
Times Using a for Loop:
• #include <stdio.h>

• int main() {
• // For loop to repeat 5 times
• for (int i = 0; i < 5; i++) {
• printf("Computer\n");
• }

• return 0;
• }
• Explanation:
• Initialization: int i = 0; initializes the loop variable i to 0.
• Condition: The loop runs as long as i < 5.
• Increment: After each iteration, i is incremented by 1 using i+
+.
• The printf("Computer\n"); statement prints "Computer"
during each iteration.
• Output:
• Computer
• Computer
• Computer
• Computer
• Computer
• write a program to display the first ten natural
numbers
• Algorithm to Display the First Ten Natural Numbers:
• Start
• Initialize a variable i to 1.
• Set condition: Check if i <= 10.
– If true, go to step 4.
– If false, go to step 6.
• Print the value of i.
• Increment i by 1 (i.e., i = i + 1) and go back to step 3.
• End the program.
• Flowchart to Display the First Ten Natural Numbers:
• Here’s a description of the flowchart:
• Start
• Initialize i = 1
• Check condition: Is i <= 10?
– If true, go to step 4.
– If false, go to step 6.
• Print the value of i.
• Increment i = i + 1, and go back to step 3.
• End
• C Program to Display the First Ten Natural Numbers:
#include <stdio.h>

int main() {
// Loop to print the first 10 natural numbers
for (int i = 1; i <= 10; i++) {
printf("%d\n", i); // Print the value of i
}

return 0;
}
• Explanation:
• The for loop starts from i = 1 (the first natural number) and runs
until i <= 10.
• Each iteration prints the current value of i and increments i by 1 .
• Output:
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• write a program to display the first n natural
numbers ,where the value of n is taken from user:
Algorithm to Display the First n Natural Numbers (Where n
is Taken from the User):
1.Start
2.Declare an integer variable n to store the user's input.
3.Prompt the user to enter the value of n.
4.Read the value of n from the user.
5.Initialize a variable i to 1.
6.Set condition: Check if i <= n.
If true, go to step 7.
If false, go to step 9.
7.Print the value of i.
8.Increment i by 1 (i.e., i = i + 1), and go back to step 6.
9.End the program.
• write a program to find the factorial of a
number,
• Algorithm to Find the Factorial of a Number
• Start.
• Input: Read a number n from the user.
• Initialize: Set factorial = 1.
• Loop: For each integer i from 1 to n, multiply factorial
by i.
• Output: Display the value of factorial.
• End.
Void main()
{
int i,n, fact;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&n);
for(i=1;fact=1;i<=n;i++)
{
Fact=fact*i;
}
printf(“Factorial of this number is:%d\n”,fact);
getch();
}
1. getch()
• Definition: getch() is a function from the conio.h (console
input-output) library.
• Purpose: It reads a single character from the keyboard but
does not display it on the screen. It is commonly used to
pause the execution of a program, allowing the user to press
any key before continuing.
2.clrscr()
• Definition: clrscr() is another function from conio.h.
• Purpose: It clears the console screen. This function was useful
in older compilers like Turbo C to clear the output screen.
• Algorithm to Display the Multiplication Table of a User-
Entered Number
• Start.
• Input: Read a number n from the user.
• Initialize: Set i = 1.
• Loop:
– While i is less than or equal to 10:
• Multiply n by i and display the result as n * i = result.
• Increment i by 1.
• End.
• C Program to Display the Multiplication Table of a User-
Entered Number
#include <stdio.h>
int main()
{
Int num, i; // Input the number from the user
printf("Enter a number: ");
scanf("%d", &num); // Display the multiplication table for the
entered number
printf("Multiplication table of %d:\n", num);
for(i = 1; i <= 10; i++)
{
printf("%d * %d = %d\n", num, i, num * i);
}
return 0;
}
• Explanation:
• Input: The user is prompted to enter a number.
• Loop: A for loop runs from 1 to 10. In each iteration, the
product of the entered number and the loop counter i is
calculated and displayed.
• Output: The program prints the multiplication table in the
format num * i = result.
• Example Output:
• Multiplication table of 5:
• 5*1=5
• 5 * 2 = 10
• 5 * 3 = 15
• 5 * 4 = 20
• 5 * 5 = 25
• 5 * 6 = 30
• 5 * 7 = 35
• 5 * 8 = 40
• 5 * 9 = 45
• 5 * 10 = 50
• Algorithm to Display Odd Numbers up to n
• Start.Input: Read a number n from the user.
• Initialize: Set i = 1.
• Loop:While i is less than or equal to n:
– Check if i is odd (i.e., i % 2 != 0).
– If true, display i.
– Increment i by 1.
• End.
C Program to Display Odd Numbers Up to n
#include <stdio.h>
int main() {
• int n, i;
// Input the number n from the user
• printf("Enter the value of n: ");
• scanf("%d", &n);
// Display odd numbers from 1 to n
• printf("Odd numbers up to %d:\n", n);
• for(i = 1; i <= n; i++) {
• if(i % 2 != 0) {
• printf("%d ", i);
• }
• }
• printf("\n");
return 0;
• }
• Odd numbers up to 10: 1 3 5 7 9
• Algorithm to Calculate the Value of the Series 1 + 1/2 + 1/3 + 1/4
+.... + 1/n
• Start.
• Input: Read the value of n from the user.
• Initialize: Set sum = 0.
• Loop:
– For i = 1 to n, do the following:
• Add 1 / i to sum.
• Output: Display the value of sum.
• End.
• C Program to Calculate the Value of the Harmonic Series

#include <stdio.h>
int main() {
• int n, i;
• double sum = 0.0;

• // Input the value of n from the user


• printf("Enter the value of n: ");
• scanf("%d", &n);

• // Calculate the sum of the harmonic series


• for (i = 1; i <= n; i++) {
• sum += 1.0 / i; // Add 1/i to sum
• }

• // Output the result


• printf("The sum of the series 1 + 1/2 + 1/3 + ... + 1/%d is: %.5lf\n", n, sum);

• return 0;
• }
• Explanation of the Program:
• Input: The user is prompted to enter the value
of n.
• Loop: A for loop runs from i = 1 to n, adding
the term 1/i to the sum.
• Floating-Point Arithmetic: 1.0 / i ensures the
result is a floating-point number.
• Output: The sum of the series is displayed
with 5 decimal places.
Output:The sum of the series 1 + 1/2 + 1/3 + ... +
1/5 is: 2.28333
• Write a progrma to calculate the sum of series S=x−x/2!
+x​/3!-x​/4!..…x/n!​
• Algorithm
• Start.
• Input: Read values for x and n from the user.
• Initialize: Set sum = 0, sign = 1, and fact = 1.
• Loop:
– For i = 1 to n:
• Calculate fact = fact * i (to get i!).
• Update the term = (sign * x) / fact.
• Update sum = sum + term.
• Change sign to -sign (to alternate signs).
• Output: Display the value of sum.
• End.
• C Program to Calculate the Sum of the Series
#include <stdio.h>
int main() {
• double x, sum = 0.0, term;
• int n, i;
• int sign = 1; // To alternate the signs
• double fact = 1.0; // To calculate factorial
• // Input values for x and n from the user
• printf("Enter the value of x: ");
• scanf("%lf", &x);
• printf("Enter the value of n: ");
• scanf("%d", &n);
// Calculate the sum of the series
• for (i = 1; i <= n; i++) {
• fact *= i; // Calculate i! iteratively
• term = (sign * x) / fact; // Calculate the term
• sum += term; // Update the sum
• sign = -sign; // Alternate the sign
• } // Output the result
• printf("The sum of the series is: %.5lf\n", sum);
return 0;
• Output:The sum of the series is: 0.28333
• Nested for Loop
• A nested for loop is a loop inside another loop. The inner
loop will be executed completely for each iteration of the
outer loop. It's commonly used when you need to iterate
over multi-dimensional structures, like matrices or grids.
• Syntax:
• for ( initialization; condition; increment )
• {
• for ( initialization; condition; increment )
• {
• // statement of inside loop
• }
• // statement of outer loop
• }
• Basic Example of Nested For Loop in C:

#include <stdio.h>
int main() {
// Outer loop
for (int i = 0; i < 3; i++)
{
// Inner loop
for (int j = 0; j < 2; j++)
{
printf("Outer loop i = %d, Inner loop j = %d\n", i, j); }
}

return 0;
}
• Output
• Outer loop i = 0, Inner loop j = 0
• Outer loop i = 0, Inner loop j = 1
• Outer loop i = 1, Inner loop j = 0
• Outer loop i = 1, Inner loop j = 1
• Outer loop i = 2, Inner loop j = 0
• Outer loop i = 2, Inner loop j = 1
while and do...while Loop
C programming has three types of loops.
• for loop
• while loop
• do...while loop
• While Loop
• The while loop through a block of code as long
as a specified condition is true:
• Syntax
• while (condition) {
// code block to be executed
}
• int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
• The Do/While Loop
• 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);
• Example:
• int i = 0;

do {
printf("%d\n", i);
i++;
}
while (i < 5);

• Try it Yourself »
c-control structures for selection
• if-else Statement
• The if-else statement is a decision-making statement
that is used to decide whether the part of the code
will be executed or not based on the specified
condition (test expression). If the given condition is
true, then the code inside the if block is executed,
otherwise the code inside the else block is executed.
• Syntax of if-else
• if (condition)
• {
• // code executed when the condition is true
• }
• else
• {
• // code executed when the condition is false
• }
• // C Program to demonstrate the use of if-else statement
• #include <stdio.h>
• int main()
• {
• // if block with condition at the start
• if (5 < 10) {
• // will be executed if the condition is true
• printf("5 is less than 10.");
• }
• // else block after the if block
• else {
• // will be executed if the condition is false
• printf("5 is greater that 10.");
• }
return 0;}
• Simple if Statement
• The if in C is the most simple decision-making statement. It
consists of the test condition and if block or body. If the given
condition is true only then the if block will be executed.
• Syntax of if Statement in C
• if(condition)
• {
• // if body
• // Statements to execute if condition is true
• }
• // C Program to demonstrate the syntax of if statement
• #include <stdio.h>

• int main()
• {
• int gfg = 9;
• // if statement with true condition
• if (gfg < 10) {
• printf("%d is less than 10", gfg);
• }
• // if statement with false condition
• if (gfg > 20) {
• printf("%d is greater than 20", gfg);
• }
• return 0;
• }
• “if-else” Ladder in C
• The if-else-if ladder statement is an extension to the if-else
statement. It is used in the scenario where there are multiple cases
to be performed for different conditions.

• 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
• }
• #include<stdio.h>
• int main(){
• int number=0;
• printf("enter a number:");
• scanf("%d",&number);
• if(number==10){
• printf("number is equals to 10");
• }
• else if(number==50){
• printf("number is equal to 50");
• }
• else if(number==100){
• printf("number is equal to 100");
• }
• else{
• printf("number is not equal to 10, 50 or 100");
• }
• return 0;
• }
• C Switch Statement
• The switch statement in C is an alternate to if-else-if ladder
statement which allows us to execute multiple operations for
the different possibles values of a single variable called switch
variable. Here, We can define various statements in the
multiple cases for the different values of a single variable.
• Rules for switch statement in C language
• The switch expression must be of an integer or character type.
• The case value must be an integer or character constant.
• The case value can be used only inside the switch statement.
• The break statement in switch case is not must. It is optional.
If there is no break statement found in the case, all the cases
will be executed present after the matched case. It is known
as fall through the state of C switch statement.
• The syntax of switch statement in c language is given below:
• switch(expression){
• case value1:
• //code to be executed;
• break; //optional
• case value2:
• //code to be executed;
• break; //optional
• ......

• default:
• code to be executed if all cases are not matched;
• }
• #include <stdio.h>
• int main() {
• int num = 2;
• switch (num) {
• case 1:
• printf("Value is 1\n");
• break;
• case 2:
• printf("Value is 2\n");
• break;
• case 3:
• printf("Value is 3\n");
• break;
• default:
• printf("Value is not 1, 2, or 3\n");
• break;
• }
• return 0;
• }
• // C program to Demonstrate returning of day based numeric value
#include <stdio.h>
• int main()
• { // switch variable
• int var = 1;
• // switch statement
• switch (var)
• { case 1:
• printf("Case 1 is Matched.");
• break;
• case 2:
• printf("Case 2 is Matched.");
• break;
• case 3:
• printf("Case 3 is Matched.");
• break;
• default:
• printf("Default case is Matched.");
• break;
• }
• return 0;
• }
• Output:Case 1 is Matched.
utput The day with number 2 is Tuesday
Unconditional Branching Statements:

• C uses unconditional branching statements to alter the


typical course of program execution. These statements
give programmers the freedom to jump to a specific
location in their code under any circumstance. The
various categories of unconditional branching statements
in C are as follows:
• goto Statement
• break Statement
• continue Statement
• goto Statement:
• The C goto statement is a jump statement which is
sometimes also referred to as an unconditional
jump statement. The goto statement can be used to
jump from anywhere to anywhere within a function. .
• Syntax of goto Statement in C:
• goto label;

• ...

• label:
• // code to be executed
• #include <stdio.h>

• int main() {
• int num = 1;

• if (num == 1) {
• goto label;
• }

• printf("This statement is skipped.\n");

• label:
• printf("The value of num is 1.\n");

• return 0;
• }
• #include <stdio.h>
• int main()
• {
• int num,i=1;
• printf("Enter the number whose table you want to prin
t?");
• scanf("%d",&num);
• table:
• printf("%d x %d = %d\n",num,i,num*i);
• i++;
• if(i<=10)
• goto table;
• }
• 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
• The 'break' Statement:
• The "break" statement is frequently employed in switch statements as
well as looping constructions like "for", "while", and "do-while". It
enables you to skip the statement that follows the loop or switch and
end the execution of the closest enclosing loop or switch statement.
• #include <stdio.h>

• int main() {
• int i;

• for (i = 1; i<= 5; i++) {
• if (i == 3) {
• break;
• }
• printf("%d ", i);
• }

• return 0;
• }
• continue Statement
• In the C programming language, the continue statement is used to go to the
next iteration of a loop while skipping the current iteration. Usually, this
statement is used in loops like for or while.
• #include <stdio.h>

• int main() {
• int i;
• for (i = 0; i< 10; i++) {
• if (i % 2 == 0) {
• continue; // skip even numbers
• }
• printf("%d ", i);
• }
• return 0;
• }
• Advantages of Branching Statements:
• Better Decision Making
• Readability of the code: Branching statements
• Code effectiveness
• Flexibility:
• Code Reusability
• Disadvantages of Branching Statements:
• Code Complexity
• Readability Issues:
• Code Maintenance
Parameters Break Statement in C Continue Statement in C

Purpose Exits the current loop Skips the current iteration

Applicability Used within loops (for, Used within loops (for,


while, do-while) while, do-while)
Effect Terminates the loop Immediately moves to the
prematurely and continues next iteration of the loop,
with the next statement skipping the remaining
after the loop code in the current
iteration
Loop Control Affects the entire loop Affects only the current
iteration of the loop
Typical Use Cases When a specific condition When you want to skip the
is met, and you want to current iteration of the
exit the loop loop based on a certain
condition and continue
with the next iteration

Example for (int i = 1; i <= 10; i++) for (int i = 1; i <= 10; i++)
{ if (i == 5) { break; } { if (i == 5) { continue; }
printf("%d\n", i); } printf("%d\n", i); }

You might also like