0% found this document useful (0 votes)
33 views36 pages

UNIT II CProgramming

cprograming

Uploaded by

samrudhsgowda097
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)
33 views36 pages

UNIT II CProgramming

cprograming

Uploaded by

samrudhsgowda097
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/ 36

C Programming Unit II: Control Structures

Formatted IO Functions
Formatted I/O functions are essential for handling user inputs and displaying outputs in a user-
friendly way. They enable programmers to:
Receive User Inputs: Formatted input functions help programs collect user input in a
structured manner. They use format specifiers to interpret and extract specific data types from
user input.
Present Data to Users: Formatted output functions allow programs to present data to users in
various formats. Format specifiers are used to control how data is displayed, making it more
readable and visually appealing.
Support Multiple Data Types: These I/O functions are versatile and support a wide range of
data types, including integers, floating-point numbers, characters, and more. Each data type
has corresponding format specifiers for precise formatting.
Formatting Control: Programmers can use format specifiers to control the alignment, width,
precision, and other formatting aspects of displayed data, ensuring it’s presented as intended.
These functions are called formatted I/O functions as they can use format specifiers in these
functions. Moreover, we can format these functions according to our needs.

Here are the list of some specifiers

The following formatted I/O functions will be discussed in this section-

1. printf()
2. scanf()
3. sprintf()
4. sscanf()
printf():
In C, printf() is a built-in function used to display values like numbers, characters, and strings
on the console screen. It’s pre-defined in the stdio.h header, allowing easy output formatting in
C programs.

scanf():

• scanf(): In C, scanf() is a built-in function for reading user input from the
keyboard. It can read values of various data types like integers, floats,
characters, and strings. scanf() is a pre-defined function declared in
the stdio.h header file. It uses the & (address-of operator) to store user input in
the memory location of a variable.

sprintf():sprintf(): Short for “string print,” sprintf() is similar to printf() but it stores the
formatted string into a character array instead of displaying it on the console screen.

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

sscanf():

sscanf(): Abbreviated for “string scanf,” sscanf() resembles scanf() but reads data from a
string or character array rather than from the console screen

Unformatted Input/Output functions

Unformatted I/O Functions: These functions are used exclusively for character data types or
character arrays/strings. They are designed for reading single inputs from the user at the console
and for displaying values on the console.
Why “Unformatted”?: They are referred to as “unformatted” I/O functions because they do
not support format specifiers. Unlike formatted I/O functions like printf() and scanf(), you
cannot use format specifiers to control the formatting of the data. They display or read data as-
is without formatting options.
The following are unformatted I/O functions

1. getch()
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()

getch(): In C, getch() reads a single character from the keyboard without displaying it on the
console screen. It immediately returns without requiring the user to press the Enter key. This
function is declared in the conio.h header file and is often used for controlling screen display.

getche():In C, getche() reads a single character from the keyboard, displays it on the console
screen, and immediately returns without requiring the user to press the Enter key. This function
is declared in the conio.h header file.

getchar(): In C, getchar() reads a single character from the keyboard and waits until the Enter
key is pressed. It processes one character at a time. This function is declared in
the stdio.h header file.

putchar():In C, putchar() is used to display a single character at a time, either by passing the
character directly or by using a variable that stores the character. This function is declared in
the stdio.h header file.

gets():In C, gets() reads a group of characters or strings from the keyboard, and these characters
are stored in a character array. It allows you to input space-separated texts or strings. This
function is declared in the stdio.h header file. However, please note that gets() is considered

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

unsafe due to the risk of buffer overflow and is generally discouraged in favor of safer
alternatives like fgets().

puts():

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

'if' Statement in C
What is Decision Making Statement?
In the C programming language, the program execution flow is line by line from top to bottom.
That means the c program is executed line by line from the main method. But this type of
execution flow may not be suitable for all the program solutions. Sometimes, we make some
decisions or we may skip the execution of one or more lines of code. Consider a situation,
where we write a program to check whether a student has passed or failed in a particular subject.
Here, we need to check whether the marks are greater than the pass marks or not. If marks are
greater, then we decide that the student has passed otherwise failed. To solve such kind of
problems in c we use the statements called decision making statements.
Decision-making statements are the statements that are used to verify a given condition
and decide whether a block of statements gets executed or not based on the condition
result.
In the c programming language, there are two decision-making statements they are as follows.
1. if statement
2. switch statement
if statement in c
In c, if statement is used to make decisions based on a condition. The if statement verifies the
given condition and decides whether a block of statements are executed or not based on the
condition result. In c, if statement is classified into four types as follows...
1. Simple if statement
2. if-else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)
Simple if statement
Simple if statement is used to verify the given condition and executes the block of statements
based on the condition result. The simple if statement evaluates specified condition. If it is
TRUE, it executes the next statement or block of statements. If the condition is FALSE, it skips

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

