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

UNIT II C

Uploaded by

then mozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

UNIT II C

Uploaded by

then mozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT – II

CHAPTER – 3

MANAGING INPUT AND OUTPUT OPERATIONS

The I/O functions are classified into two types:


 Formatted Functions
 Unformatted Functions

Input and Output functions

Formatted Functions Unformatted Functions

printf() getch()
scanf() getche()
getchar()
gets()
putch()
putchar()

Unformatted Functions:
They are used when I/P & O/P is not required in specific format.
C has three types I/O functions:
a) Character I/O
b) String I/O
c) File I/O
a) Character I/O:
1. getchar() This function reads a single character data from the
standard input.
(E.g. Keyboard)
Syntax :
variable_name=getchar()
;
Eg:
char c;
c=getcchar();
2. putchar() This function prints one character on the screen at a time.
Syntax:
putchar(variable name);

Eg:
char c=’C’;
putchar(c);
Example program:
#include<stdio.h>
main()
{
int i;
char ch;
ch = getchar();
putchar(ch);
}
Output:
A
A
3. getch() and getch(): getch() accepts only a single character from
keyboard. The character entered through getch() is not displaying in the
screen (monitor).
Syntax:
variable_name = getch();

Like getch(), getche() also accepts only single character, but getche() display
the entered character in the screen.
Syntax:
variable_name =
getche();
4. putch(): putch display any alphanumeric characters to the standard
output devices. It displays only one character at a time.
Syntax:
putch(variable_name);

b)String I/O:
1. gets() This function is used for accepting any string through stdin
(keyboard) until enter key is pressed.
Syntax:
gets(variable_name);

2. puts() This function prints the string or character array.


Syntax:
puts(variable_name);

3. cgets() This function reads string from the console.


Syntax:
cgets(char * st);

It requires character pointer as an argument.


4. cputs() This function displays string on the console.
Syntax:
cputs(char * st);

Example program:
void main()
{
char ch[30];
clrscr();
printf(“Enter the string:”);
gets(ch);
puts(“\nEnter the string: %s”,ch);
}
Output:
Enter the string: WELCOME
Enter the string WELCOME

FORMATTED INPUT AND OUTPUT FUNCTIONS

When I/P & O/P is required in a specified format then the standard library
functions scanf() & printf() are used.
Output function: printf()
The printf() function is used to print data of different data types on the
console in a specified format.
Syntax:

printf(“Control string”,var1, var2,….);

Control String may contain


1. Ordinary characters
2. Conversion Specifier Fields OR Format Specifiers
They denoted by %, contains conversion codes like %c, %d etc. and the
optional modifiers width, flag, precision and size.
Conversion codes
Data type Conversion
symbol
Char %c
int %d
Float %f
Unsigned octal %o
Pointer %p

Width Modifier:
It specifies the total number of characters used to display the value.
Precision:
It specifies the number of character used after the decimal point.
E.g: printf(“Number=%7.2\n”, 5.4321);
Width = 7
Precision = 2
Output: Number = 5.43 (spaces added in front of 5)
Flag:
It is used to specify one or more print modifications.
Flag Meaning
- Left justify the display
+ Display +ve or –ve sign of value
Space Display space if there is no sign
0 Pad with leading 0s

E.g: printf(“Number=%07.2\n”,5.4321)
Output: Number=0005.43
Size:
Size modifiers used in printf are,
%ld means long int variable
%hd means short int variable

Size modifier Converts To


L Long int
H Short int
L Long double

Control Codes
They are also known as Escape Sequences.
Control Code Meaning
\n New line
\t Horizontal Tab
\b Back space
Input function: scanf()
It is used to get data in a specified format. It can accept data of different
data types.
Syntax:

scanf(“Control strig”,var1address,
var2address,…);
Format string or Control string is enclosed in quotation marks. It may contain
1. White space
2. Ordinary number
3. Conversion specified field
It is denoted by % followed by conversion code and other optional modifiers
E.g: width, size.
Format specifiers for scanf()
Data type Conversion
symbol
Char %c
Int %d
Float %f
string %s

Example program:
#include<stdio.h>
Void main()
{
Int num1, num2, sum;
Printf(“Enter two integers:”);
Scanf(%d%d”, &num1, &num2);
Sum=num1+num2;
Printf(“sum:%d”,sum);
}
Output:
Enter two integers: 20 30
Sum: 50

