0% found this document useful (0 votes)
46 views70 pages

1 1 Module-2

Uploaded by

harshagowda0464
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)
46 views70 pages

1 1 Module-2

Uploaded by

harshagowda0464
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/ 70

Decision control and Looping

statements
MODULE-2
Contents:
• Introduction to decision control
• Conditional branching statements:
• if
• if-else
• if-else-if
• switch case
• Iterative statements:
• For
• While
• do- while
• Nested loops
Decision making statements in ‘C’
• When you are going to write some program, it
will always be necessary that you will have to
put some code which has to be executed only
when a specific condition is satisfied.
• Your program must take decision based on
internal/external events or conditions.
• For example, if the user presses a key, then
execute ‘this’ set of statements or if the user
doesn’t press any key, then execute ‘that’ set
of statements.
• In embedded programming, let’s take an
example of water level indication and control
program. If the sensor detects water level
rising above the threshold, then the program
executes the code to turn off the motor,
otherwise program doesn’t turn off the motor.
SELECTION OR BRANCHING STATEMENTS:
• The C statements that transfer the control from one
place to other place in the program with or without
any condition are called branching or selection
statements.
• The selection / branching statements can be
classified into two categories:
1] Conditional Control /Branch Statements:
• Conditional branching statements that alter the
sequence of execution of the program based on
some condition are called Conditional branching
statements/ selection statements /decision
statements.
• Conditional Control /Branch Statements are as
follows: simple if (single selection), if-else (two
way selection), Nested if (multiple if statements),
else –if ladder (multi-way selection), switch
( multi-way selection).
Example
#include <stdio.h>
int main() {
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
} else {
printf("x is not greater than 5\n");
}
return 0;
}

Output is: 5
SELECTION OR BRANCHING STATEMENTS:
2] Unconditional Control /Branch Statement:
• The statements that alter the sequence of execution of the program based on some
unconditioned are called Unconditional branching statement.
• Unconditional Control /Branch Statements are as follows: Goto Statement, break
Statement, continue Statement and return Statement.
#include <stdio.h>
int main() {
Output:
int num = 1;
Number: 1
start:
Number: 2
printf("Number: %d\n", num);
Number: 3
num++;
Number: 4
if (num <= 5) {
Number: 5
goto start;
}
return 0;
}
Introduction to decision
control:

• Decision control is a fundamental


