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

c unit II

best notes

Uploaded by

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

c unit II

best notes

Uploaded by

Amogh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit II

IO Operations and Control structures


Input and output with C:
Input is a means to provide the program with some data to be used and
output to display data on screen. The input and output statements
involving format specifiers are called formatted input output
statements. Those without format specifiers are called unformatted
input output statements. C language provides many built-in functions
for this purpose.
Formatted input/output functions: These functions are used to
take one or more inputs from the user & allow us to display one or
multiple values in the output to the user. There are two functions for
performing formatted input-output. They are:
1. printf ( ) -formatted output
2. scanf ( ) -formatted input
Input Output
functions functions
scanf() printf( )
getchar( ) putchar( )
getch( ) putch( )
getche( ) puts( )
gets( )
All these built-in functions are present in C header files. The standard
input output header file stdio.h provides formatted console based i/o
functions. The console input output header file conio.h provides
unformatted console based i/o functions.

1.The printf() function: The printf( ) function is used to display the


data on the monitor. It is included in the header file stdio.h. The general
form of printf ( ) function is,
printf (“control string”,var_list);
Where: control specifies the format of the value and var_list specifies a list
of variables
eg: printf(“%d”,n);
printf(“%f%f”,p,q);
printf (“programming in c”);
2.The scanf () function: C provides a function scanf () to i/p the
values for the variables from the keyboard. It is used to enter the numeric,
character or string type data.
Syntax: scanf (“control string”, address_list);
Where: control string specifies the sequence of one or more format
specifiers. The address list specifies the address of memory locations where
the values of variables should be stored.
e.g: 1. scanf(“%d
%f”,&x,&y);
2. scanf (%c%s”,&ch,st);
Escape sequence characters or Backslash character constants: C
supports back slash character constants that are used in o/p statements.
They use a back slash (\) followed by a character.
Constant Meaning
\n new line( line feed)
\t horizontal tab space
\v vertical tab space
\b back spsce
\r carriage return
\\ back spsce
\” quotation marks
\’ apostrophe
\0 NULL

Format specifier or Conversion specifiers or Control strings:


Format specifiers are used in formatted input & output operations.
Format specifiers are used for formatting the data, for example, in
printf() and scanf() . They begin with a % & ends with a conversion
character. Following format specifiers are used based on the nature of
data type.
Format Specifier Data type
%i signed integer
%d signed decimal integer
%c character
%f signed float value
%e float value in exponential form
%o unsigned octal value
%x or %X unsigned hexa decimal integer value
%u unsigned integer
%p pointer value
%ld signed long integer decimal

Unformatted i/p functions: These functions are used to read


character data from the keyboard. The getchar( ) & gets( ) are used for
this purpose. They are included in the header file stdio.h.
1.The getchar() function: This function reads a single character from
the keyboard. There is no parameter within the parenthesis.
Syntax: var = getchar( );
Where var specifies the character type variable to which an accepted
character is assigned.

Program to illustrate getchar()


#include<stdio.h>
main()
{
char c;
printf("Enter a character : "); c = getchar();
printf("\nEntered character : %c ", c);
} Enter a character : y Entered character : y

2.getch() Function: The getch() function reads the alphanumeric


character from the user. The
entered character will not be displayed (echoed). getch() is used to hold
the output window on the screen after the whole program run is
completed till we enter a key from keyboard.
However, the character entered is not displayed on screen. For that we use
getche() function. #include<stdio.h>
main()
{
char ch;
printf("Enter a character :"); ch=getch();
printf("\nEntered character is : %c",ch); Enter a character : G Entered character : G
}