the execution of the next statement or block of statements. The general syntax and execution
flow of the simple if statement is as follows.

Simple if statement is used when we have only one option that is executed or skipped based on
a condition.
Example Program | Test whether given number is divisible by 5.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 5\n") ;
printf("statement does not belong to if!!!") ;
}
Output 1:

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

Output 2:

if-else statement
The if-else statement is used to verify the given condition and executes only one out of the two
blocks of statements based on the condition result. The if-else statement evaluates the specified
condition. If it is TRUE, it executes a block of statements (True block). If the condition is
FALSE, it executes another block of statements (False block). The general syntax and
execution flow of the if-else statement is as follows.

The if-else statement is used when we have two options and only one option has to be executed
based on a condition result (TRUE or FALSE).
Example Program | Test whether given number is even or odd.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

else
printf("Given number is ODD\n") ;
}
Output 1:

Output 2:

Nested if statement
Writing a if statement inside another if statement is called nested if statement. The general
syntax of the nested if statement is as follows...

The nested if statement can be defined using any combination of simple if & if-else statements.
Example Program | Test whether given number is even or odd if it is below 100.
#include<stdio.h>

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

#include<conio.h>

void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}
Output 1:

Output 2:

if-else-if statement (if-else ladder)


Writing a if statement inside else of an if statement is called if-else-if statement. The general
syntax of the if-else-if statement is as follows...

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

The if-else-if statement can be defined using any combination of simple if & if-else statements.
Example Program | Find the largest of three numbers.
#include<stdio.h>
#include<conio.h>
void main(){
int a, b, c ;
clrscr() ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &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) ;
}
Output:

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

'switch' statement in C
Consider a situation in which we have many options out of which we need to select only one
option that is to be executed. Such kind of problems can be solved using nested if statement.
But as the number of options increases, the complexity of the program also gets increased. This
type of problem can be solved very easily using a switch statement. Using the switch statement,
one can select only one option from more number of options very easily. In the switch
statement, we provide a value that is to be compared with a value associated with each option.
Whenever the given value matches the value associated with an option, the execution starts
from that option. In the switch statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.

The switch statement contains one or more cases and each case has a value associated with it.
At first switch statement compares the first case value with the switchValue, if it gets matched
the execution starts from the first case. If it doesn't match the switch statement compares the
second case value with the switchValue and if it is matched the execution starts from the second
case. This process continues until it finds a match. If no case value matches with the
switchValue specified in the switch statement, then a special case called default is executed.

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

When a case value matches with the switch Value, the execution starts from that particular case.
This execution flow continues with the next case statements. To avoid this, we use the "break"
statement at the end of each case. That means the break statement is used to terminate the
switch statement. However, it is optional.
Example Program | Display pressed digit in words.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any digit: ") ;
scanf("%d", &n) ;
switch( n ) {
case 0: printf("ZERO") ;
break ;
case 1: printf("ONE") ;
break ;
case 2: printf("TWO") ;
break ;
case 3: printf("THREE") ;
break ;
case 4: printf("FOUR") ;
break ;
case 5: printf("FIVE") ;
break ;
case 6: printf("SIX") ;
break ;
case 7: printf("SEVEN") ;
break ;
case 8: printf("EIGHT") ;

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

break ;
case 9: printf("NINE") ;
break ;
default: printf("Not a Digit") ;
}
getch() ;
}
Output 1:

Output 2:

'while' statement in C
Consider a situation in which we execute a single statement or block of statements repeatedly
for the required number of times. Such kind of problems can be solved
using looping statements in C. For example, assume a situation where we print a message 100
times. If we want to perform that task without using looping statements, we have to either write
100 printf statements or we have to write the same message 100 times in a single printf
statement. Both are complex methods. The same task can be performed very easily using
looping statements.
The looping statements are used to execute a single statement or block of statements
repeatedly until the given condition is FALSE.
C language provides three looping statements...
• while statement
• do-while statement
• for statement

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

