Sei sulla pagina 1di 29

UNIT-II Input and Output Operators

C Programming language provides many built-in function to read given input and
write data on screen, printer or in any file.

An input/output function can be accessed from anywhere within a program simply


by writing the function name, followed by a list of arguments enclosed in
parentheses. The arguments represent data items that are sent to the function.
Some input/output function does not require arguments, though the empty
parentheses must still appear.

The header file required by the standard input/output functions is called stdio.h

The input/output function can be divided in to formatted input/output function


and unformatted input/output function.

Unformatted input/output statement

a) Single Character Input –The getchar() function

Single charactercan be entered into the computer using the C library function
getchar().

The getchar() function is a part of the standard C I/O library. It returns a single
character from a standard input device( typically a keyboard). The function does not
require any arguments, though a pair of empty parentheses must follow the word
getchar().

Syntax

variable =getchar();

where variable refers to character variable declared.


Example

char ch;

ch=getchar();

The first statement declares that ch is a character type variable. The second
statement causes a single character to be entered from the standard input device
and then assigned to ch.

b) Single Character Output –The putchar() function

Single character can be displayed using the C library function putchar().

The putchar() function, transmits a single character to a standard a standard


output device(typically monitor).

Syntax

putchar(variable)

where variable refers to character variable declared

Example

char ch;

putchar(ch);

The first statement declares that ch is a character type variable. The second
statement causes the current value of ch to be transmitted to the standard output
device where it will be displayed.

c) Reading a String –The gets() function

gets() receives the string from the standard input device.

d) Printing a String –The puts() function

puts() outputs the string to the standard output device.

Program for demonstration of gets() and puts()


void main()
{
char str[50]; clrscr();

printf("Enter a string \n"); gets(str);


printf("The string typed is : "); puts(str);
getch();
}
Output
Enter a String
Varsha G Kalyan
The String typed is: Varsha G Kalyan

Formatted input/output statement

a) The scanf() function

Input data can be entered into the computer from a standard input device by
means of the C library function scanf(). This function can be used to enter any
combination of numerical values, single characters and strings. The function
returns the number of data items that have been entered successfully.

Syntax

scanf(control string, arg1,agr2,……………agrn);

Where control string refers to a string containing certain formatting information,


and arg1,agr2,.argn are arguments that represent the individual input data items.
The arguments represent pointers that indicate the address of the data items
within the computer‟s memory.

The control string consists of individual groups of characters, with one character
group for each input data item. Each character group must begin with a percent
sign (%) followed by a conversion character which indicate the type of the
corresponding data item.

Example-1:

int x;

x is an integer data type variable.

scanf(“%d”, &x);

Example-2:

int x,y;

x and y are integer data type variable.

scanf(“%d%d”, &x,&y);
Example-3:

int x,y;

float price;

x, y are integer data type variable, price is float data type variable.

scanf(“%d%d%f”, &x,&y,&price);

b) The printf() function

Output data can be written from the computer onto a standard output device
using the library function printf(). This function can be used to output any
combination of numerical values, single characters and strings.

Syntax

printf(control string, arg1,agr2,………..agrn)

where control string refers to a string that contains formatting information, and
arg1,agr2,.agrn are arguments that represent the individual output data items.

Example-1:

printf(“Enter the value of x”);

it display Enter the value of X

Example-2:

int x=10;

printf(“%d”, x);

it display 10

Example-3:

int x=10;

printf(“The value of x=%d”, x);

it display The value of x=10

Example-4:

float S=123.456;

printf(“%f %.3f %.2f”, S,S,S);

it display 123.456000 123.456 123.45


Decision making, Branching and Looping
Decision Making Statements / Conditional Statements:

C provides various key condition statements to check condition and execute


statements according conditional criteria.

These statements are called as 'Decision Making Statements' or 'Conditional


Statements.'

Followings are the different conditional statements used in C.

a) if Statement
b) if-else Statement
c) Nested if-else Statement
d) if-elseif ladder
e) switch case

a) if Statement
If statement is a conditional branching statement. In conditional branching
statement a condition is evaluated, if it is evaluate true a group of statement is
executed. The simple format of an if statement is as follows:

Syntax:

if(condition)
{
statements;
}

In above syntax, the condition is checked first. If it is true, then the program
control flow goes inside the braces and executes the block of statements
associated with it. If it returns false, then program skips the braces.
If there are more than one statements in if statement then use { } braces else it
is not necessary to use.
Example:

if (number>0)

printf(“Given number is Positive”);

If the value of the number is greater than 0, then the condition is true, it displays
the message Given number is Positive on the screen; otherwise the statement
is skipped.

b) if-else Statement