Note: int main() is an old style declaration that indicates main takes an
unspecified number of arguments.
3.The gets() function: This function reads all characters entered from
the keyboard until the ENTER key or RETURN key is pressed.
Syntax: gets(string);
Unformatted o/p functions: These functions are used to print the
character type data on the monitor. The putchar( ) and puts( ) are used
for this purpose. Both these functions are defined in the header file
stdio.h.
1.The putchar()function: This function points a single character
on the screen. The variable to be displayed is of type char.
Syntax: putchar (var);
Where: var specifies a character type variable which is enclosed within the
parenthesis.
A program to illustrate the use of getchar and putchar
#include<std
io.h> main( )
{
char ch;
ch=getc
har( );
putchar
(ch);
}
2.The puts( ): This function prints a set of characters on the screen.
Syntax:puts (string); where: string specifies a sequence of characters.
WAP to read and print a string using gets( ) and puts( )
#include<stdi
o.h> main( )
{
char name[20];
printf(“enter your name:\n”);
gets(n
ame);
puts(n
ame);
getcha
r( );
}
Functio Descript
n ion
Reads a single character from the user at
getch()
the console, without echoing it.
Reads a single character from the user at the
getche()
console, and echoing it.
Reads a single character from the user at the
getchar(
) console and echoing it, but needs an Enter key to
be pressed at the end.
gets() Reads a single string entered by the user at the
console.
puts() Displays a single string's value at the console.
putchar( Displays a single character value at the console.
)

Echoing means displaying


Decision making, Branching and looping
C supports structured programming by supporting 3 basic control
structures.
1. Sequence structure.
2. Selection structure.
3. Loop structure.
Sequence statements are executed instruction after instruction.
Selection Statements: The selection statements are executed depending
on the truth ness of the condition. There are two types of selection
statements.
1. Conditional control statements
2. Looping statements
Conditional control statements: C provides two types of
conditional statements.
1. The if statements
2. The switch statements
1. The if statements: There are 4 types of if statements. 1. Simple if
2. The if else
statement
3. Nested if
4. The else if ladder

1. Simple if: The simple if statement is executed if the condition is true.


If the condition is false, no execution of the statement.
Syntax:
if (condition) false
if
Statement; (cond)D

Program to find greatest of two numbers.


#include<stdio.h> Statement block
main()
{ Statement after if
int a,b,big;
clrscr();
printf(“enter a and b values\n”);
scanf(“%d%d”,&a,&b);
big=a;
if(big<b)
big=b;
printf(“ largest of %d and %d is %d”,a,b,big);
getch();
}

Program to check the number is even.


#include<stdio.h>
main()
{
int a;
clrscr();
printf(“enter the value of a\n”);
scanf(“%d”,&a);
if(a%2==0)
printf(“%d is even”,a);
getch();
}
2. The if else statement: The if else is a two way branching statement

Syntax: if(condition)
if
statement 1; false CondD true

else
statement 2; Statement 2
If condition is true statement 1 is executed Statement 1
and skips statement 2. If condition is false,
statement 2 is executed and skips Statement after if
statement1.
Program to find greatest of 2 numbers.
#include<stdio.h>
Program to find the largest of 2 numbers
main()
{
int a,b;
printf(“enter two numbers”); scanf(“%d%d”,&a,&b);
if(a>b)
printf(“%d is greater”,a); enter the value of a and b
else 15 35
35 is greater
printf(“(“%d is greater”,b);
getch();
}

Program to check the given number is positive or negative

#include<stdio.h>
main()
{
int a; enter a number
15
15 is positive
printf(“enter a number”); scanf(“%d”,&a);
if(a>0)
printf(“%d is positive”,a);
else
printf(“%d is negative”,a);
}

Program to check the year is leap or not.


#include<stdio.h>
main()
{
int year;
printf(“enter a year\n”); scanf(“%d”,&year);
if(year%4==0)
printf(“the given year is leap”);
else
printf(“the given year is not leap”);
getch();
}

Nested if statement: Enclosing an if statement with in another if statement


is called nested if statement. This is a multi way decision statement in which
an action is performed based on several conditions.
if (cond1 )
if(cond 2)
{
statement1;
else
statement 2;
}
else
statement 3;
Program to find the largest of 3 numbers using nested if
main()
{
int a,b,c;
printf(“enter the a,b,c values\n”); 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 is greater”);
getch();
}
3.The else if ladder: This is an extension of if-else structure. This is a
multi-way branching statement. The control moves towards the false side of
the program.
Syntax: if (condition-1)
Statement-1;
else if(condition-2)
Statement-2;
else if(condition-3)
Statement-3;
else if(codition-4)
Statement-4;
else
statement-5;

