0% found this document useful (0 votes)
201 views39 pages

Unit 3 FPL

Uploaded by

uzair63210
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)
201 views39 pages

Unit 3 FPL

Uploaded by

uzair63210
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/ 39

PPS Unit-III DIT,Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY, PIMPRI, PUNE-18


Department of First Year Engineering
Fundamentals of Programming Languages
Unit- 3: CONTROL FLOW

Syllabus:
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

Control flow refers to the order in which statements within a program execute. While programs
typically follow a sequential flow from top to bottom, there are scenarios where we need more
flexibility.

What are Control Flow Statements?


 Control flow statements control the order in which instructions are executed in a
program.
 They enable execution of a block of code multiple times, execute a block of code based
on conditions, terminate or skip the execution of certain lines of code, etc.

Types of Control Flow Statements in C


1. Decision / Conditional Statements
a. if Simple if statement
b. if-else statements
c. else-if ladder
d. Nested if-else statements
e. switch-case

1
PPS Unit-III DIT,Pimpri

2. Branching statements
a. goto statement
b. break statement
c. continue statement

3. Looping / Iterative Statements


a. while loop
b. do – while loop
c. for loop

3.1 Decision Making and Branching

3.1.1 Simple If Statement

 Simple if statements are carried out to perform some operation when the condition is
only true.
 If the condition / test expression of the if statement is true then the statement block under
the if statement is executed otherwise the if statement–block is skipped and control is
transferred to the statements outside the if block.
 The statement block may be a single statement or a group of statements.
 When the condition is true both the statement-block and statement-x are executed in
sequence.

Syntax
if (condition / test expression)
{
Statement-block;
}
Statement-x;

2
PPS Unit-III DIT,Pimpri

Flowchart

Example: Program to check person is eligible to vote or not.

#include <stdio.h>
void main()
{
int age = 29;
if (age >= 18)
{
printf("Eligible to vote");
}
if (age < 18)
{
printf("Not eligible to vote");
}
}

3
PPS Unit-III DIT,Pimpri

3.1.2 If-Else
 The if-else statement is an extension of simple if statement
 If the test expression is true, then the true-block statements immediately following the if
statement are executed; otherwise, the false-block statements are executed.
 In either case, statements inside if block or statements inside else block will be executed,
not both.
 In both cases, the control is transferred subsequently to the statement-x that is statements
outside if-else block.

Syntax
if (condition / test expression)
{
True-block statements;
}
else
{
False-block statements;
}
Statement-x;

Flowchart

4
PPS Unit-III DIT,Pimpri

Example: Program to check person is eligible to vote or not.


#include <stdio.h>
void main()
{
int age = 29;
if (age >= 18)
{
printf("Eligible to vote");
}
else
{
printf("Not eligible to vote");
}
}

3.1.3 Nesting of if…else statements


 When a series of decisions are involved, nested if-else statements are needed.
 Nested if-else statements mean you can use one if or else-if statement inside
another if or else-if statement(s).

Syntax
if (test condition-1)
{
if (test condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-x;

 In the above syntax, if the condition-1 is false, the statement-3 will be executed;
otherwise it continues to perform second test.

5
PPS Unit-III DIT,Pimpri

 If the condition-2 is true, the statement-1 will be evaluated; otherwise statement-2


will be evaluated and then control is transferred to the statement-x.

Flowchart

Example: Program to check a number is positive, negative or zero.

#include <stdio.h>
void main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0)
{
printf("%d is positive.\n", num);
}
else
{
if (num < 0)
{
printf("%d is negative.\n", num);
}
else
{
printf("%d is zero.\n", num);
}
}
}
6
PPS Unit-III DIT,Pimpri

3.1.4 Else-If Ladder (IF – ELSE IF – ELSE)

 The if-else-if ladder statement is used in the scenario where there are multiple cases to be
performed for different conditions.
 In if-else-if ladder statement, if a condition is true then the statements defined in the if
block will be executed, otherwise if some other condition is true then the statements
defined in the else-if block will be executed, at the last if none of the condition is true
then the statements defined in the else block will be executed.
 There are multiple else-if blocks possible.

Syntax

if (condition 1)
{
Statement-1;
}
else if (condition 2)
{
Statement-2;
}
else if(condition n)
{
Statement-n;
}
else
{
Default-statement;
}
Statement-x;

7
PPS Unit-III DIT,Pimpri

Flowchart