concept in programming that allows
the execution of certain statements or
blocks of code based on specified
conditions.
• There are mainly two types of decision
control structures:
• if statement
• switch statement
if Statement:
• The if statement is used to decide based on a condition.
• It evaluates whether a condition is true or false and executes a block of code
accordingly. In this example, if the value of num is greater than 0, the
Example: statement inside the if block (‘printf("The number is
positive.\n");’) will be executed.
#include <stdio.h>
int main() { Output:
int num = 10; The number is Positive
if (num > 0)
{
printf("The number is positive.\n");
}
return 0;
}
If else
statement:
switch Statement:
• The switch statement is used to select one of many blocks of code to be executed.
• It evaluates an expression and compares it with multiple cases, executing the code
block associated with the matched case.
Example:
#include <stdio.h>
int main() {
char grade = 'A'; In this example, based on the value of grade,
switch (grade) { the switch statement will execute the
case 'A':
printf("Excellent!\n"); corresponding code block. If grade is 'A', it
break; will print "Excellent!", if 'B', it will print
case 'B': "Good!", and so on. The default case is
printf("Good!\n"); executed if none of the cases match.
break;
case 'C':
printf("Fair!\n");
break;
default:
printf("Invalid grade!\n");
}
return 0;
}
Conditional branching statements:
if statement:
• The if statement is the simplest form of decision control statements that is frequently used in decision-making.

• A conditional branching statement like the ‘if’ statement in C programming allows you to control the flow of execution
based on certain conditions.

• The ‘if’ statement is fundamental in controlling program flow and implementing conditional logic in C programs.

• Purpose: The ‘if’ statement is used to execute a block of code only if a specified condition is true.

• Syntax:

if (condition)

// Code to execute if the condition is true

}
How it works:
The ‘if’ keyword is followed by a condition enclosed in parentheses (condition).

If the condition is true, the code block inside the curly braces ‘{}’ is executed.

If the condition is false, the code block inside the curly braces is skipped, and the program continues executing the next statement
after the ‘if’ block.

Example:

int num = 10;

if (num > 5)

printf("Number is greater than 5\n");

Use Cases:

Checking conditions before performing an action.

Implementing decision-making logic based on user input or variable values.

Handling different scenarios based on runtime conditions.


Conditional branching statements:
if-else statement:
• The ‘if-else’ statement in C programming is an extension of the ‘if’ statement that allows
you to execute different blocks of code based on whether a specified condition is true or
false.
• The ‘if-else’ statement is a powerful tool for implementing decision-making logic in C
programs, allowing for more flexible control over program flow based on conditions.
• Purpose: The if-else statement is used to execute one block of code if a condition is true
and another block of code if the condition is false.
• Syntax:
if (condition)

// Code to execute if the condition is true

else

// Code to execute if the condition is false

• How it works:
• The if keyword is followed by a condition enclosed in parentheses (condition).

• If the condition is true, the code block inside the first set of curly braces {} is executed.

• If the condition is false, the code block inside the else block's curly braces is executed.
• Example:
int num = 10; Use Cases:
• Implementing binary decisions where an action is taken
if (num > 15) if a condition is true, and another action is taken if the
condition is false.
{
• Handling mutually exclusive scenarios based on the
printf("Number is greater than 15\n"); evaluation of a condition.

} • Providing fallback options or default behaviour when a


condition is not met.
else

printf("Number is not greater than 15\n");

}
Difference between if and if-else statement:
• In if, the statements inside the if block will execute, if the condition is
true and the control is passed to the next statement after the if block.
• In the if else, if the condition is true, the statements inside the if block
will execute and if the condition is false the statements in the if else
block will execute.
#include <stdio.h>
#include <stdio.h>
int main() {
int main() { int age;
int age;
printf("Enter your age: ");
printf("Enter your age: "); scanf("%d", &age);
scanf("%d", &age);
if (age >= 18) {
if (age >= 18) { printf("You are eligible to vote.\n");
printf("You are eligible to vote.\n"); } else {
} printf("You are not eligible to vote.\n");
}
return 0;
} return 0;
}
Conditional branching statements:
if-else-if statement:
• The "if-else-if" statement, is a conditional branching statement used in
programming languages like C.
• It allows you to test multiple conditions and execute different blocks of
code based on the outcome of these conditions.
• Syntax:
if (condition1) {
// code block 1
} else if (condition2) {
// code block 2
} else {
// default code block
}
Working:
The if statement checks condition1. If it's true, code block 1 executes.
If condition1 is false, the else if part checks condition2. If condition2 is true,
code block 2 executes.
If neither condition1 nor condition2 is true, the else part executes the default
code block.
Example:
int num = 10;
if (num > 0) {
printf("Positive\n");
} else if (num < 0) {
printf("Negative\n");
} else {
printf("Zero\n");
}
// C program to illustrate nested-if statement
#include <stdio.h>

int main()
{
int i = 10;

if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}

return 0;
}
Finding the Largest Number
#include <stdio.h>

int main() {
int num1, num2, num3;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);

if (num1 >= num2 && num1 >= num3) {


printf("%d is the largest number.\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("%d is the largest number.\n", num2);
} else {
printf("%d is the largest number.\n", num3);
}
return 0;
}
Checking Leap Year
#include <stdio.h>

int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {


printf("%d is a leap year.\n", year);
} else {
printf("%d is not a leap year.\n", year);
}

return 0;
}
The main differences between the if-else statement and the if-else-if statement (nested if) in C programming are:

1. Usage:

• The if-else statement is used to execute a block of code if a condition is true. If the condition is false, the code inside the else block
executes.

• The if-else-if statement is used when you have multiple conditions to check sequentially. It allows you to test multiple conditions and
execute different blocks of code based on these conditions.

2. Structure:

• The if-else statement has a simple structure with an initial if condition followed by an optional else block.

• The if-else-if statement has a more complex structure with an initial if condition followed by multiple else if conditions, and an optional else
block at the end.

3. Execution:

• In the if-else statement, only one block of code (either the if block or the else block) is executed based on the condition's evaluation.

