0% found this document useful (0 votes)
3 views

Unit 2

The document provides an overview of formatted and unformatted input/output functions in C, including usage of printf() and scanf() with various format specifiers. It also explains control structures such as if statements, switch cases, and loops, detailing their syntax and examples. Additionally, it covers the concept of padding in output and the use of escape sequences.

Uploaded by

Harsh Borewar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit 2

The document provides an overview of formatted and unformatted input/output functions in C, including usage of printf() and scanf() with various format specifiers. It also explains control structures such as if statements, switch cases, and loops, detailing their syntax and examples. Additionally, it covers the concept of padding in output and the use of escape sequences.

Uploaded by

Harsh Borewar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT-II

 Formatted I/O : scanf(), printf(), Unformatted I/O : getch(), getchar(), gets(), putch(),
putchar(), puts().

1) Formatted input/output functions


i)printf()

This function is used to print text as well as value of the variables on the standard
output device (monitor), printf is very basic library function in c language that is declared in
stdio.h header file.
Syntax:
printf(“message”);
printf(“message + format-specifier”,variable-list);
 Format specifiers
Here are the list some of the format specifiers, use them in printf() & scanf() to format & print
values of the variables:
Character (char) %c
Integer (int) %d
Unsigned integer (unsigned int) %ld
Long (long) %ld
Unsigned long (unsigned long) %lu
Float (float) %f
Double (double) %lf
Octal Value (octal value) %o
Hexadecimal Value (hex value) %x
String (char[]) %s
 Escape Sequences
To print special extra line/spaces etc, we use escape sequences, these characters are followed by
‘\’ (slash).
\\ \
\” “
\’ ‘
\? ?
\a Alert
\b Back space
\n New Line
\t Horizontal tab
\v Vertical tab
\r Carriage return
 Padding integers with 0’s / Spaces
 Another important and useful concept is padding values with 0’s or Spaces.
 Padding with Space: Use %[n]d, here [n] is the number of characters, use %-[n]dfor
right space padding.
#include <stdio.h>
int main()
{
int a=10;
int b=1234;
int c=11111;

printf("\nLeft padded with spaces:");


printf("\na=%5d \nb=%5d \nc=%5d",a,b,c);

printf("\nRight padded with spaces:");


printf("\na=%-5d,b=%-5d,c=%-5d",a,b,c);
return 0;
}
Output
Left padded with spaces:
a= 10
b= 1234
c=11111
Right padded with spaces:
a=10 ,b=1234 ,c=11111
 Padding with Zeros: Use %0[n]d, here [n] is the number of characters.
#include <stdio.h>
int main()
{
int a=10;
int b=1234;
int c=11111;

printf("\nLeft padded with 0's:");


printf("\na=%05d \nb=%05d \nc=%05d",a,b,c);
return 0;
}
Output
Left padded with 0's:
a=00010
b=01234
c=11111
 Print value in Decimal, Octal & Hexadecimal format
 You can print integer value in following formats using following format specifiers:
 %d - Decimal
 %o - Octal (small ‘o’)
 %x - Hexadecimal (alphabets will print in small case)
 %X - Hexadecimal (alphabets will print in upper case)
 Consider the following example
 #include <stdio.h>
 int main()
 {
 int val=32106;

 printf("\nDecimal : %d",val);
 printf("\nOctal : %o",val);
 printf("\nHex : %x",val);
 printf("\nHex : %X",val);
 return 0;
 }

ii)scanf()
This function is used to get (input) value from the keyboard. We pass format specifiers, in which
format we want to take input.
Syntax:
scanf(“format-specifier”, &var-name);
scanf(“fromat-specifier-list”, &var-name-list);
First type of scanf() takes the single value for the variable and second type of scanf() will take
the multiple values for the variable list.
#include <stdio.h>