The if-else statement permits the programmer to write a single comparison, and
then execute one of the two statements depending upon whether the condition is
true or false.

If the condition is true, statement1 is executed otherwise statement2 will be


executed.

Syntax:

if(condition)
{
Statements1;
}
else
{
Statements2;
}

Example:

if (number==0)

printf(“Given number is Zero”);

else

printf(“Given number is not Zero”);

If the value of the number is 0(zero), then statement1 “Given number is Zero”
is displayed on the screen; otherwise the statement2”Given number is not
Zero” is displayed on the screen.
c) Nested if Statement
An if statement containing one more if statement either in true part or in else
part is called nested if statement.

Syntax:

if(condition1)
{
if(condition2)
{
Statement1;
}
else
{
Statement2;
}

}
else
{
Statement3;
}

If condition1 is true, then condition 2 is checked and statement1 is executed if it is true,


otherwise statement2 is executed.
If condition1 is false, then statement3 is executed.

Example:

if (number==0)

printf(“Given number is Zero”);

else

if (number>0)

printf(“Given number is Positive Number”);

else

printf(“Given number is Negative Number”);

}
d) If-Else-If Ladder Statement

Consider the example, to display the student‟s grade based on the following
table:

e) switch Statement

Switch statement accepts single input from the user and based on that input
executes a particular block of statements.

 You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.

 The switch expression requires only one argument of int or char data type,
which is checked with number of case options.

 when the variable being switched on is equal to a case, the statements


following that case will execute until a break statement is reached.

 when a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.

 Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.

 A switch statement can have an optional default case, which must appear at
the end of the switch. The default case can be used for performing a task when
none of the cases is true. No break is needed in the default case.

Here switch, case, break and default are reserved words or keywords.
Syntax
switch (expression)
{
case constant1:
statement-1;
break;
case constant2:
statement-2;
break;
..........
default:
statement-n;
}

Example 1:
switch(dayno)
{
case 1: printf(“Sunday”);
break;
case 2: printf(“Monday”);
break;
case 3: printf(“Tuesday”);
break;
case 4: printf(“Wednesday”);
break;
case 5: printf(“Thursday”);
break;
case 6: printf(“Friday”);
break;
case 7: printf(“Saturday”);
break;
default: printf(“Invalid day number””);
}
Example 2:
switch(Light)
{
case „R‟: printf(“RED Light Please STOP”);
break;
case „Y‟: printf(“YELLOW Light Please Check and Go”);
break;
case „G‟: printf(“GREEN Light Please GO”);
break;
default: printf(“THERE IS NO SIGNAL POINT ”);
}

Program to check whether the entered character is vowel or Consonant

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char ch;
clrscr();
printf("enter a character\n");
ch=getchar();
switch(toupper(ch))
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':printf("vowel");
break;
default:printf("consonant");
}
getch();
}
Program to find the roots of the given quadratic equation using switch case.

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,disc,x1,x2,xi,xr,x; int choice=1;
clrscr();
printf("input co-efficient\n");
scanf("%f%f%f",&a,&b,&c);
disc=b*b-4*a*c;
if(disc>0) choice=1;
else if(disc<0)choice=2;
else if(disc==0)choice=3;
switch(choice)
{
case 1:printf("real and distinct roots\n");
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
printf("x1=%.2f\n",x1);
printf("x2=%.2f\n",x2);
break;
case 2:printf("complex roots\n");
xr=-b/(2*a);
xi=sqrt(abs(disc))/(2*a);
printf("real part=%.2f\n",xr);
printf("imaginary part=%.2f\n",xi);
break;
case 3:printf("repeated roots\n");
x=-b/(2*a);
printf("x=%.2f\n",x);
}
getch();
}
Loops Statements
A loop statement allows us to execute a statement or group of statements
multiple times

A Program is usually not limited to a linear sequence of instructions or conditional


structures and it is sometimes required to execute a statement or a block of
statements repeatedly. These repetitive constructs are called loops or control
structures.

The C language supports three constructs; namely


a) while loop
b) do-while loop
c) for loop

a) while Loop
A while loop statement in C programming language repeatedly executes
the statement as long as a given condition is true. Here, statement(s)
may be a single statement or a block of statements.
The while loop checks whether the condition is true or not. If it is true,
code/s inside the body of while loop is executed, that is, code/s inside the
braces { } are executed. Then again the condition is checked whether
condition is true or not. This process continues until the condition becomes
false.
while loop is called as top tested loop, because the condition is tested at the
top (ie prior to entering into the loop).

Syntax:

while(condition)
{
statements;
}
Example:
x=1;
while(x<5)
{
printf(“Hello”);
x=x+1
}
The above code displays the output as
Hello
Hello
Hello
Hello