Example: Program to check a number is positive, negative or zero.


#include <stdio.h>
int main()
{
int n = 10;
if (n > 0)
{
printf("Positive");
}
else if (n < 0)
{
printf("Negative");
}
else
{
printf("Zero");
}
return 0;
}
8
PPS Unit-III DIT,Pimpri

3.1.5 Switch Statement


 The switch-case statement is a decision-making statement in C.
 The if-else statement provides two alternative actions to be performed, whereas
the switch-case construct is a multi-way branching statement.
 A switch statement in C simplifies multi-way choices by evaluating a single variable
against multiple values, executing specific code based on the match.
 It allows a variable to be tested for equality against a list of values.

How switch-case Statement Work?


 The parenthesis in front of the switch keyword holds an expression. The expression
should evaluate to an integer or a character.
 Inside the curly brackets after the parenthesis, different possible values of the expression
form the case labels.
 One or more statements after a colon(:) in front of the case label forms a block to be
executed when the expression equals the value of the label.
 A switch-case can be translated as "in case the expression equals value1, execute the
block1", and so on.
 C checks the expression with each label value, and executes the block in front of the first
match.
 Each case block has a break as the last statement. The break statement takes the control
out of the scope of the switch construct.
 You can also define a default case as the last option in the switch construct. The default
case block is executed when the expression doesn’t match with any of the earlier case
values.

Rules for Switch statement


 The switch statement must be integral type.
 Case labels must be constants or constant expressions.
 Case labels must be unique. No two labels can have same value.
 Case labels must end with colon.
 The break statement transfers the control out of the switch statement.
9
PPS Unit-III DIT,Pimpri

 The break statement is optional. That is, two or more case labels may belong to the same
statements.
 The default label is optional. If present, it will be executed when the expression does not
find a matching case label.
 There can be at most one default label.
 The default may be placed anywhere but usually placed at the end.
 It is permitted to nest switch statements.

Syntax
switch (expression)
{
case value-1:
block-1
break;
case value-2:
block-1
break;
...
...
default:
default-block
break;
}
statement-x

Flowchart

10
PPS Unit-III DIT,Pimpri

Example: Program to display performance of student based on grade

#include <stdio.h>
int main()
{
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Outstanding!\n" );
break;
case 'B':
printf("Excellent!\n");
break;
case 'C':
printf("Well Done\n" );
break;
case 'D':
printf("You passed\n" );
break;
case 'F':
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade);
return 0;
}

11
PPS Unit-III DIT,Pimpri

3.1.6 Goto Statement

 C supports the goto statement to branch unconditionally from one point to another in the
program.
 The goto requires a label in order to identify the place where the branch is to be made.
 A label is any valid variable name, and must be followed by a colon.
 The label is placed immediately before the statement where the control is to be
transferred.
 The label: can be anywhere in the program either before or after the goto label;
statement.
 If the label: is placed after the goto label; some statements will be skipped and the jump
is known as a forward jump.
 If the label: is before the statement goto label; a loop will be formed and some statements
will be executed repeatedly. Such a jump is known as a backward jump.
 During running of a program when a statement like
goto begin;
is met, the flow of control will jump to the statement immediately following the label
begin:. This happens unconditionally.
 A goto breaks normal sequential execution of the program.

12
PPS Unit-III DIT,Pimpri

Example: Program to print multiplication table of a number


#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;
}

3.2 Decision Making and Looping

 In looping, a sequence of statements is executed until some conditions for termination of


the loop are satisfied.
 A program loop therefore consists of two segments, one known as the body of the loop
and the other known as the control statement.
 The control statement tests certain conditions and then directs the repeated execution of
the statements contained in the body of the loop.

A looping process, in general, would include the following four steps:


1. Setting and initialization of a condition variable.
2. Execution of the statements in the loop.
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.

The C language provides for three constructs for performing loop operations. They are
1. The while statement.
2. The do statement (do-while statement).
3. The for statement.

13
PPS Unit-III DIT,Pimpri

Entry-controlled and Exit-controlled loop


Depending on the position of the control statement in the loop, a control structure may be
classified either as the entry-controlled loop or as the exit-controlled loop.
 In the entry-controlled loop, the control conditions are tested before the start of the loop
execution. If the conditions are not satisfied, then the body of the loop will not be
executed. It is also called as pre-test loop.
 In the case of an exit-controlled loop, the test is performed at the end of the body of the