int main()
{

int a;
float b;
char c;

printf("Enter an integer number (value of a)?:");


scanf("%d",&a);
printf("Enter a float number (value of b)?:");
scanf("%f",&b);

printf("Enter a character (value of c)?:");


fflush(stdin); // to flush (clear) input buffer
scanf("%c",&c);

printf("\na=%d,b=%f,c=%c",a,b,c);
return 0;
}
Output
Enter an integer number (value of a)?:1234
Enter a float number (value of b)?:1.2345
Enter a character (value of c)?:G

a=1234,b=1.234500,c=G
to read multiple value in single scanf statement:
#include <stdio.h>

int main()
{

int a;
float b;
char c;

printf("\nEnter value of a,b,c (an integer, a float, a character):");


scanf("%d%f%c",&a,&b,&c);

printf("\na=%d,b=%f,c=%c",a,b,c);
return 0;
}
2) Unformatted input/output functions
i)getchar() and putchar() functions
1. getchar() is used to read one character at a time from console input (generally
keyboard). Ex: char c=getchar();and 2.putchar is used to display one character at a time
onto console output (generally monitor). It accepts one argument of character type. Ex:
char c; putchar(c);
syntax:int getchar(void);
Example:#include<stdio.h>
#include<conio.h>

void main()
{
char ch;
clrscr();
ch = getchar();
printf("Input Char Is :%c",ch);
getch();
}
2)putchar():syntax:int putchar(variable name);
Example: #include<stdio.h>
#include<conio.h>

void main()
{
char ch='a';
putchar(ch);

getch();
}

ii)gets() and puts() functions


1.gets() reads charactyers from the standard input and stores them as string while 2. Puts() prints
characters from the standard output like printf statement.
Syntax:gets(char_array_variable);
Puts(char_array_variable/string);

Example: #include<stdio.h>
#include<conio.h>
main()
{
char val[10];
clrscr();
printf(“enter the string”);
gets(val);
printf(“enterd data is”);
puts(val);
getch();
}
iii)getch() and putch() functions
1.getch() is used to get character from the console but does not echo to the screen.while putch()
displays any alphanumeric characters to the standard output device. It displays only one
character at za time.
Syntax:int getch(void);
Putch(variable name);

Example:
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
ch=getch();
printf(“the character entered is %c”,ch);
}

#include<stdio.h>
#include<conio.h>
void main()
{
char ch=’a’;
putch(ch);
}

iv)getche() and putche()


1.getche() is used to get a character from console, and echoes to the screen.
Syntax:int getche(void)

Example: #include<stdio.h>
#include<conio.h>
void main()
{
char ch;
ch=getche();
//printf(“the entered character is %c”,ch”);
getch();
}

 Control structures: Branching: if, if-else, Conditional operator(? : ), nested if, else-if Ladder.
Looping: while, do-while, for statements, comma operator, nested loops, goto, break, continue.

Control Structures

If statement

The single if statement in C language is used to execute the code if a condition is true. It is
also called one-way selection statement.

Syntax :

if(expression)

//code to be executed

}
Example:

//Program for if statement


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
print(“Enter value for a and b”);
scanf(“%d%d”,&a,&b);
if(a<b)
{
printf(“The a is greater”);
}
printf(“we are students”);
getch();
}

if-else statement
The if-else statement in C language is used to execute the code if condition is true or false. It is
also called two-way selection statement.
Syntax :
if(expression)
{ //Statements
}
Else
{
//Statements
}
Example:

//Program for if-else statement


#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
print(“Enter any number”);
scanf(“%d”,&num);
if(num%2==0)
{
printf(“The number is even”);
}
Else
{
printf(“The umber is odd”);
}
getch();
}

If..else If ladder
The if-else-if statement is used to execute one code from multiple conditions. It is also called
multipath decision statement. It is a chain of if..else statements in which each if statement is
associated with else if statement and last would be an else statement.

Syntax
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if
(condition3)
{ //statements
}
Else
{ //statements
}