• In the if-else-if statement, multiple conditions are sequentially tested. Once a condition is true, the corresponding block of code executes,
and the remaining conditions are not evaluated.

4. Decision Making:

• The if-else statement is suitable for simple decision-making scenarios where there are only two possible outcomes based on a single
condition.

• The if-else-if statement is suitable for more complex decision-making scenarios where there are multiple conditions to be checked in a
specific order.
#include <stdio.h>
// Using if-else-if statement
int main() { if (num > 0) {
int num = 10; printf("Number is positive.\n");
} else if (num < 0) {
// Using if-else statement printf("Number is negative.\n");
if (num > 0) { } else {
printf("Number is positive.\n"); printf("Number is zero.\n");
} else { }
printf("Number is not positive.\n");
} return 0;
}
Multiple Conditions using if-else if-else (if else if
ladder)
int score = 85;
if (score >= 90) {
printf("Grade A\n");
} else if (score >= 80) {
printf("Grade B\n");
} else if (score >= 70) {
printf("Grade C\n");
} else {
printf("Grade F\n");
}
Conditional branching statements:
switch case :
• A "switch case" statement is a type of conditional branching statement commonly
used in programming languages like C, C++, Java, and others.
• It allows you to execute one out of several possible blocks of code based on the
value of an expression or variable.
• Overall, switch case statements offer a structured approach to handle multiple
conditional branches based on the value of an expression, enhancing code
readability and maintainability.
• Syntax:
switch (expression) {
case value1:
// Code to be executed if expression == value1
break;
case value2:
// Code to be executed if expression == value2
break;
...
default:
// Code to be executed if expression doesn't match any case
}
• The switch keyword is followed by an expression in parentheses.
• Inside the curly braces, there are multiple case statements each followed by a value.
• The break statement is used to exit the switch case block.
• The default case is optional and executes when none of the other cases match.
Execution Flow:
The expression inside the switch is evaluated.
The value of the expression is compared with each case value sequentially.
If a match is found, the corresponding block of code is executed, and the
switch case block is exited unless a break statement is encountered.
If no match is found and there is a default case, its block of code is executed.
Use Cases:
Switch case statements are often used when there are multiple conditions to be
checked against a single variable.
They provide a more organized and efficient way to handle multiple conditions
compared to nested if-else statements, especially when each condition
corresponds to a specific value.
Note:
• The case values must be unique and constants (integer, character, enum, or string literals in
some languages).
• The break statement is crucial to prevent "fall-through," where execution continues into
subsequent cases after a match.
• If-Else is executed based on the condition inside the statement and is used to choose between
two options. Switch Case executes as per the user decision and is used to choose among
multiple options.
Example-1:
#include <stdio.h>
int main() {
int choice;
printf("Enter a number between 1 and 3: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You entered 1.\n");
break;
case 2:
printf("You entered 2.\n");
break;
case 3:
printf("You entered 3.\n");
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
#include <stdio.h> case 'g':
#include <string.h> case 'G':
printf("Green\n");
int main() { break;
char color[10]; case 'b':
case 'B':
printf("Enter a color (red, green, blue): "); printf("Blue\n");
scanf("%s", color); break;
default:
switch (color[0]) { printf("Unknown color\n");
case 'r': }
case 'R':
printf("Red\n"); return 0;
break; }
1. Start the program.
2. Declare a character array color of size 10.
3. Display a message asking the user to enter a color (red, green, blue).
4. Read the input color from the user using scanf and store it in the character array color.
5. Use a switch case statement to check the first character of the input color (color[0]):
• If the first character is 'r' or 'R', print "Red" and then exit the switch case block using break.

• If the first character is 'g' or 'G', print "Green" and then exit the switch case block using

break.
• If the first character is 'b' or 'B', print "Blue" and then exit the switch case block using

break.
• If the first character does not match any of the cases, print "Unknown color".

6. End the program.


#include <stdio.h>
case 4:
int main() { printf("Four\n");
int num; break;
case 5:
printf("Enter a number between 1 and 5: "); printf("Five\n");
scanf("%d", &num);
break;
switch (num) { default:
case 1: printf("Number out of range\n");
printf("One\n"); }
break;
case 2:
return 0;
printf("Two\n");
break; }
case 3:
printf("Three\n");
break;
1. Start the program.
2. Declare an integer variable num.
3. Display a message asking the user to enter a number between 1 and 5.
4. Read the input number from the user using scanf and store it in the variable num.
5. Use a switch case statement to check the value of num:
• If num is 1, print "One" and then exit the switch case block using break.

• If num is 2, print "Two" and then exit the switch case block using break.

• If num is 3, print "Three" and then exit the switch case block using break.

• If num is 4, print "Four" and then exit the switch case block using break.

• If num is 5, print "Five" and then exit the switch case block using break.

• If num is not within the range of 1 to 5, print "Number out of range".

6. End the program.


#include <stdio.h>
case Saturday:
case Sunday:
enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
printf("Weekend\n");
break;
int main() {
default:
enum Weekday day = Wednesday;
printf("Invalid day\n");
}
switch (day) {
case Monday:
return 0;
case Tuesday:
case Wednesday:
case Thursday:
case Friday:
printf("Weekday\n");
break;
1. Start the program.
2. Declare an enumeration enum Weekday with constants Monday,
Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.
3. Set a variable day of type enum Weekday to a specific day, for example,
Wednesday.
4. Use a switch case statement to check the value of the day variable:
• If day is Monday, Tuesday, Wednesday, Thursday, or Friday, print "Weekday" and
then exit the switch case block using break.
• If day is Saturday or Sunday, print "Weekend" and then exit the switch case block
using break.
• If day does not match any of the cases, print "Invalid day".
5. End the program.
Iterative statements:
For
• The "for" loop in C programming is an iterative statement used to execute
a block of code repeatedly based on a specified condition.
• It's commonly used when the number of iterations is known beforehand
or when iterating over arrays, sequences, or ranges.
• Syntax:
• for (initialization; condition; increment/decrement) {
• // Code to be executed repeatedly
• }
• Initialization: It typically initializes a loop control variable and is executed once at the
beginning of the loop.
• Condition: It is evaluated before each iteration. If it's true, the loop continues;
otherwise, the loop terminates.
• Increment/Decrement: It updates the loop control variable after each iteration.
#include <stdio.h>

int main() {
int i;
for (i = 0; i < 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
In this example, the loop initializes i to 0, checks if i is less than 5 in each iteration, and
increments i by 1 after each iteration. The loop prints "Iteration 0" to "Iteration 4".
Components:
• Initialization: It sets the initial value of the loop control variable.
• Condition: It defines the condition that must be true for the loop to continue executing.
• Increment/Decrement: It updates the loop control variable to progress towards the termination condition.
• Loop Body: It contains the code to be executed repeatedly as long as the condition is true.
Common Usages:
• Iterating over arrays or sequences.
• Performing a specific number of iterations.
• Implementing counters and accumulators.
• Generating number sequences.
Note:
• The initialization, condition, and increment/decrement parts are optional but
commonly used.
• The loop control variable is often used as an index in arrays or for counting iterations.
#include <stdio.h>
int main() {
// Declare a 5x5 array
int matrix[5][5];

// Initialize the array using nested for loops


for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
// Assign values to each element based on row and column indices
matrix[row][col] = row * 10 + col;
} // Print the array elements
} printf("Matrix elements:\n");
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
printf("%3d ", matrix[row][col]); // Print each element with 3 digits width
}
printf("\n"); // Move to the next row
}
return 0;
}
Example-1: Printing Numbers from 1 to 10
#include <stdio.h>