Program to display the number upto N terms using while loop


void main()
{
int x,n; clrscr();
printf("Enter the value for n\n"); scanf("%d",&n);
x=1;
while(x<=n)
{
printf("%d\t",x);
x++;
}
getch();
}
Write a C Program that reverse a given integer number and check whether the number
is palindrome or not.

#include<stdio.h>
#include<conio.h>
void main()
{
int n,t,r,rev=0;
clrscr();
printf("enter the number\n");
scanf("%d",&n);
t=n;
while(n>0)
{
r=n%10;
n=n/10;
rev=rev*10+r;
}
printf("the reverse of a number is %d\n",rev);
if (t==rev)
printf("The number is palindrome");
else
printf("The number is not a palindrome");
getch();
}
b) do…while Loop
In do...while loop, the body of loop is executed at first then the condition is
checked, So the statements are executed at least once in do...while loop.

At first statements inside body of do is executed. Then, the condition is checked.


If it is true, statements inside body of do are executed again and the process
continues until condition becomes false(zero). in do...while loop there is
semicolon in the end of while ();

do…while loop is called bottom tested loop, since the condition is checked at
bottom.

Syntax:

do
{
statements;
}
while(condition);

Example:
x=1;
do
{
printf(“Hello”);
x=x+1
}
while(x<5);
The above code displays the output as
Hello
Hello
Hello
Hello
c) for Loop
A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number of times.
The init(initialization) expression is executed only once at the beginning of the for
loop. Then the condition is checked. If the condition is false, for loop is
terminated. But if condition is true then the statements inside body of for loop is
executed and then increment expression executed. This process repeats until
condition is false.

Syntax
for (init; condition; increment)
{
statements;
}

Example:

for(x=1; x<5; x++)


{
printf(“Hello”);
}

The above code displays the output as


Hello
Hello
Hello
Hello
Difference between while loop and do-while loop

While Loop Do...While Loop

Entry-Controlled Loop Exit-Controlled Loop

Loop body will execute if condition Loop body will be executed at-least once
is true only. even thou the condition is failed

Top Tested Loop Bottom Tested Loop

Syntax for while: Syntax for do…while:


while(condition) do
{ {
statement... statement...
statement... statement...
} } while(condition);

Semicolon is not used after while Semicolon is used after while condition
condition

Loop Type Description

Repeats a statement or group of statements while a given condition


while loop
is true. It tests the condition before executing the loop body.

Like a while statement, except that it tests the condition at the end
do...while loop
of the loop body

A for loop is a repetition control structure that allows you to


for loop efficiently write a loop that needs to execute a specific number of
times.

You can use one or more loop inside any another while, for or
nested loops
do..while loop.
Program to display the number upto N terms using for loop
void main()
{
int x,n;
clrscr();
printf("Enter the value for n\n");
scanf("%d",&n);
for(x=1; x<=n; x++)
{
printf("%d\t",x);
}
getch();
}
Program to display odd number upto N terms