true
Cond-1
false
true
Cond-2
St-1

false
St-2
Cond-3

false true
St-4 St-3

next

Program to find the largest of 3 numbers using else if ladder


4.The switch statement: This is a multi-way branching statement in which
only one of the possible statements is executed while the remaining
statements are skipped.
Syntax: switch (expression)
{
case 1 : statement 1; break;
case 2 : statement 2 ;break;
……………………………………
case n : statement n; break;
default : default statement;
}
The break is needed if you want to terminate the switch after execution of
one choice. Otherwise the next case would get evaluated.
Program to evaluate arithmetic operators using switch statement
#include<stdio.h>
main()
o/p
{ enter a and b values
int a,b,opr; 15
clrscr(); 9
printf(“enter a and b value”);scanf(“%d%d”,&a,&b); enter your option
printf(“enter your option\n”);scanf(“%d”,&opr); 1
switch(opr) 15+9=24
{ enter a and b values
case 1: printf(“%d+%d=%d”a,b,a+b); break; 10
case 2: printf(“%d-%d=%d”, a,b, a-b); break; 4
case 3: printf(“%d*%d=%d”, a,b, a-b); break; enter your option
case 4: printf(“%d/%d=%d”, a,b, a-b); break; 3
default: printf(“your option is wrong”); 10*4=40
}
getch();
}

LOOPS
The process of repeating the execution of a certain set of statements
again & again is called looping. C has 3 looping statements they are
1. while
2. do while
3. for
The while and do while are used when the programmer does not know
exactly the number of executions. Thus the execution will be repeated until
the condition become false. The for loop is normally used when the number
of repetitions is know in advance.

1. The while statement: This is a pre-tested looping statement


(condition is check at the beginning). If the condition is true it enters the
loop otherwise it skips the loop. Ones it enters to the loop the statements
false
are executed again and again.
When the condition becomes false the control goes out of the loop.
(cond)

Syntax:
while ( condition )
true
{
Statement ;
statement 1;
statement 2;
…………….; Inc/dec
statement n;
} Next statement

2. do while statement: This is a post-tested loop. In this case control


enters directly to the loop and executes the statements. At the end it checks
the condition, if the condition is true it starts repeated execution otherwise
the loop ends. Statement 1;
Syntax:
do Is (Cond)
true
{

statement 1;
statement 2;
Next statement
…………….;
statement n; false
}
while ( condition);

3. The for loop: The for statement is a “fixed execution” looping


structure. This is also a post-tested looping statement. The general form of
for statement is
for (expression 1; expression 2; expression 3)
{
Statement 1;
Statement 2;
Statement n; Where
} for (expression 1; expression 2; expression 3 )

Initialization condition increment or

Working:
1. expression1is first evaluated i.e. initialize values for declared variables
2. expression 2: checks the condition; suppose the condition is true it enter
the loop.
Otherwise it skips the loop.
3. expression 3: Control send back to beginning of the structure, the value
of variable is incremented or decremented depending on
the expression.
for (initialization; condition; updation)
false true

Statements;
Next statement

Difference between while and do while

Sl.N
while do while
o
1. This is pre- tested loop This is post tested loop

2. Minimum execution of loop is Minimum execution of loop is


zero once.
3.
Syntax: while ( condition) Syntax: do
{ {
statement 1; statement 1;
…………….; …………….;
statement n; statement n;
} }while ( condition);

Semi colon is not used. Semi colon is used.

Simple programs using while, do while and for

1. Write a program to print n natural numbers;


Program using while

#include<stdio.h>
main()
{
int a=1,n;
clrscr();
printf(“enter number”);
scanf(“%d”,&n);
while (a<=n)
{
printf(“%d”,a);
a++;
}
getch();
}Program using do while