int main() {
for(int i = 1; i <= 10; i++)
{
printf("%d ", i);
}
return 0;
}
Example-2: Calculating Factorial
#include <stdio.h>

int main() {
int n = 5;
int factorial = 1;

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


{
factorial *= i;
}

printf("Factorial of %d is %d\n", n, factorial);


return 0;
}
Example-3: Summing Array Elements
#include <stdio.h>

int main()
{
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;

for(int i = 0; i < 5; i++)


{
sum += arr[i];
}

printf("Sum of array elements: %d\n", sum);


return 0;
}
Example-4: Printing Even Numbers
#include <stdio.h>

int main()
{
for(int i = 0; i <= 10; i += 2)
{
printf("%d ", i);
}
return 0;
}
Iterative statements:
While
• The while statement is an iterative control structure in programming that repeats a block
of code as long as a specified condition is true.
• Syntax:
while (condition) {
// code block to be executed while the condition is true
}
• Behavior:
• Condition Check: The condition inside the parentheses is evaluated before each iteration. If the
condition is true, the code block inside the while loop is executed.
• Loop Execution: As long as the condition remains true, the code block inside the while loop
continues to execute.
• Exiting the Loop: When the condition becomes false, the loop terminates, and program control
moves to the statement immediately following the while loop.
Example:
#include <stdio.h>