loop and therefore the body is executed unconditionally for the first time. It is also called
as post-test loop.

3.2.1 While Statement


 The while is an entry-controlled loop statement.
 The test-condition is evaluated and if the condition is true, then the body of the loop is
executed.
 After execution of the body, the test-condition is once again evaluated and if it is true,
the body is executed once again
 This process of repeated execution of the body continues until the test-condition finally
becomes false and the control is transferred out of the loop.

14
PPS Unit-III DIT,Pimpri

 On exit, the program continues with the statement immediately after the body of the
loop.
 The body of the loop may have one or more statements.
 The braces are needed only if the body contains two or more statements.
 However, it is a good practice to use braces even if the body has only one statement.

Syntax:
while (test condition)
{
Body of the loop
}

Example 1: Sum of squares of numbers from 1 to 10


#include <stdio.h>
void main()
{
int sum,n;
sum=0;
n=1;
while(n<=10)
{
sum=sum+n*n;
n=n+1;
}
printf("sum %d\n", sum);
}

Example 2: Reverse a number


#include <stdio.h>
void main()
{
int reverseNumber=0;
int number=12345;
while(number>0)
{
reverseNumber= (reverseNumber*10)+ number%10;
number/=10;
}
printf("Reverse Number is: %d\n", reverseNumber);
}
15
PPS Unit-III DIT,Pimpri

3.2.2 Do-While
 On some occasions it might be necessary to execute the body of the loop before the test
is performed. Such situations can be handled with the help of the do statement.
 On reaching the do statement, the program proceeds to evaluate the body of the loop
first.
 At the end of the loop, the test-condition in the while statement is evaluated.
 If the condition is true, the program continues to evaluate the body of the loop once
again. This process continues as long as the condition is true.
 When the condition becomes false, the loop will be terminated and the control goes to
the statement that appears immediately after the while statement.
 Since the test-condition is evaluated at the bottom of the loop, the do...while construct
provides an exit- controlled loop and therefore the body of the loop is always executed at
least once.
Syntax of do...while statement
do
{
body of the loop
} while(test-condition);

Example: Program to print numbers from 0 to 4

#include <stdio.h>
void main()
{
int i = 0;
do
{
printf("%d\n", i);
i++;
}while (i < 5);
}

16
PPS Unit-III DIT,Pimpri

3.2.3 For Statement

Simple 'for' Loops


The for loop is another entry-controlled loop that provides a more concise loop control structure.
1. Initialization of the control variables is done first, using assignment statements such as i=1
and count = 0. The variables i and count are known as loop-control variables.

2. The value of the control variable is tested using the test-condition. If the condition is true, the
body of the loop is executed; otherwise the loop is terminated and the execution continues with
the statement that immediately follows the loop.

3. When the body of the loop is executed, the control is transferred back to the for statement
after evaluating the last statement in the loop. Now, the control variable is incremented or
decremented and the new value of the control variable is again tested to see whether it satisfies
the loop condition. If the condition is satisfied, the body of the loop is again executed. This
process continues till the value of the control variable fails to satisfy the test-condition.

Syntax:
for (initialization; test-condition; increment or decrement)
{
body of the loop
}

Example: Program to print first 10 natural numbers


#include <stdio.h>
void main()
{
int i;
printf("The first 10 natural numbers are:\n");
for (i=1; i<=10; i++)
{
printf("%d ", i);
}
}

17
PPS Unit-III DIT,Pimpri

Nesting of for Loop:


 Nesting of loops, that is, one for statement within another for statement, is allowed in C.
 The nesting may continue up to any desired level.
 The loops should be properly indented so as to enable the reader to easily determine
which statements are contained within each for statement.
 ANSI C allows up to 15 levels of nesting However, some compilers permit more

For example, two loops can be nested as follows.

Example: Program to print multiplication tables


#include <stdio.h>
int main()
{
int n;
n=10;
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j));
}
printf("\n");
}
}

18
PPS Unit-III DIT,Pimpri

Comparison of the Loops:


