0% found this document useful (0 votes)
43 views23 pages

Unit 2

Uploaded by

dofat94986
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)
43 views23 pages

Unit 2

Uploaded by

dofat94986
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/ 23

Control Statements:

Loops
Loops in programming are used to repeat a block of code until the specified condition is met. A loop
statement allows programmers to execute a statement or group of statements multiple times without
repetition of code.

There are mainly two types of loops in C Programming:


1. Entry Controlled loops: In Entry controlled loops the test condition is checked before entering the
main body of the loop. For Loop and While Loop is Entry-controlled loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of the loop
body. The loop body will execute at least once, irrespective of whether the condition is true or
false. do-while Loop is Exit Controlled loop.

Loop Type Description

first Initializes, then condition check, then executes the body and at last, the
for loop
update is done.

first Initializes, then condition checks, and then executes the body, and
while loop
updating can be inside the body.

do-while
do-while first executes the body and then the condition check is done.
loop
1. for Loop
A for loop in C is a way to repeat a block of code a certain number of times. It has three main parts:

1. Initialization: Set a starting point (e.g., int i = 0) or we assign a loop variable or loop counter to
some value
2. Condition: In this expression, test conditions are performed. If the condition evaluates to true then
the loop body will be executed If the test expression becomes false then the control will exit from
the loop.

Check if it should keep running (e.g., i < 10).

3. Increment/Decrement: Update the variable (e.g., i++).

Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}

EXAMPLE

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


{

printf("%d\n", i);

}
Output
0
1
2
3
4
5
6
7
8
9

2. While Loop
While loop does not depend upon the number of iterations. In the While loop, the execution is terminated
on the basis of the test condition. If the test condition will become false then it will break from the while
loop else body will be executed.

Syntax:
initialization_expression;

while (test_expression)
{
// body of the while loop

update_expression;
}
Flow Diagram for while loop:
#include <stdio.h>
int main()
{
int i = 2;
while(i < 5)
{
printf( "BCA \n");
i++;
}
return 0;
}
Output
BCA
BCA
BCA

3. do-while Loop
A do while loop in C is a way to repeat a block of code at least once and then continue repeating it as long as
a condition is true. The key feature is that the code inside the loop runs before the condition is checked.

Here's the basic structure:

1. Do: Start the block of code.


2. While: Check the condition after the code runs.

Syntax:
initialization_expression;
do
{
// body of do-while loop

update_expression;

} while (test_expression);
#include <stdio.h>
int main()
{
// Initialization expression
int i = 2;

do
{
// loop body
printf( "Hello BCA\n");

// Update expression
i++;

// Test expression
} while (i < 1);

return 0;
}
Output:
Hello BCA
4. Nested loops
A nested loop means a loop statement inside another loop statement. That is why nested loops are also
called “loop inside loops“. We can define any number of loops inside another loop.

Nested for loop refers to any type of loop that is defined inside a ‘for’ loop. Below is the equivalent flow
diagram for nested ‘for’ loops:

Nested for loop in C

Syntax:
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{
// statement of inside loop
}

// statement of outer loop


}

Example
#include <stdio.h>
int main( )
{
int rows = 5;
// Outer loop for rows
for (int i = 1; i <= rows; i++) {
// Inner loop for columns
for (int j = 1; j <= i; j++) {
printf("* "); // Print an asterisk
}
printf("\n"); // Move to the next line after each row
}
return 0;
}

OUTPUT
*
**
***
****
*****

Decision Making in C
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are
used for decision-making purposes in C programs.

Need of Conditional Statements


There come situations in real life when we need to make some decisions and based on these decisions, we
decide what should we do next. Similar situations arise in programming also where we need to make some
decisions and based on these decisions we will execute the next block of code.

Types of Conditional Statements in C


1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement

if statement
The if statement is the most simple decision-making statement. if statement in C is used to make decisions
in your code. It checks a condition, and if that condition is true, it runs a block of code. If the condition is
false, it skips that block.
Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
}

#include <stdio.h>
int main()
{
int i = 10;
if (i > 15)
{
printf("10 is greater than 15");
}
printf("I am Not in if");
}
Output
I am Not in if

if-else in C
The if-else statement consists of two blocks, one for false expression and one for true expression. It
checks a condition: if the condition is true, it runs if block of code; if it's false, it runs else block of code.
]
Syntax of if else in C
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