Example:
//Program for nested if-else
#include<stdio.h>
#include<conio.h>
void main()
{
int side1,side2,side2;
clrscr();
printf(“Enter three sides of triangle”);
scanf(“%d%d%d”,&side1,&side2,&side3);
if(side1==side2&&side2==side3)
{
Printf(“The given triangle is equilateral”);
}
else if(side1==side2||side2==side3)
{
printf(“The given triangle is isosceles”);
}
else
{
Printf(“The given triangle is scalene”);
}
getch();
}

Nested-if

 A nested if in C is an if statement that is the target of another if statement. Nested if


statements means an if statement inside another if statement. Yes, both C and C++ allows
us to nested if statements within if statements, i.e, we can place an if statement inside
another if statement.
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{ // Executes when condition2 is true
}
}
//program for nested if
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf(“enter three numbers a,b and c”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf(“ a is greater”);
}
else
{
printf(“c is greater”);
}
}
else
{
if(b>c)
{
printf(“b is greater”);
}
else
{
printf(“ c iss greater”);
}
}
return 0;
}

switch case statement in C programming


switch case is a multiple branching statement which compares the value of expression or
variable inside switch() with various cases provided with the statement and executes
a block when a match is found. If no cases inside the switch is matched, the statements
inside default block is executed. However, default is optional and may not be present. It
is similar to else part of if statement.
switch case can be considered as simplified version of if statement. When there are large
number of conditions to be tested, it is difficult to use if statement as the number of
repeated if statements may cause confusion and makes the program unreadable.
So, switch case is preferred in such cases to simplify programmers job and increases code
readability.
example:
//program for switch case
#include<stdio.h>
#include<conio.h>
void main()
{
int day;
switch(day)
{
case1:printf(“it is monday today”);
break;
case2:printf(“it is tuesday today”);
break;
case3:printf(“it is wednesday today”);
break;
case4:printf(“it is thursday today”);
break;
case5:printf(“it is friday today”);
break;
case6:printf(“it is saturday today”);
break;
case7:printf(“it is sunday today”);
break;
default:printf(“it is monday today”);
}
getch();
}

Conditional operator

 The Conditional Operator in C, also called a Ternary operator, is one of the Operators,
which used in the decision-making process. The C Programming Conditional Operator
returns the statement depends upon the given expression result.
 The basic syntax of a Ternary Operator in C Programming is as shown below:
 Test_expression ? statement1: statement2
 Ex: (a>b)?printf(“a is greater”):printf(“b is greater”);
//Program for Conditional Operaters
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,ans;
clrscr();
printf("Enter the value of a and b");
scanf("%d%d",&a,&b);
ans=(a>b?a:b);
printf("The greater number is %d",ans);
getch();
}
OUTPUT:
Enter the value of a and b 5 6
The greater number is 6

What are Loops?


A Loop executes the sequence of statements many times until the stated condition
becomes false. A loop consists of two parts, a body of a loop and a control statement. The
control statement is a combination of some conditions that direct the body of the loop to
execute until the specified condition becomes false. The purpose of the loop is to repeat
the same code a number of times.
 Types of Loops in C
 Depending upon the position of a control statement in a program, looping in C is
classified into two types:
 1. Entry controlled loop
 2. Exit controlled loop
 In an entry controlled loop, a condition is checked before executing the body of a loop.
It is also called as a pre-checking loop.
 In an exit controlled loop, a condition is checked after executing the body of a loop. It is
also called as a post-checking loop.
 'C' programming language provides us with three types of loop constructs:
 1. The while loop
 2. The do-while loop
 3. The for loop

While Loop

 A while loop is the most straightforward looping structure. Syntax of while loop in C
programming language is as follows:
while (condition)
{
statements;
}
 It is an entry-controlled loop. In while loop, a condition is evaluated before processing a
body of the loop. If a condition is true then and only then the body of a loop is executed.
After the body of a loop is executed then control again goes back at the beginning, and
the condition is checked if it is true, the same process is executed until the condition
becomes false. Once the condition becomes false, the control goes out of the loop.
 After exiting the loop, the control goes to the statements which are immediately after the