Sr. For loop While loop Do while loop
No
1. Syntax: Syntax: Syntax:
for(initialization; while(condition) do
condition;updating) { {
{ Statements; Statements;
Statements; } } while(condition);
}
2. It is known as entry It is known as entry It is known as exit
controlled loop controlled loop. controlled loop.
3. If the condition is not true If the condition is not true Even if the condition is not
first time than control will first time than control will true for the first time the
never enter in a loop never enter in a loop. control will enter in a loop.
4. There is no semicolon; after There is no semicolon; There is semicolon; after
the condition in the syntax after the condition in the the condition in the syntax
of the for loop. syntax of the while loop. of the do while loop.
5. Initialization and updating Initialization and updating Initialization and updating
is the part of the syntax. is not the part of the is not the part of the syntax
syntax.
6. For loop is use when we While loop is use when Do while loop is use when
know the number of we don't know the number we don't know the number
iterations means where the of iterations means where of iterations means where
loop will terminate. the loop will terminate. the loop will terminate.

3.2.4 Break and Continue


Jumps In Loops
Loops perform a set of operations repeatedly until the control variable fails to satisfy the test-
condition. The number of times a loop is repeated is decided in advance and the test condition is
written to achieve this. Sometimes when executing a loop it becomes desirable to skip a part of
the loop or to leave the loop as soon as a certain condition occurs. C permits a jump from one
statement to another within a loop as well as a jump out of a loop.

Break statement
Jumping Out of a Loop
 An early exit from a loop can be accomplished by using the break statement.

19
PPS Unit-III DIT,Pimpri

 When a break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop.
 When the loops are nested, the break would only exit from the loop containing it. That is,
the break will exit only a single loop.
 break statement can be used within while, do, or for loops.

Syntax:
break;

Example:
#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
printf("%d\n", i);
}
return 0;
}
20
PPS Unit-III DIT,Pimpri

Continue statement
Skipping a Part of a Loop
 During the loop operations, it may be necessary to skip a part of the body of the loop
under certain conditions.
 For example, in processing of applications for some job, we might like to exclude the
processing of data of applicants belonging to a certain category. On reading the category
code of an applicant, a test is made to see whether his application should be considered
or not. If it is not to be considered, the part of the program loop that processes the
application details is skipped and the execution continues with the next loop operation.
 The continue, as the name implies, causes the loop to be continued with the next iteration
after skipping any statements in between.
 The continue statement tells the compiler, "SKIP THE FOLLOWING STATEMENTS
AND CONTINUE WITH THE NEXT ITERATION'.
 In while and do loops, continue causes the control to go directly to the test-condition and
then to continue the iteration process.
 In the case of for loop, the increment section of the loop is executed before the test-
condition is evaluated.

21
PPS Unit-III DIT,Pimpri

Syntax:
continue;

Example:
#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
printf("%d\n", i);
}
return 0;
}

Difference Between Break and Continue Statement in C


Parameters Break Statement in C Continue Statement in C

Loop This statement lets a user exit It does not let a user make an exit from an
Construct from an overall loop construct. overall loop construct.
One can easily use the break
statement along with the switch You cannot use the continue statement
Switch and statement. You can also use it with the switch statement. Still, you can
Loop within the for loop, do-while use it within the for loop, do-while loop,
Statement loop, and the while loop. It means and the while loop. It means that continue
that break can easily occur in both can only occur in the loop and not switch.
loop and switch.
As soon as the control encounters the
The control exits immediately
continue statement, it passes automatically
Control from a loop construct as soon as it
from the very beginning of a loop
encounters the break statement.
statement.
The continue statement doesn’t cause a
The break statement causes a loop
loop termination- but leads it into its next
or a switch to terminate a case at
iteration. It means that a loop will execute
the very moment of its execution.
Function all of its iterations even if it encounters a
It means that a switch or a loop
continue statement. We use the continue
would end abruptly as soon as
statement to skip those statements that
they encounter a break.
appear after the continue in a loop.
You can denote it as: You can denote it as:
Syntax
break; continue;
22
PPS Unit-III DIT,Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY PIMPRI, PUNE-411 018


DEPARTMENT OF FIRST YEAR ENGINEERING
CLASS: F.E. - (SEM – I) ACADEMIC YEAR: 2024-25
SUB: Fundamentals of Programming Languages

Unit 3: Control Flow


Question Bank