CHAPTER – 4
DECISION MAKING AND BRANCHING
INTRODUCTION:
C language possesses such decision – making capabilities by supporting the
following statements:
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement

These statements are popularly known as decision – making statements.


Since these statements 'control' the flow of execution, they are also known
as control statements.
Decision making with if statement:
The if statement is powerful decision – making statement and is used to
control the flow of execution of statements. It is basically a two – way
decision statement and is used in conjunction with an expression. It takes
the following form:
if(test expression)
It allows the computer to evaluate the expression first and then, depending
on whether the value of the expression ( relation or condition ) is 'true' ( or
non – zero ) of 'false' ( zero ). This point of program has two paths to follow,
one for the true condition and other for the false condition.
The if statement may be implemented in different forms depending on the
complexity of conditions to be tested. The different forms are:
1. Simple if statement
2. if….else statement
3. Nested if….else statement
4. else if ladder.

Simple if statement:

The general form of a simple if statement is


if ( test expression )
{
statement – block;
}
statement – x;
 The 'statement - block' may be a single statement or a group of
statements. If the test expression is true, the statement – block will be
executed; otherwise the statement – block will be skipped and the execution
will jump to the statement – x.

Program
main()
{
int a, b, c, d;
float ratio;
printf(“Enter four integer values\n”);
scanf(“%d %d %d %d, &a, &b, &c, &d);
if ( c – d ! = 0 ) // Execute statement block
{
ratio = (float) ( a + b ) / (float) ( c – d );
printf(“Ratio = %f\n”, ratio);
}
}
Output
Enter four integer values
12 23 34 45
Ratio = - 3.181818
The if….else statement:
The if….else statement is an extension of the simple if statement. The

general form is
if ( test expression )
{
True – block statement (s)
}
else
{
False – block statement (s)
}
statement – x
 If the test expression is true, then the true – block statement (s),
immediately following the if statements are executed; otherwise, the false –
block statement (s) are executed. In either case, either true – block or false
– block will be executed, not both.