loop. The body of a loop can contain more than one statement. If it contains only one
statement, then the curly braces are not compulsory. It is a good practice though to use
the curly braces even we have a single statement in the body.
 In while loop, if the condition is not true, then the body of a loop will not be executed,
not even once.

//Program to print table of given number using While loop

#include<stdio.h>
#include<conio.h>
void main()
{
int no,i=1;
clrscr();
printf("Enter number for which table is to be printed:-");
scanf("%d",&no);
printf("\nthe table of given number is");
while(i<=10)//While loop
{
printf("\n%d",no*i);
i++;
}
getch();
}

Do-While loop in C
 A do...while loop in C is similar to the while loop except that the condition is always
executed after the body of a loop. It is also called an exit-controlled loop.
Syntax :
do
{
Statements
}
while (expression);
 In the do-while loop, the body of a loop is always executed at least once. After the body
is executed, then it checks the condition. If the condition is true, then it will again execute
the body of a loop otherwise control is transferred out of the loop.
 Similar to the while loop, once the control goes out of the loop the statements which are
immediately after the loop is executed.
 The critical difference between the while and do-while loop is that in while loop the
while is written at the beginning. In do-while loop, the while condition is written at the
end and terminates with a semi-colon (;)
//Program to print table of given number using do-While loop

#include<stdio.h>
#include<conio.h>
void main()
{
int no,i=1;
clrscr();
printf("Enter number for which table is to be printed:-");
scanf("%d",&no);
printf("\nthe table of given number is");
do
{
printf("\n%d",no*i);
i++;
}
while(i<=10);
getch();
}

For loop in C
 A for loop is a more efficient loop structure in 'C' programming. The general
structure of for loop
 syntax
 for (initial value; condition; incrementation or decrementation )
 {
 statements;
 }
 The initial value of the for loop is performed only once.
 The condition is a Boolean expression that tests and compares the counter to a fixed
value after each iteration, stopping the for loop when false is returned.
 The incrementation/decrementation increases (or decreases) the counter by a set value.

//Program to print table of given number using for loop


#include<stdio.h>
#include<conio.h>
void main()
{
int no,i;
clrscr();
printf("Enter number for which table is to be printed:-");
scanf("%d",&no);
printf("\nthe table of given number is");
for(i=1;i<=10;i++)
{
printf("\n%d",no*i);

getch();
}

WHILE DO-WHILE

Statement(s) is executed
Condition is checked first then
atleast once, thereafter
statement(s) is executed.
condition is checked.

It might occur statement(s) is


At least once the
executed zero times, If
statement(s) is executed.
condition is false.

No semicolon at the end of Semicolon at the end of


while. while.
while(condition) while(condition);

If there is a single statement, Brackets are always


brackets are not required. required.

Variable in condition is variable may be


initialized before the execution initialized before or
of loop. within the loop.

while loop is entry controlled do-while loop is exit


loop. controlled loop.

while(condition) do { statement(s); }
{ statement(s); } while(condition);
goto statement in C
 A goto statement in C programming provides an unconditional
jump from the 'goto' to a labeled statement in the same function.

Example:
#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;
}
Break statement in C
 The break statement in C programming has the following two usages −
 When a break statement is used inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
 It can be used to terminate a case in the switch statement (covered in the next chapter).
Syntax:
//loop or switch case
break;

Example:
//Program for break in loop
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("the values of i printed due to break in loop are:-");
for(i=1;i<=10;i++)
{
if(i==5)
{
break;
}
printf("\n%d",i);
}
getch();
}
The continue statement in C
 The continue statement in C programming works somewhat like
the break statement. Instead of forcing termination, it forces the next
iteration of the loop to take place, skipping any code in between.
 Syntax
 The syntax for a continue statement in C is as follows −
 continue;

//Program for continue in loop


#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("the values of i printed due to break in loop are:-");
for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
printf("\n%d",i);
}
getch();
}

You might also like