int main() {
int count = 1;

// Loop will execute as long as count is less than or equal to 5


while (count <= 5) {
printf("Count: %d\n", count);
count++; // Increment count to avoid an infinite loop
}

printf("Loop ended.\n");

return 0;
}
Key Points:
• The condition in a while loop is evaluated before each iteration.
• The loop continues to execute as long as the condition remains true.
• Care should be taken to avoid infinite loops by ensuring that the condition eventually becomes false during the loop
execution.
Example-1: Countdown from 10 to 1
#include <stdio.h>

int main() {
int count = 10;

while(count >= 1) {
printf("%d ", count);
count--;
}

printf("\n");
return 0;
}
Example-2: Summing Numbers Entered by the User
#include <stdio.h>

int main() {
int num, sum = 0;

printf("Enter numbers to sum (enter 0 to stop):\n");

while(1) {
scanf("%d", &num);
if(num == 0) break;
sum += num;
}

printf("Sum of the numbers: %d\n", sum);


return 0;
}
Example-3: Finding Factorial using while loop
#include <stdio.h>

int main() {
int n = 5;
int factorial = 1;
int i = 1;

while(i <= n) {
factorial *= i;
i++;
}

printf("Factorial of %d is %d\n", n, factorial);


return 0;
}
Example-4: Printing Fibonacci Series
#include <stdio.h>

int main() {
int n = 10;
int prev = 0, curr = 1, next;

printf("Fibonacci Series up to %d terms:\n", n);

while(n > 0) {
printf("%d, ", prev);
next = prev + curr;
prev = curr;
curr = next;
n--;
}

printf("\n");
return 0;
}
Example-5: Copying Characters from one
String to Another
#include <stdio.h>

int main() {
char source[] = "Hello, world!";
char destination[20];
int i = 0;

while(source[i] != '\0') {
destination[i] = source[i];
i++;
}
destination[i] = '\0';

printf("Copied string: %s\n", destination);


return 0;
}
Difference between for loop Vs while loop:
Parameters for Loop while Loop
Basics The for loop provides its users with a concise way in The while loop is a type of continuous flow
which they can write the loop structure. It provides a statement that basically allows the repeated
very easy to debug and short looping structure. execution of a code on the basis of any given
Boolean condition.

Number of Iterations These must be known when using a for loop. The while loop works well even if the number of
iterations is basically unknown.

Condition It is a form of relational expression. The condition, in this case, may be a non-zero value
or an expression.

Initialization The initialization may exist both- outside the loop or The initialization, in this case, always occurs outside
in the loop statement. the loop.

Time of Increment The increment occurs only after the execution of the We can perform the increment both- after or before
statement(s). the execution of the given statement(s).

Use We use the for loop when the increment and We use the while loop in the case of a complex
initialization are very simple. initialization.
Iterative statements:
do- while
• The do-while loop is an iterative statement in C programming that executes a
block of code repeatedly until a specified condition becomes false.
• Unlike the while loop, which checks the condition before entering the loop,
the do-while loop checks the condition after executing the loop's body at least
once.
• Syntax:
do {
// code to be executed
} while(condition);
Execution Flow:
• The block of code inside the do statement is executed first, regardless of the
condition.
• After executing the code inside the do block, the condition is evaluated.
• If the condition is true, the loop repeats, executing the do block again.
• If the condition is false, the loop terminates, and program control moves to the
statement immediately following the do-while loop.
• Key Points:
• The do-while loop guarantees that the loop's body is executed at least
once, even if the condition is initially false.
• The loop continues to execute as long as the condition remains true.
• The condition is checked after each iteration, so even if the condition
becomes false during the loop's execution, the loop completes its current
iteration before terminating.
Example:
#include <stdio.h>