Q. No. Question
1 Explain conditional statements in C.
2 Explain if statement with syntax, flowchart and example.
3 Explain if – else statement with syntax, flowchart and example.
4 Explain if – else ladder (if-else if – else) statement with syntax, flowchart and example.
5 Explain nested if statement with syntax, flowchart and example.
6 Explain switch statement with syntax, flowchart and example.
7 Explain goto statement in detail.
8 Explain looping / iterative statements in C.
9 Explain for loop with syntax and example.
10 Explain while loop with syntax and example.
11 Explain do-while loop with syntax and example.
12 Explain nested loops with example.
13 Illustrate difference between for, while and do-while loops.
14 Explain break statement with syntax and example.
15 Explain continue statement with syntax and example.
16 Differentiate between break and continue statements.
17 Write a Program to check whether a person is eligible to vote or not.
18 Write a Program to Find the Greater and smaller of Two Numbers
19 Write a program print 1 to 5 using while loop.
20 Write a c program to compute the sum of the first 10 natural numbers using for loop.
Write a C program using for loop to print all the numbers from m-n thereby classifying
21
them as even or odd.
22 Write a C program to sum the series 1+1/2+1/3+1/4….1/n
23 Write a C program to calculate sum of cubes of numbers from 1-n
24 Write a C program to calculate sum of square of even numbers
Write a C program to display the following pattern
1
25 12
1234
12345
Write a C program to display the following pattern
******
26
******
******

23
PPS Unit-III DIT,Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY PIMPRI, PUNE-411 018


DEPARTMENT OF FIRST YEAR ENGINEERING
CLASS: F.E. - (SEM – I) ACADEMIC YEAR: 2024-25
SUB: Fundamentals of Programming Languages

Unit 3: Control Flow


Practice Programs

Q. No. List of Programs


1 C program to Check Whether a Number is Positive or Negative or Zero
2 Program to Check Even or Odd
3 C Program to Check Vowel or Consonant
4 C program to Find the Largest Number Among Three Numbers
5 C Program to Calculate Sum of n-Natural Numbers
6 Leap Year Program in C
7 Program to find factorial of a number
8 Program to Print Multiplication Table in C using for loop.
9 Program to Print Alphabets From A to Z Using Loop
10 Fibonacci Series Program in C
11 C Program To Find LCM of Two Numbers
12 C Program to Check Armstrong Number
13 C Program to Reverse an Integer
14 Palindrome Number Program in C
15 Prime Number Program in C
16 C Program to Find All Factors of Number
C Program to Print Half Pyramid Pattern of Numbers
1
22
17
333
4444
55555

24
PPS Unit-III DIT,Pimpri

C Program to Print Inverted Half Pyramid Pattern of Numbers


666666
55555
18 4444
333
22
1
C Program To Print Triangle
*
**
19 ***
****
*****
******
C Program To Print Character Pyramid Pattern
A
BB
20
CCC
DDDD
EEEEE

Case Study

Sr.
Case Study
No.
1 C Program to Make a Simple Calculator
2 C program to display month by month calendar for a given year

25
PPS Unit-III DIT,Pimpri

Case Study

1. C Program to Make a Simple Calculator


#include <stdio.h>
double simpleCalc(double num1, double num2, char op)
{
double result;
switch (op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0)
{
result = num1 / num2;
}
else
{
printf("Error! Division by zero.\n");
return -1;
}
break;
default:
printf("Error! Operator is not correct.\n");
return -1;
}
return result;
}
int main()
{
char op;
double num1, num2, result;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf %lf", &num1, &num2);
result = simpleCalc(num1, num2, op);
printf("Result: %.2lf\n", result);
return 0;
}
26
PPS Unit-III DIT,Pimpri

2. C program to display month by month calendar for a given year

#include <stdio.h>
int dayNumber(int day, int month, int year)
{
static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
year -= month < 3;
return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7;
}

// Function that returns the name of the month for the given month Number
// January - 0, February - 1 and so on
char* getMonthName(int monthNumber)
{
char* month;
switch (monthNumber)
{
case 0:
month = "January";
break;
case 1:
month = "February";
break;
case 2:
month = "March";
break;
case 3:
month = "April";
break;
case 4:
month = "May";
break;
case 5:
month = "June";
break;
case 6:
month = "July";
break;
case 7:
month = "August";
break;
case 8:
month = "September";
break;
case 9:
month = "October";
break;
27
PPS Unit-III DIT,Pimpri

case 10:
month = "November";
break;
case 11:
month = "December";
break;
}
return month;
}

// Function to return the number of days in a month