#include <stdio.h>
int main()
{
int i = 20;
if (i < 15)
{
printf("i is smaller than 15");
}
else
{
printf("i is greater than 15");
}
return 0;
}
Output
i is greater than 15
Nested if-else
Nested if statements mean an if statement inside another if statement.
Nested if-else statement is when you have an if-else block inside another if or else block.
It's like placing one decision within another decision.
You use this when you want to check for a new condition after a previous condition has already been found
true (or false).
Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{
// statement 1
}
else
{
// Statement 2
}
}
else {
if (condition_3)
{
// statement 3
}
else
{
// Statement 4
}
}

#include <stdio.h>
int main( )
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
printf("You are an adult.\n");

if (age >= 65)


{
printf("You are a senior citizen.\n");
}
else
{
printf("You are not a senior citizen.\n");
}
}
else
{
printf("You are a child.\n");
}
return 0;
}
Output
Enter your age: 15
You are a child.

if-else-if Ladder
 The if else if statements are used when the user has to decide among multiple options.
 The C if statements are executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is
bypassed.
 If none of the conditions is true, then the final else statement will be executed.

Syntax of if-else-if Ladder


if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
#include <stdio.h>
int main()
{
int i = 20;

if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}
Output
i is 20

switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to execute the
conditional code based on the value of the variable specified in the switch statement.
The switch block consists of cases to be executed based on the value of the switch variable.

Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
Note: The switch expression should evaluate to either integer or character. It cannot evaluate any other
data type.
Flowchart of switch

#include <stdio.h>
int main()
{
int var = 2;
switch (var)
{
case 1:printf("Case 1 is executed");
break;
case 2:printf("Case 2 is executed");
break;
default:
printf("Default Case is executed");
break;
}
return 0;
}
Output
Case 2 is executed

Jump Statements:
These statements are used in C for the unconditional flow of control throughout the functions in a
program. They support four types of jump statements:
 break
 continue

break Statement
1.Break is a keyword

2.It is used to "jump out" of a switch statement.

3.The break statement can also be used to jump out of a loop.

This will stop the execution of more code


When a match is found, and the job is done, it's time for a break.

This example jumps out of the for loop when i is equal to 4:


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

OUTPUT
continue Statement
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with
the next iteration in the loop.

This example skips the value of 4:

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

OUTPUT
Formatted Input/Output functions in C
Formatted I/O functions are used to take various inputs from the user and display multiple outputs to the
user.
These I/O supports all data types like int, float, char, and many more.

Why they are called formatted I/O?

These functions are called formatted I/O functions because we can use format specifiers in these functions
and hence, we can format these functions according to our needs.
List of some format specifiers-
Sr. Format Specifier
Type Description
NO.

1 %d int/signed int used for I/O signed integer value

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

Used for I/O string/group of characters


4 %s string

5 %ld long int Used for I/O long signed integer value

unsigned int
6 %u Used for I/O unsigned integer value

The following formatted I/O functions are:


1. printf()
2. scanf()
3. sprintf()
4. sscanf()

1.printf():
printf() function is used in a C program to display any value like float, integer, character, string, etc on the
console screen.
It is a pre-defined function that is already declared in the stdio.h(header file).
Syntax:
printf(“Format Specifier”, var1, var2, …., varn);
#include <stdio.h>
int main()
{
int a;
a = 20;
printf("%d", a);

return 0;
}

2. scanf():
scanf() function is used in the C program for reading or taking any value from the keyboard by the user,
these values can be of any data type like integer, float, character, string, and many more. This function is
declared in stdio.h(header file).

Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);

#include <stdio.h>
int main()
{
int num1;
printf("Enter a integer number: ");
scanf("%d", &num1);
printf("You have entered %d", num1);
return 0;
}

3. sprintf():
sprintf stands for “string print”. This function is similar to printf() function but this function prints the
string into a character array instead of printing it on the console screen.

Syntax:
sprintf(array_name, “format specifier”, variable_name);
#include <stdio.h>
int main()
{
char str[50];
int a = 2, b = 8;

// The string "2 and 8 are even number"


// is now stored into str
sprintf(str, "%d and %d are even number",
a, b);
printf("%s", str);
return 0;
}