int main() { In this example, the loop prints numbers


int count = 1; from 1 to 5. Even if the initial value of
count is 6 (which makes the condition
do { false), the loop still executes once
printf("%d ", count); because the condition is checked after
count++; the first iteration.
} while(count <= 5);

printf("\n");
return 0;
}
Use Cases:
• Use the do-while loop when you want to execute a block of code at least once,
regardless of the condition's initial value.
• It is commonly used when you need to perform an action and then check a condition
to decide whether to repeat the action.
Example-1: Reading Input Until a Valid Value is Entered
#include <stdio.h>

int main() {
int num;
do
{
printf("Enter a positive number: ");
scanf("%d", &num);
}
while(num <= 0);

printf("You entered: %d\n", num);


return 0;
}
Example-2:Menu-Driven
case 1:
Program
#include <stdio.h>
printf("You chose Option 1\n");
int main() {
break;

int choice; case 2:


printf("You chose Option 2\n");
do {
break;
printf("Menu:\n"); case 3:

printf("1. Option 1\n"); printf("Exiting the program\n");


break;
printf("2. Option 2\n");
default:
printf("3. Exit\n"); printf("Invalid choice! Try again.\n");
}
printf("Enter your choice: ");
} while(choice != 3);
scanf("%d", &choice); return 0;

switch(choice) { }
Example-3: Calculating Factorial
#include <stdio.h>

int main() {

int n, factorial = 1;

int i = 1;

printf("Enter a number: ");

scanf("%d", &n);

do {

factorial *= i;

i++;

} while(i <= n);

printf("Factorial of %d is %d\n", n, factorial);

return 0;

}
Example-4: Generating Fibonacci Series
#include <stdio.h> do {
int main() { printf("%d, ", first);

int n, first = 0, second = 1, next; next = first + second;

printf("Enter the number of terms: "); first = second;

scanf("%d", &n); second = next;


n--;
printf("Fibonacci Series: ");
} while(n > 0);
printf("\n");
return 0;
}
Writing a program to calculate
factorial using for, while and do-
while loop
For Loop:
#include <stdio.h> 1. Begin the program.
2. Declare variables n (for the input number) and factorial (to
int main() { store the factorial value).
int n; 3. Prompt the user to enter a number and read the input into
variable n.
unsigned long long factorial = 1;
4. Initialize factorial to 1.
5. Start a for loop with the loop variable i initialized to 1 and the
printf("Enter a number to calculate factorial: ");
loop condition i <= n.
scanf("%d", &n);
• Inside the loop, multiply factorial by i.
• Increment i by 1 in each iteration.
for(int i = 1; i <= n; i++) {
6. After the loop, print the calculated factorial using the printf
factorial *= i; function.
} 7. End the program.

printf("Factorial using for loop: %llu\n", factorial);

return 0;
}
While loop: 1. Begin the program.
2. Declare variables n (for the input number), i (loop
#include <stdio.h>
variable initialized to 1), and factorial (to store the
int main() { factorial value).
int n, i = 1; 3. Prompt the user to enter a number and read the
unsigned long long factorial = 1; input into variable n.
4. Initialize factorial to 1.
printf("Enter a number to calculate factorial: ");
scanf("%d", &n);
5. Start a while loop with the loop condition i <= n.
• Inside the loop, multiply factorial by i.
while(i <= n) { • Increment i by 1 in each iteration.
factorial *= i;
6. After the loop, print the calculated factorial using the
i++;
}
printf function.
7. End the program.
printf("Factorial using while loop: %llu\n", factorial);

return 0;
}
Do-While loop: 1. Begin the program.
2. Declare variables n (for the input number), i (loop
#include <stdio.h> variable initialized to 1), and factorial (to store the
factorial value).
int main() {
3. Prompt the user to enter a number and read the input
int n, i = 1;
into variable n.
unsigned long long factorial = 1;
4. Initialize factorial to 1.
printf("Enter a number to calculate factorial: "); 5. Start a do-while loop with the loop condition i <= n.
scanf("%d", &n); • Inside the loop, multiply factorial by i.
• Increment i by 1 in each iteration.
do {
6. After the loop, print the calculated factorial using the
factorial *= i;
printf function.
i++;
} while(i <= n); 7. End the program.

printf("Factorial using do-while loop: %llu\n", factorial);

return 0;
}

You might also like