int numberOfDays(int monthNumber, int year)
{
// January
if (monthNumber == 0)
return (31);

// February
if (monthNumber == 1)
{
// If the year is leap then Feb has 29 days
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
return (29);
else
return (28);
}

// March
if (monthNumber == 2)
return (31);

// April
if (monthNumber == 3)
return (30);

// May
if (monthNumber == 4)
return (31);

// June
if (monthNumber == 5)
return (30);

// July
if (monthNumber == 6)
return (31);
// August
28
PPS Unit-III DIT,Pimpri

if (monthNumber == 7)
return (31);

// September
if (monthNumber == 8)
return (30);

// October
if (monthNumber == 9)
return (31);

// November
if (monthNumber == 10)
return (30);

// December
if (monthNumber == 11)
return (31);
}

// Function to print the calendar of the given year


void printCalendar(int year)
{
printf(" Calendar - %d\n\n", year);
int days;

// Index of the day from 0 to 6


int current = dayNumber(1, 1, year);

// i for Iterate through months j for Iterate through days of the month - i
for (int i = 0; i < 12; i++)
{
days = numberOfDays(i, year);

// Print the current month name


printf("\n ------------%s-------------\n",getMonthName(i));

// Print the columns


printf(" Sun Mon Tue Wed Thu Fri Sat\n");

// Print appropriate spaces


int k;
for (k = 0; k < current; k++)
printf(" ");

for (int j = 1; j <= days; j++)


29
PPS Unit-III DIT,Pimpri

{
printf("%5d", j);
if (++k > 6)
{
k = 0;
printf("\n");
}
}

if (k)
printf("\n");

current = k;
}
return;
}

// Driver Code
int main()
{
int year = 2016;

// Function Call
printCalendar(year);
return 0;
}

30
PPS Unit-III DIT,Pimpri

Unit-III: Control Flow


C Programs

1. C program to Check Whether a Number is Positive or Negative or Zero


#include <stdio.h>
int main()
{
int A;
printf("Enter the number A: ");
scanf("%d", &A);
if (A > 0)
printf("%d is positive.", A);
else if (A < 0)
printf("%d is negative.", A);
else if (A == 0)
printf("%d is zero.", A);
return 0;
}

2. Program to Check Even or Odd


#include <stdio.h>
int main()
{
int N = 101;
int r = N % 2;
if (r == 0)
{
printf("Even");
}
else
{
printf("Odd");
}
return 0;
}

3. C Program to Check Vowel or Consonant


#include <stdio.h>
int main()
{
char ch = 'A';
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o'
|| ch == 'O' || ch == 'u' || ch == 'U')
{
printf("The character %c is a vowel.\n", ch);
31
PPS Unit-III DIT,Pimpri

}
else
{
printf("The character %c is a consonant.\n", ch);
}
return 0;
}

4. C program to Find the Largest Number Among Three Numbers

#include <stdio.h>
int main()
{
int A = 11, B = 2, C = 9;
printf("The numbers A, B and C are: %d, %d, %d\n", A, B,C);
if (A >= B && A >= C)
printf("%d is the largest number.", A);
else if (B >= A && B >= C)
printf("%d is the largest number.", B);
else
printf("%d is the largest number.", C);
return 0;
}

5. C Program to Calculate Sum of Natural Numbers


#include <stdio.h>
int main()
{
int i, s = 0;
int n = 10;
for (i = 0; i <= n; i++)
{
s += i;
}
printf("Sum = %d", s);
return 0;
}

6. Leap Year Program in C


#include <stdio.h>
int main()
{
int inputYear;
printf("Enter a year: ");
scanf("%d", &inputYear);
if ((inputYear % 4 == 0 && inputYear % 100 != 0) || (inputYear % 400 == 0))
32
PPS Unit-III DIT,Pimpri

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

7. Program to find factorial of a number


#include<stdio.h>
int main()
{
int i, number, factorial = 1;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1; i<=number; i++)
{
factorial = factorial * i;
}
printf("Factorial of %d is: %d",number, factorial);
return 0;
}

8. Program to Print Multiplication Table in C


#include <stdio.h>
int main()
{
int num, i = 1;
printf (" Enter a number to generate the table in C: ");
scanf (" %d", &num);
printf ("\n Table of %d \n ", num);
while (i <= 10)
{
printf (" %d x %d = %d \n", num, i, (num * i));
i++;
}
return 0;
}

9. Program to Print Alphabets From A to Z Using Loop


33
PPS Unit-III DIT,Pimpri

#include <stdio.h>
int main()
{
int i;
printf("Alphabets from (A-Z) are:\n");
// ASCII value of A=65 and Z=90
for (i = 65; i <= 90; i++)
{
printf("%c ", i);
}

printf("\nAlphabets from (a-z) are:\n");


// ASCII value of a=97 and z=122
for (i = 97; i <= 122; i++)
{
printf("%c ", i);
}
return 0;
}