void main()
{
int x,n;
clrscr();
printf(“Enter the value for n \n”); scanf(“%d”,&n);
printf(“\n The odd numbers are \n”);
for(x=1; x<=n; x=x+2)
{
printf("%d\t”,x)
}
getch();
}
Output:

Enter the value for n 10


The odd numbers are 1 3 5 7 9
Write a C Program to generate and print first N Fibonacci numbers.

#include<stdio.h>
#include<conio.h>
void main()
{
int i=3,f1=0,f2=1,f3,n;
clrscr();
printf("\nHow many terms:");
scanf("%d",&n);
printf("%d \t %d ",f1,f2);
for(i=3;i<=n;i++)
{
f3=f1+f2;
printf("%d ",f3);
f1=f2;
f2=f3;
}
getch();
}

Output

How many terms:8


0 1 1 2 3 5 8 13
Nested for Loops
The way if statements can be nested, similarly while and for can also be nested.
To understand how nested loops work, look at the program given below:

Program for the demonstration of nested loops


void main( )
{
int r, c;
clrscr();
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */
{
for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */
{
printf ( "r = %d c = %d \n", r, c) ;
}
}
getch()
}

When you run this program you will get the following output:
r=1c=1
r=1c=2
r=2c=1
r=2c=2
r=3c=1
r=3c=2

Here, for each value of r the inner loop is cycled through twice, with the variable c
taking values from 1 to 2. The inner loop terminates when the value of c exceeds
2, and the outer loop terminates when the value of r exceeds 3.
As you can see, the body of the outer for loop is indented, and the body of the
inner for loop is further indented. These multiple indentations make the program
easier to understand.
The way for loops have been nested here, similarly, two while loops can also be
nested. Not only this, a for loop can occur within a while loop, or a while within a
for.
Unconditional jump Statements (break, continue, exit())

break Statement

In C programming, break is used in terminating the loop immediately


after it is encountered. The break statement is used with conditional if
statement. break statements are also used in switch...case statement.

Program for demonstration for break statement


void main()
{
int x;
clrscr();
for(x=1; x<=10; x++)
{
If (x==6)
break;
else
printf("x=%d\n",x);
}
getch();
}
Output
x=1
x=2
x=3
x=4
x=5
In the above program, the for loop runs till x<=10, since in the body of
for loop we have written break statement, when the value of x=6.
Because of that loop is terminated.
continue Statement
The continue statement, continue forces the next iteration of the loop
to take place, skipping any code in between.

continue statement is a jump statement. The continue statement can


be used only inside for loop, while loop and do-while loop. Execution
of these statement does not cause an exit from the loop but it suspend
the execution of the loop for that iteration and transfer control back to
the loop for the next iteration.

Program for the demonstration of continue statement


void main()
{
int x;
clrscr();
for(x=1; x<=5; x++)
{
if (x==3)
{
continue;
}
printf("x=%d\n",x);
}
getch();
}
Output
x=1
x=2
x=4
x=5

In the above program make use of continue statement, which


displays the number from 1 to 5 except the number 3.
exit function
exit( ) is not a program control statement, its help us to terminate
the program immediately.

Program to find the factorial of a number


void main()
{
long fact;
int n,x;
clrscr();

printf("Enter the number\n");


scanf("%d",&n);
fact=1;
for(x=1; x<=n; x++)
{
fact=fact*x;
}
printf("Factorial of %d is %ld", n, fact);
getch();
}
BCA105T- Programming Concepts using C Page 1 of 29

Program to display the following pattern.


1
12
123
1234
12345

void main()
{
int i,j;
clrscr();
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
{
printf("%d ",j);
}
printf("\n");
}
getch();
}

www.gkmvkalyan.blogspot.in
BCA105T- Programming Concepts using C Page 2 of 29

Program to display the following pattern.

*
* *
* * *
* * * *
* * * * *
void main()
{
int i,j;
for(i=1; i<=5; ++i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
getch();
}

www.gkmvkalyan.blogspot.in
BCA105T- Programming Concepts using C Page 3 of 29

Program to display the following pattern.

1
23
456
7 8 9 10

void main()
{
int rows,i,j,k=0;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; i++)
{
for(j=1; j<=i; ++j)
printf("%d ",k+j);
++k;
printf("\n");
}
getch();
}

www.gkmvkalyan.blogspot.in
BCA105T- Programming Concepts using C Page 4 of 29

goto Keyword

Avoid goto keyword! It shows you are not a good programmer. Because of
the reasons that programs become unreliable, unreadable, and hard to
debug.

The big problem with goto is that when we use them we can never be sure how
we got to a certain point in our code. They obscure the flow of control. So as far
as possible skip them.

The following program shows how to use goto.

main( )
{
int s ;
printf ( "Enter the number” ) ;
scanf ( "%d", &goals ) ;
if ( s < 5 )
goto sos ;
else
{
printf ( "you have entered the value more than 5" ) ;
exit( ) ;
}
sos :
printf ( "you have entered the values less than 5!" ) ;
}

www.gkmvkalyan.blogspot.in
BCA105T- Programming Concepts using C Page 5 of 29

2) Write a C Program to generate and print first N Fibonacci numbers.

#include<stdio.h>
#include<conio.h>
void main()
{
int i=3,f1=0,f2=1,f3,n;
clrscr();
printf("\nHow many terms:");
scanf("%d",&n);
printf("%d \t %d",f1,f2);
for(i=3;i<=n;i++)
{
f3=f1+f2;
printf("\t %d",f3);
f1=f2;
f2=f3;
}
getch();
}

Output
How many terms:8
0 1 1 2 3 5 8 13

www.gkmvkalyan.blogspot.in
BCA105T- Programming Concepts using C Page 6 of 29

Write a C Program to find the GCD and LCM of two integer numbers.

#include<stdio.h>
#include<conio.h>
void main()
{
int m,n,temp,lcm,gcd;
clrscr();
printf("Enter the two numbers\n");
scanf("%d%d",&m,&n);
temp=m*n;
while(m!=n)
{
if(m>n)
m=m-n;
else
n=n-m;
}
gcd=n;
lcm=temp/gcd;
printf("LCM =%d\t GCD =%d",lcm,gcd);
getch();
}
Output

Enter the two numbers


4 6
LCM =12 GCD =2

www.gkmvkalyan.blogspot.in