while Statement
The while statement is used to execute a single statement or block of statements repeatedly as
long as the given condition is TRUE. The while statement is also known as Entry control
looping statement. The while statement has the following syntax...

The while statement has the following execution flow diagram...

At first, the given condition is evaluated. If the condition is TRUE, the single statement or
block of statements gets executed. Once the execution gets completed the condition is
evaluated again. If it is TRUE, again the same statements get executed. The same process is
repeated until the condition is evaluated to FALSE. Whenever the condition is evaluated to
FALSE, the execution control moves out of the while block.
Example Program | Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>

void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}

getch() ;
}
Output:

MOST IMPORTANT POINTS TO BE REMEMBERED


When we use a while statement, we must follow the following...
• while is a keyword so it must be used only in lower case letters.
• If the condition contains a variable, it must be assigned a value before it is used.
• The value of the variable used in condition must be modified according to the
requirement inside the while block.
• In a while statement, the condition may be a direct integer value, a variable or a
condition.
• A while statement can be an empty statement.
'do-while' statement in C

• The do-while statement is used to execute a single statement or block of statements

repeatedly as long as given the condition is TRUE. The do-while statement is also

known as the Exit control looping statement. The do-while statement has the
following syntax...

Swetha C V, DCA, Presidency College (Autonomous)


C Programming Unit II: Control Structures

• The do-while statement has the following execution flow diagram...

• At first, the single statement or block of statements which are defined in do block are

executed. After the execution of the do block, the given condition gets evaluated. If the

condition is evaluated to TRUE, the single statement or block of statements of do block

are executed again. Once the execution gets completed again the condition is evaluated.

If it is TRUE, again the same statements are executed. The same process is repeated

until the condition is evaluated to FALSE. Whenever the condition is evaluated to

FALSE, the execution control moves out of the while block.

Swetha C V, DCA, Presidency College (Autonomous)


break, continue and goto in C
Presidency
College
• There are control statements that do not need any
condition to control the program execution flow. These
control statements are called as unconditional control
statements. C programming language provides the
following unconditional control statements...
Reaccredited by
NAAC with A+
• break
• continue
• Goto

Presidency
Group The above three statements do not need any condition to
control the program execution flow.
break statement
Presidency
College
The break statement is used to perform the following
two things...
1. break statement is used to terminate the switch
case statement
Reaccredited by 2. break statement is also used to terminate looping
NAAC with A+
statements like while, do-while and for.
When a break statement is encountered inside the
switch case statement, the execution control moves out
Presidency
of the switch statement directly. For example, consider
Group
the following program.
Program to perform all arithmetic operations
using switch statement.
Presidency
College #include<stdio.h>
#include<conio.h>

void main(){
int number1, number2, result ;
char operator;
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &number1, &number2) ;
printf("Please enter any arithmetic operator: ");
operator = getchar();
switch(operator)
{
Reaccredited by case '+': result = number1 + number2 ;
printf("Addition = %d", result) ;
NAAC with A+ break;
case '-': result = number1 - number2 ;
printf("Subtraction = %d", result) ;
break;
case '*': result = number1 * number2 ;
printf("Multiplication = %d", result) ;
break;
case '/': result = number1 / number2 ;
printf("Division = %d", result) ;
Presidency break;
case '%': result = number1 % number2 ;
Group
printf("Remainder = %d", result) ;
break;
default: printf("\nWrong selection!!!") ;
}
getch() ;
}
Presidency
College
• When the break statement is encountered inside the
looping statement, the execution control moves out of the
looping statements. The break statement execution is as
shown in the following figure.

Reaccredited by
NAAC with A+

Presidency
Group
continue statement
Presidency
College
• The continue statement is used to move the program execution
control to the beginning of the looping statement.
• When the continue statement is encountered in a looping
statement, the execution control skips the rest of the statements
in the looping block and directly jumps to the beginning of the
Reaccredited by
loop.
NAAC with A+
• The continue statement can be used with looping statements
like while, do-while and for.
• When we use continue statement with while and do-
while statements the execution control directly jumps to the
Presidency condition.
Group
• When we use continue statement with for statement the
execution control directly jumps to the modification portion
(increment/decrement/any modification) of the for loop.
Presidency
College