Output:
2 and 8 are even number

4.sscanf():
sscanf stands for “string scanf”. This function is similar to scanf() function but this function reads data
from the string or character array instead of the console screen.

Syntax:
sscanf(array_name, “format specifier”, &variable_name);

#include <stdio.h>
int main()
{
char str[50];
int a = 2, b = 8, c, d;

// The string "a = 2 and b = 8"


// is now stored into str
// character array
sprintf(str, "a = %d and b = %d",
a, b);
// The value of a and b is now in
// c and d
sscanf(str, "a = %d and b = %d",
&c, &d);

// Displays the value of c and d


printf("c = %d and d = %d", c, d);
return 0;
}
Output
c = 2 and d = 8

Unformatted Input/Output functions in C


Unformatted I/O functions are used only for character data type or character array/string and cannot be
used for any other datatype. These functions are used to read single input from the user at the console and
it allows to display the value at the console.

Why they are called unformatted I/O?


These functions are called unformatted I/O functions because we cannot use format specifiers in these
functions and hence, cannot format these functions according to our needs.
The following unformatted I/O functions will be discussed in this section-
1. getch( )
2. getchar( )
3. putchar( )
4. gets( )
5. puts( )

getch( ):
getch() function reads a single character from the keyboard by the user but doesn’t display that character
on the console screen and immediately returned without pressing enter key. This function is declared in
conio.h(header file). getch() is also used for hold the screen.

Syntax:
getch();
or
variable-name = getch();

#include <conio.h>
#include <stdio.h>

int main()
{
printf("Enter any character: ");

// Reads a character but


// not displays
getch();
return 0;
}

Output:
Enter any character:

getchar( ):
The getchar() function is used to read only a first single character from the keyboard whether multiple
characters is typed by the user and this function reads one character at one time until and unless the enter
key is pressed. This function is declared in stdio.h(header file)

Syntax:
Variable-name = getchar();

#include <conio.h>
#include <stdio.h>
int main()
{
char ch;
printf("Enter the character: ");
// Taking a character from keyboard
ch = getchar();
// Displays the value of ch
printf("%c", ch);
return 0;
}
Output:
Enter the character: a
A
putchar( ):
The putchar() function is used to display a single character at a time by passing that character
directly to it or by passing a variable that has already stored a character. This function is declared
in stdio.h(header file)

Syntax:
putchar(variable_name);

#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
char ch;
printf("Enter any character: ");
// Reads a character
ch = getchar();

// Displays that character


putchar(ch);
return 0;
}

Output:
Enter any character: Z
Z

gets( ):
gets() function reads a group of characters or strings from the keyboard by the user and these characters
get stored in a character array. This function allows us to write space-separated texts or strings. This
function is declared in stdio.h(header file).

Syntax:
char str[length of string in number]; //Declare a char type variable of any length
gets(str);

#include <conio.h>
#include <stdio.h>
int main()
{

char name[50];
printf("Please enter some texts: ");
// Reading a line of character or
// a string
gets(name);

// Displaying this line of character


// or a string
printf("You have entered: %s", name);
return 0;
}
Output:
Please enter some texts: BCA STUDENTS
You have entered: BCA STUDENTS

puts( ):
In C programming puts() function is used to display a group of characters or strings which is already
stored in a character array. This function is declared in stdio.h(header file).

Syntax:
puts(identifier_name );

#include <stdio.h>
int main()
{
char name[50];
printf("Enter your text: ");

// Reads string from user


gets(name);

printf("Your text is: ");


// Displays string
puts(name);
return 0;
}

Output:
Enter your text: BCA STUDENTS
Your text is: BCA STUDENTS

Formatted I/O vs Unformatted I/O


S
Formatted I/O functions Unformatted I/O functions
No.

These functions allow us to take input or display These functions do not allow to take input or
1
output in the user’s desired format. display output in user desired format.

2 These functions support format specifiers. These functions do not support format specifiers.

These are used for storing data more user


3 These functions are not more user-friendly.
friendly

Here, we can use only character and string data


4 Here, we can use all data types.
types.

printf(), scanf, sprintf() and sscanf() are getch(), getche(), gets() and puts(), are some
5
examples of these functions. examples of these functions.

You might also like