10. Fibonacci Series Program in C


#include <stdio.h>
int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; ++i) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}

11. C Program To Find LCM of Two Numbers


#include <stdio.h>
int main()
{
int x = 15, y = 25, max;
max = (x > y) ? x : y;
// While loop to check if max variable is divisible by x and y
while (1)
{
if (max % x == 0 && max % y == 0)
34
PPS Unit-III DIT,Pimpri

{
printf("The LCM of %d and %d is %d.", x, y,max);
break;
}
++max;
}
return 0;
}

12. C Program to Check Armstrong Number


We can simply calculate the sum of individual digits by dividing the number by 10 and getting
reminders. And if it will be equal to the number itself then it is an Armstrong number.

#include <stdio.h>
int main()
{
int n = 153;
int temp = n;
int p = 0;
// Calculating the sum of individual digits
while (n > 0) {
int rem = n % 10;
p = (p) + (rem * rem * rem);
n = n / 10;
}
// Condition to check whether the value of P equals to user input or not.
if (temp == p)
{
printf("Yes. It is Armstrong No.");
}
else
{
printf("No. It is not an Armstrong No.");
}
return 0;
}

13. C Program to Reverse an Integer


#include <stdio.h>
int main()
{
int number, reversedNumber = 0, remainder;
printf("Enter a number: ");
scanf("%d", &number);
while (number != 0)
{
remainder = number % 10;
35
PPS Unit-III DIT,Pimpri

reversedNumber = reversedNumber * 10 + remainder;


number /= 10;
}
printf("Reversed number: %d\n", reversedNumber);
return 0;
}

14. Palindrome Number Program in C


#include <stdio.h>
int main()
{
int original_number = 12321;
int reversed = 0;
int num = original_number;
while (num != 0)
{
int r = num % 10;
reversed = reversed * 10 + r;
num /= 10;
}

if (original_number == reversed)
{
printf(" Given number %d is a palindrome number",original_number);
}
else
{
printf(" Given number %d is not a palindrome number",original_number);
}
return 0;
}

15. Prime Number Program in C


#include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for(i = 2; i <= n/2; ++i)
{
if(n%i == 0)
{
flag = 1;
break;
}
36
PPS Unit-III DIT,Pimpri

}
if (n == 1)
{
printf("1 is neither prime nor composite.");
}
else
{
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
return 0;
}

16. C Program to Find All Factors of Number


#include <stdio.h>
int main()
{
int number, i;
printf("Enter a positive integer: ");
scanf("%d", &number);
printf("Factors of %d are: ", number);
for (i = 1; i <= number; ++i)
{
if (number % i == 0)
{
printf("%d ", i);
}
}
return 0;
}

Pattern Printing

17. C Program to Print Half Pyramid Pattern of Numbers


#include <stdio.h>
int main()
{
int rows;
printf("Number of rows: ");
scanf("%d", &rows);
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
printf("%d ", i);
37
PPS Unit-III DIT,Pimpri

}
printf("\n");
}
return 0;
}

Output
Number of rows: 5
1
22
333
4444
55555

18. C Program to Print Inverted Half Pyramid Pattern of Numbers


#include <stdio.h>
int main()
{
int rows;
printf("Number of rows: ");
scanf("%d", &rows);
for (int i = rows; i >= 1; i--)
{
for (int j = 1; j <= i; j++)
{
printf("%d ", i);
}
printf("\n");
}
return 0;
}

Output
Number of rows: 6
666666
55555
4444
333
22
1

19. C Program To Print Triangle


#include <stdio.h>
int main()
{
int n = 6;
for (int i = 1; i <= n; i++) {
38
PPS Unit-III DIT,Pimpri

for (int j = 1; j <= i; j++) {


printf("*");
}
printf("\n");
}
return 0;
}

Output
*
**
***
****
*****
******

20. C Program To Print Character Pyramid Pattern

#include <stdio.h>
int main()
{
int i, j;
int rows = 5;
char character = 'A';
for (i = 0; i < rows; i++)
{
for (j = 0; j <= i; j++)
{
printf("%c ", character);
}
printf("\n");
character++;
}
return 0;
}

Output
A
BB
CCC
DDDD
EEEEE

39

You might also like