Reaccredited by
NAAC with A+

Presidency
Group
Program to illustrate continue statement.
Presidency
College #include<stdio.h>
#include<conio.h>

void main(){
int number ;
clrscr() ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
Reaccredited by if(number%2 == 0)
NAAC with A+ {
printf("Entered number is EVEN!!! Try another number!!!\n") ;
continue ;
}
else
{
printf("You have entered ODD number!!! Bye!!!") ;
exit(0) ;
Presidency
}
Group
}
getch() ;
}
goto statement
Presidency
College
• The goto statement is used to jump from one line to
another line in the program.
• Using goto statement we can jump from top to bottom or
bottom to top.
• To jump from one line to another line, the goto statement
Reaccredited by
NAAC with A+ requires a label. Label is a name given to the instruction
or line in the program.
• When we use a goto statement in the program, the
execution control directly jumps to the line with the
Presidency specified label.
Group
Example Program for goto statement.
Presidency
College
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr() ;
Reaccredited by printf("We are at first printf statement!!!\n") ;
NAAC with A+
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
Presidency
last: printf("We are at last printf statement!!!\n") ;
Group
getch() ;
}
Note:
Presidency
College
• The break is a keyword so it must be used only in lower case letters.
• The break statement can not be used with if statement.
• The break statement can be used only in switch case and looping
statements.
• The break statement can be used with if statement, only if that if
statement is written inside the switch case or looping statements.
Reaccredited by
NAAC with A+ • The continue is a keyword so it must be used only in lower case
letters.
• The continue statement is used only within looping statements.
• The continue statement can be used with if statement, only if that if
statement is written inside the looping statements.
Presidency
Group • The goto is a keyword so it must be used only in lower case letters.
• The goto statement must require a label.
• The goto statement can be used with any statement like if, switch,
while, do-while, and for, etc.
Functions in C
Presidency
College
• Functions are used to divide a larger program into smaller
subprograms such that the program becomes easy to
understand and easy to implement.
• A function is defined as follows

Reaccredited by
A function is a subpart of a program used to
NAAC with A+
perform a specific task and is executed
individually.

Presidency
Group
Functions in C
Presidency
College
Every C program must contain at least one function called
main(). However, a program may also include other
functions.
Every function in C has the following...
• Function Declaration (Function Prototype)
Reaccredited by
NAAC with A+ • Function Definition
• Function Call

Presidency
Group
Function Declaration
Presidency
College
• The function declaration tells the compiler about function
name, the data type of the return value and parameters.
• The function declaration is also called a function
prototype.
• The function declaration is performed before the main
Reaccredited by
NAAC with A+ function, inside the main function, or any other function.

Presidency
Group
Function Definition
Presidency
College
• The function definition is also known as the body of the
function.
• The actual task of the function is implemented in the
function definition.
• The actual instructions of a function are written inside the
Reaccredited by
NAAC with A+ braces "{ }".

Presidency
Group
Function Call
Presidency
College
• The function call tells the compiler when to execute the
function definition.
• When a function call is executed, the execution control
jumps to the function definition where the actual code gets
executed and returns to the same functions call once the
Reaccredited by execution completes.
NAAC with A+

• The function call is performed inside the main function or


any other function or inside the function itself.

Presidency
Group
Types of Functions in C
Presidency
College
• Based on providing the function definition, functions are
divided into two types. Those are as follows...
• System Defined Functions
• User Defined Functions
Reaccredited by
NAAC with A+

Presidency
Group
Function without Parameters and without
Return value
Presidency
College

Reaccredited by
NAAC with A+

Presidency
Group
Function with Parameters and without Return
value
Presidency
College

Reaccredited by
NAAC with A+

Presidency
Group
Function without Parameters and with Return
value
Presidency
College

Reaccredited by
NAAC with A+

Presidency
Group
Function with Parameters and with Return value
Presidency
College

Reaccredited by
NAAC with A+

Presidency
Group
Recursive Functions in C
Presidency
College
• A function called by itself is called
recursive function.

Reaccredited by
NAAC with A+

Presidency
Group
Presidency
College

Reaccredited by
NAAC with A+

Presidency
Group

You might also like