Program
int main ()
{
int a = 100;
if( a < 20 )
{
printf("a is less than 20\n" );
}
else
{
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
Output
a is not less than 20;
value of a is : 100
Nesting of if….else statements:
if ( testcondition – 1 )
{
if(test condition –2 );
{
statement – 1;
}
else
{
statement – 2;
}
else
{
statement – 3;
}
statement – x;
 If the condition – 1 is false, the statement – 3 will be executed;
otherwise it continues to perform the second test. If the condition – 2 is true,
the statement –1 will be evaluated; otherwise the statement – 2 will be
evaluated and the control is transferred to the statement – x.
Program
main()
{
Float A, B, C;
Printf(“Enter three values\n”);
Scanf(“%f %f %f”, &A, &B, &C);
Printf(“\nLargest value is”);
If (A>B)
{
If (A>C)
Printf(“%f\n”, A);
Else
Printf(“%f\n”, C);
}
Else
{
If (C>B)
Printf(“%f\n”, C);
Else
Printf(“%f\n”, B);
}
}
Output
Enter three values
23445 67379 88843
Largest value is 88843.000000
The else if ladder:
There is another way of putting ifs together when multipath decision are
involved. A multipath decision is a chain of ifs in which the statement

associated with each else is an if. It take the following form:


if ( condition 1 )
statement – 1;
else if ( condition 2 )
statement – 2;
else if ( condition 3 )
statement – 3;
else if ( condition n )
statement – n;
else
default – statement;
Statement –x;
 This construct is known as the else if ladder. The condition are
evaluated from the top ( of the ladder), downward. As soon as a true
condition of found, the statement associated with it is executed and the
control is transferred to the statement – x ( skipping the rest of the ladder ).
When all the n conditions become false, then the final else containing the
default – statement will be executed.
Program
main()
{
int units, custnum;
float charges;
printf (“Enter CUSTOMER NO. and UNITS consumed\n”);
scanf(“%d %d”, &custnum, &units);
if(units <= 200)
Charges = 0.5 * units;
else if ( unit <= 400)
charges = 100 + 0.65 * ( units – 200);
else if (units <= 600)
changes = 230 + 0.8 * (units – 400);
else
charges = 390 + (unit – 600);
printf (“\n\nCustomer No: %d: Charges = %.2f\n”, custnum, charges);
}
Output
Enter CUSTOMER NO. and UNITS consnum 101 150
Customer No: 101 Charges = 75.00
Enter CUSTOMER NO. and UNITS consnum202 225
Customer No: 202 Charges = 116.25
Enter CUSTOMER NO. and UNITS consnum303 375
Customer No: 303 Charges = 213.75
Enter CUSTOMER NO. and UNITS consnum404 520
Customer No: 404 Charges = 326.00
Enter CUSTOMER NO. and UNITS consnum505 625
Customer No: 505 Charges = 415.00
The switch statement:
C has a built – in multiway decision statement known as a switch. The
switch statement tests the value of a given variable ( or expression )
against a list of case values and when a match is found, a block of

statements associated with that case is executed.


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

Program
Output

Value is 8
The ?: Operator:
The c language has an unusual operator, useful for making two – way
decision. This Operator is a combination of ? and :, and takes three
operands. This operator is popularly known as the conditional operator. The
general form of use of the conditional operator is as follows:
conditional expression? expression1: expression 2
 The conditional expression is evaluated first. If the result is non – zero,
expression1 is evaluated and is returned as the value of the conditional
expression. Otherwise, expression 2 is evaluated and it’s value is returned.
 For example:
if ( x < 0 )
flag = 0;
else
flag = 1;
Can be written as
flag = ( x < 0 ) ? 0 : 1;

The goto statement:


A goto statement in C programming provides an unconditional jump from the
'goto' to a labeled statement in the same function.
goto label;
..
.
label: statement;
 Here label can be any plain text except C keyword and it can be set
anywhere in the C program above or below to gotostatement.
Program
#include <stdio.h>
int main ()
{
int a = 10;
LOOP:do
{
if( a == 15)
{
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

C LOOPS
FOR, WHILE, DO WHILE, LOOPING STATEMENTS
WITH EXAMPLES

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.

The control conditions must be well defined and specified otherwise the loop
will execute an infinite number of times. The loop that does not stop
executing and processes the statements number of times is called as
an infinite loop. An infinite loop is also called as an "Endless loop."
Following are some characteristics of an infinite loop:
1. No termination condition is specified.
2. The specified conditions never meet.

'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.
Following program illustrates while loop in C programming example:
Program
#include<stdio.h>
#include<conio.h>
int main()
{
intnum=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}
Output
1
2
3
4
5
6
7
8
9
10
Do-While loop:
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 of do...while loop in C programming language is as follows:

do {
statements
} while (expression);

As we saw in a while loop, the body is executed if and only if the condition is
true. In some cases, we have to execute a body of the loop at least once
even if the condition is false. This type of operation can be achieved by using
a do-while loop.
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
#include<stdio.h>
#include<conio.h>
int main()
{
intnum=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
return 0;
}
Output
2
4
6
8
10
12
14
16
18
20
1. First, we have initialized a variable 'num' with value 1. Then we have
written a do-while loop.
2. In a loop, we have a print function that will print the series by
multiplying the value of num with 2.
3. After each increment, the value of num will increase by 1, and it will be
printed on the screen.
4. Initially, the value of num is 1. In a body of a loop, the print function
will be executed in this way: 2*num where num=1, then 2*1=2 hence
the value two will be printed. This will go on until the value of num
becomes 10. After that loop will be terminated and a statement which
is immediately after the loop will be executed. In this case return 0.

For loop:
A for loop is a more efficient loop structure in 'C' programming. The general
structure of for loop syntax in C is as follows:
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
#include<stdio.h>
int main()
{
int number;
for(number=1;number<=10;number++) //for loop to print 1-10 numbers
{
printf("%d\n",number); //to print the number
}
return 0;
}
Output
1
2
3
4
5
6
7
8
9
10
Break Statement:
The break statement is used mainly in in the switch statement. It is also
useful for immediately stopping a loop.

We consider the following program which introduces a break to exit a while


loop:

#include <stdio.h>
int main() {
intnum = 5;
while (num> 0) {
if (num == 3)
break;
printf("%d\n", num);
num--;
}
}
Output
5
4
Continue Statement:
When you want to skip to the next iteration but remain in the loop, you
should use the continue statement.
#include <stdio.h>
int main() {
intnb = 7;
whilenb--;
if (nb == 5)
continue;
printf("%d\n", nb);
}
}
Output
6
4
3
2
1

You might also like