#include<stdio.h>
main()
{
int a=1,n;
clrscr();
printf(“enter number”);
scanf(“%d”,&n);
do
{
printf(“%d”,a);
a++;
Program
} using for loop
while (a<=n);
#include<stdio.h>
getch();
main()
}
{
int a,n;
clrscr();
printf(“enter number”);
scanf(“%d”,&n);
for(a=1;a<=n;a++)
printf(“%d\n”,a);
getch();
}

Nested loops: Enclosing one looping statement inside another is called


nested loop. if one for statement is performed with in another the sequence
is called nested for.
In nested loops, the inner loop is completely enclosed by the outer
loop i,e the inner loop is completely repeated for each repetition of the
outer loop.

Write a program to generate the following pattern


#include<stdio.h> *
#include<conio.h> * *
main()
{ * * *
int r, c; * * * *
clrscr();
for(r=1;r<=4;r++)
{
for(c=1; c <= r; c++ )
printf("* \t”);
}
printf("\n”);
getch();
}
Write a program to generate the following pattern
1
#include<stdio.h> 2 2
main() 3 3 3
{
4 4 4 4
int r, c, n;
clrscr();
for(r=1;r<=n;r++)
{
for(c=1;c<=r;c++)
printf("%d \t”,r);
}
printf("\n”);
getch();
}

Write a program to generate the following pattern 1

#include<stdio.h> 1 2
main() 1 2 3
{ 1 2 3 4
int r, c, n;
clrscr();
for(r=1;r<=n;r++)
{
for(c=1;c<=r;C++)
printf("%d \t”,c);
}
printf("\n");
}
Wap to generate the following pattern 1
2 3
4 5 6

7 8 9 10

Infinite Loop(endless loop): A loop that results in execution of the


statement infinite times is called Infinite loop. A loop that never terminates
is called infinite loop
#include<stdio.h>
main()
{
for(;;)
printf("UCST\n");
getch();
}

There is no way to stop an infinite loop. To pause the infinite loop


press the BREAK or CTRL +BREAK . It will return back to the program
Jump Statements : The statement which are unconditionally transfer
the program control within a function are called jump statements. There are
four jump statements.

1. break
2. continue
3. exit()
4. goto
5. return.

goto and return statements are used anywhere in the program while break
and continue are used inside the loop. In addition the function exit() is also
used inside the loop.

The break statement: The break statement is used to terminate the


loop. When break statement is encountered in a loop the control passes to
the 1st statement after the loop
Syntax break;
Program to illustrate break statement
o/p
#include<stdio.h>
main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
break;
printf(“%d\n”,i);
}
printf("KARNATAKA\n");
}

The continue statement : When the key word continue is encountered the
control automatically pass brak to the beginning of the loop
Syntax:continue;
#include<stdio.h>
main()
{
int i; o/p
for(i=1;i<=5;i++)
{
if(i==3)
continue;
printf(“%d\n”,i);
}
printf("KARNATAKA \n");
}

Difference Between break and continue


break continue
A break can appear in both A continue can appear only in loop
switch and loop statements. statements.

When a break statement is When a continue statement is encountered,


encountered, the control goes out of it gets the control to the next iteration of the
the loop. loop.
A break causes the innermost A continue inside a loop nested causes the
enclosing loop to be skipped. next loop iteration.

exit() function: exit() is a standard library function present in the header


file stdlib.h. So the required header for the exit function is: #include
<stdlib.h>. When exit() is encountered it terminate the execution of the
program itself.
#include<stdio.h>
#include <stdlib.h>
main()
{
o/p
int i;
for(i=1;i<=5;i++)
{
if(i==3)
exit ();
printf(“%d\n”,i);
}
printf("KARNATAKA \n");
}

goto statement

The goto statement is known as jump statement in C. As the name


suggests, goto is used to transfer the program control to a predefined label.
The goto statment can be used to repeat some part of the code for a
particular condition.
#include <stdio.h>
int main()
{
int sum=0;
for(int i = 0; i<=10; i++)
{
sum = sum+i;
if(i==5)
In this program the sum is displaying
{
the sum of numbers till 5 even
goto addition; though the loop runs from 0 to 10.
} Hence the output of this program is
} 15.
addition:
printf("%d", sum);
}

You might also like