Professional Documents
Culture Documents
Bca C Language 2&3
Bca C Language 2&3
UNIT 2
. INPUT AND OUTPUT STATEMENTS
2.1.1. Introduction
C provides several functions that give different levels of input and output capability.
These functions are, in most cases, implemented as routines that call lower-level
input/output functions. The input and output functions in C are built around the concept
of a set of standard data streams being connected from each executing program to the
basic input/output devices.
These standard data streams or files are opened by the operating system and are
available to every C and assembler program to use without having to open or close the
files. These standard files or streams are called:
stdin Connected to the keyboard
stdout Connected to the screen
stderr Connected to the screen
A number of functions and macros exist to provide support for streams of various
kinds. The <stdio.h> header file contains the various declarations necessary for the
functions, together with the macros and type declarations needed for the input and
output functions.
The formatted functions return the values after execution. The return value is equal to
the number of variables successfully read/written. Using this value the user can find
out the errors occurring during reading or writing the data.
Where,
Control string determines how values are read into the variables pointed
to in the argument list.
Inputting an Address
To input a memory address, use the %p format specifier. This specifier causes
scanf() to read an address in the format defined by the architecture of the CPU.
All the variables used to receive values through scanf() must be passed by their
addresses. All argument, i.e., must be pointers, which allows a function to alter the
contents of an argument. For example, to read an integer into the - variable count, the
following scanf() call is used:
scanf("%d", &count);
Syntax
printf(control string, argl, arg2, ............ arg n)
Where control string refers to a string that contains formatting information, and argl,
arg2... arg n are arguments that represent the indivf&aal output data items. The
arguments can be written as constants, single variables or array names, or more
complex expressions. Function references may also be included.
The unformatted input/output functions only work with the character data type. They
do not require conversion symbol for identification of data types because they work
only with character data type. There is no need to convert the data. In case, values of
other data types are passed to these functions, they are treated as the character data.
The unformatted functions also return values, but the return value of unformatted
function is always the same.
Syntax
variable_name = getche();
4) getch() Function: This function returns a character that has been recently typed.
But, neither the user is required to press Enter key after entering the character nor
the typed character is echoed to the computer screen. This function has advantages
over the other functions in the applications where the user wants to hide the input.
This input is usually the password used for system security.
Syntax
variable_name = getch();
5) putch() Function: They print a character on the screen. This helps the compiler in
single character output.
Syntax
putch(variable_name);
6) putchar() Function: This function outputs a character constant or a character
variable to the standard output device.
Syntax
putchar(variable_name);
7) puts()-Function: This function outputs a string constant or a string variable to the
standard output device.
Syntax
puts(variable_name);
Program 2: To illustrate the unformatted functions.
#include<stdio.h>
#include<conio.h>
void main()
{
char a[30];
gets(a);
puts(a);
getch();
}
Output
$ C:\Users\pravesh\Desktop\To\VIU.exe ^ ® ................................................... .... -
■
this is Thakur Publishers.
[his is Thakur Publishers. I
4 m : > 1
Explanation
1) #include<stdio.h> This header file is included because, the C in-built statements
gets and puts used in the program comes under stdio.h.
2) #include<conio.h> This header file is used because the C in-built function
getch() comes under conio.h header files.
3) mainO function is the place where C program execution begins.
4) Array a[] of type char size 30 is declared.
5) gets is used to receive the user input to the array, gets stops receiving user input
only when the Newline character (Enter Key) is interrupted.
6) puts is used to display them back in the console (monitor).
2.2. EXERCISE
Write a short note on Built-in Operators and’Functions.
2) Write the function for file handling^
3) Write the basic steps to processing a file.
4) Explain the formatted I/O.
5) What are unformatted functions?
1) Explain the following functions with a suitable example.
i) gets()
ii) puts()
iii) getch()
Selection/Branching Iteration/Looping
I , . !
3.2.1. Introduction
C has various kinds of statements that permit the execution of a single statement, or
a block of statements, based on the evaluation of a test expression or permit the
selection of the statement to be executed among several statements based on the
value of an expression or a control variable.
Conditional branching and selection statements include constructs like:
1) if «.
2) if-else
3) if-else-if
4) switch
C supports two selection statements: if and switch. In addition, the “?” operator is an
alternative to if in certain circumstances.
3.2.2. if Statement
The general syntax and flowchart of the if statement is given below.
Syntax
if (expression)
{
statement;
}
Syntax
if (expression)
{
statement;
}
else
{
statement;
}
<—
Flowchart
Program 1: /*To check the number as even or odd using if-else statement*/
#include<stdio.h>
#include<conio.h> •
void main()
{
int n; clrscr();
printf("Enter any number (which is to be checked as even or odd): );
scanf("%d", &n);
if (n%2==0) /* test for even*/
printf("%d number is even number",n);
else
printf("%d is an odd number" ,n);
getchQ;
°utPut — ufKMd
Flowchart
Program 2: /*To demonstrate nested else-if*/
#include<stdio.h>
#include<conio.h>
void main()
{
int units, custnum;
float charges;
clrscr();
printf("Enter customer number and units consumed\n");
scanf("%d %d", &custnum, &units);
if(units<=200)
charges=0.5*units;
else if(units<=400)
charges=100+.65* (units-200);
else if(units<=600)
charges=230+0.8*(units-400);
else
charges=390+(units-600);
printf( \n\n Customer No. %d: Charges=%.2f\n", custnum, charges)-
getch(); ’
}
Output
, . ^ gx
nter customer number and units consumed 671
The default statement is executed if no matches are found. The default is optional, and
if it is not present, no action takes place if all matches fail.
Syntax
switch (expression)
{
case constant l:
statement sequence
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
default
statement sequence
}
Output
■ C:\Users\pravesh\Desktop\t\bftwi.,, ^ ®
The first two are pre-test loops and do-while is a post-test loop. In the post-test loop,
the code is always executed once.
Syntax:
for (initialization; condition; increment) statement;
Where,
1) Initialization: The first is a run before the loop is entered. This is usually the
initialization of the loop variable.
2) Condition: The second is a test, the loop is exited when this returns false.
3) Increment: The third is a statement to be run every time the loop body is
completed. This is usually an increment of the loop
The initialization is an assignment statement that is used to set the loop control
variable. The condition is a relational expression that determines when the loop
exits.
The ‘for’ loop continues to execute as long as the condition is true. Once the
condition becomes false, program execution resumes on the statement following the
for.
For example, consider the following loop that prints the numbers less than 3.
Expression 2(test expression)
Expression 1 (initialization) A
Expression 3(increment/update)
int 1; for(i=0;
i<3fi++)
printf(“%d”, i);
for keyword
Compound
statement
for( i = 0; i <= j; i ++ )
{
printf("Hello %d\n", i);
}
getch();
}
Output
C:\UserAprevesh\Desktop\t\bitv vise.exe
Lout; r * I imit
Enter
5 Upper li mit
tnt e r
510 10 15 20 25 30 35 43 45 50
6 12 18 24 30 3& 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 2V 36. 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Output _____________________
Syntax:
while(condition)
{
statements;
}
Output _______________
m C:\Users\pravesh\De5 =. m ss
Unlike for and while loops, which test the loop condition at the top of the loop, the
do-while loop checks its condition at the bottom of the loop. This means that a do-
while loop always executes atleast once. The general form of the do-while loop is
given below:
Syntax:
do
{
statement;
} while(condition);
Although the curly braces are not necessary when only one statement is present, they
are usually used to avoid confusion with the while. The do-while loop iterates until
condition becomes false.
For example, consider the following loop that prints Heel three times.
do keyword
Compoun
d
statement
while
keyword
Program 7: /*Illustrating do-while statement*/
#include <stdio.h>
#include <conio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
printf("value of a: %d\n", a);
a= a + 1;
}while( a < 20 );
getch();
}
Output
] CAUsers\pravssh\De: \ * ‘
exit(int status);
After exit() all memory and temporary storage areas are all flushed-out and control goes
out of program. In contrast, the return() statement is used to return from a function and
return control to the calling function.
Also in a program there can be only one exit() statement but a function can have
number of return statements. In other words, there is no restriction on the number of
return statements that can be present in a function.
exit() statement is placed as the last statement in a program since after this program is
totally exited. In contrast return statement can take its presence anywhere in the
function. It need not be presented as the last statement of the function.
It is important to note that whenever a control is passed to a function and returns back,
some value gets returned. Only if one uses a return statement the correct value would
get returned from the called function to the calling function.
The difference between break and exit() is that the former terminates the execution of a
loop in which it is written, while exit() terminates the execution of the program itself.
Its use is widespread in switch statements, where it is more or less essential to get the
control that most people want.
The use of the break within loops is of dubious legitimacy. It has its moments, but is
really only justifiable when exceptional circumstances have happened and the loop has
to be abandoned. It would be nice if more than one loop could be abandoned with a
single break but that is not how it works.
If the body of the for loop is large then the continue statement is used to induce an
extra level of indentation and enhance readability. Program below illustrate the
concept of continue statement.
int main ()
{.
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
getch();
}
Output
goto LI;
/* whatever you like here */
LI: /* anything else */
A label is an identifier followed by a colon. Labels have their own ‘name space’ so
they cannot clash with the names of variables or functions. The name space only
exists for the function containing the label, so label names can be re-used in different
functions. The label can be used before it is declared, too, simply by mentioning it in
a goto statement.
Labels must be part of a full statement, even if it is an empty one. These usually ,
only matters when you are trying to put a label at the end of a compound statement.
For example, consider the following statement:
int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20);
getch();
}
Output ____________
* C^Userc\pravesh\Deslctop\t\bitwise.exe ’_«=>. ED S3
alue of a: 10 ................................
alue of a: 11
alue of a: 12
alue of a: 13
alue of a: 14
alue of a: 16
alue of a: 17
alue of a: 18
alue of a: 19
|* rrr . . ►;
-V - -------------------------------------------------------------- -- ------
-------------------------------------------------------------------- ■
3.4.6. Difference between Break and Continue Statement
Table: Break Statement versus Continue Statement
Break Statement Continue Statement
1) Can be used in switch statement. 1) Cannot be used in switch statement.
2) Causes premature exit of the loop enclosing it. 2) Causes skipping of the statements following it in
the body of the loop.
3) The control is transferred to the statement 3) Control is transferred back to the loop.
following the loop.
4) The loop may not complete the intended 4) The loop completes the intended number of
number of iterations. iterations.
3.5. PROGRAMS
Program 11: /*To convert upper case to lower case or lower case to upper case
depending on the name it is invoked with as found in argument.*/
#include<stdio.h>
#include<conio.h>
void lower_to_upper();
void upper_to_lower();
void main()
{
int n;
clrscr();
printf("Please enter your choice.\n");
printf("\n");
printf("(l) for upper to lower conversion.\n");
printf("\n(2) for lower to upper conversion.\n");
printf("\nCHOICE:- \n");
scanf("%d", &n);
switch(n)
{
case 1:
{
printf("Please enter a string in upper caseAn");
{
printf("String will be terminated if you press Ctrl + ZAn");
printf("\n");
printf("\nSTRING:- \n");
upper_to_lower ();
break;
}
case 2:
{
printf("Please enter a string in lower case.");
printfO'String will be terminated if you press Ctrl-Z.");
printf(“STRING:- ");
lower_to_upper();
break;
}
default:
printf("ERROR");
}
printf("HAVE A NICE DAY!BYE.");
getch();
}
void upper_to_lower()
{
inti, j;
char c4[80], c3;
for(i=0; (c3=getchar())!=EOF; i++)
c4[i]=(c3>='A' && c3<='Z')?('a' + c3 -'A'):c3;
printf("The lower case equivalent is ");
for(j=0; j<i; j++)
putchar(c4[j]);
return;
}
void lower_to_upper()
{
inti, j;
char c2[80], cl;
for (i=0;(cl=getchar())!=EOF;i++)
c2[i]=(cl>=’a' && cl<='z')?('A' + cl -'a'):cl;
printf("The upper case equivalent is ");
for(j=0; j<i; j++)
putchar(c2[j]);
getch();
}
Output
J3 _ " ____ •{, "
ple^te enter, ^ojul^ \
|<1 ^Toi iQpper to 'JuiV ■ "Cjnuei*:, ICH.
i ^ .%*s.
(?) louer to u#^ier conuers.. jn.
Explanation: The code describes the switch case usage wounded with ‘for’ loop for
function calling of upper_to_lower and lower_to_upper.
scanf(" %d",&num);
while(icnum){
if(num%i==0)
sum=sum+i;
i++;
}
if(sum==num)
printf("%d is a perfect number",i);
else
printf("%d is not a perfect number",i);
getch();
return 0;
}
Output __________
«? C:\Dev-Cpp\Exair;
Enter a number: 6
6 is a perfect number
Program 13: /*Program for Prime Number Generation*/
J#inciude<stdio.h>
#include<conio .h> main()
{
int n, i=l, j,c;
clrscr();
printf("\nEnter Number Of Terms\n");
printf("NnPrime Numbers Are Following/n”);
scanf("%d", &n);
while(i<=n)
{
c=0;
for(j=l; j<=i; j++)
{
if(i%j==0)
C++;
}
if(c==2)
printf("%d ", i);
i++;
}
getch();
Output
Turbo f. - ID
Output
Explanation: Here the division method is used for the calculation of square root
function. Here the text is colored by using the inbuilt library function textcolour. The
nested if-else and do-while loops are used for the program control flow.
Program 15: Generate Armstrong number upto n.
#include<stdio.h>
#include<conio ,h>
int main()
{
int r;
long number = 0, c, sum = 0, temp;
printf("Enter the maximum range upto which you want to find armstrong
numbers ");
scanf(" %ld" ,&number);
getch();
return 0;
}
1i
int main()
{
int m,n,c;
up:
printf("\n Enter Lower Range: ");
scanf("%d", &n);
printf("\n Enter Higher Range: ");
scanf("%d", &m);
if(n>=m){
printf("\nImproper Input\n");
goto up;
}
\ printf("What do you want:\n");
printf("l. Sum of All NumbersAn");
printf("2. Sum of All Odd Numbers:\n");
printf("3. Sum of All Even Numbers:\n");
printf("4. Exit:\n");
scanf("%d", &c);
switch(c)
{
case 1: All_sum(n,m);
break;
case 2: Odd_sum(n,m);
break;
case 3 : Even_sum(n,m);
break;
case 4 : exit(O);
}.
getch();
return 0;
}
//Sum of All Numbers
ALLsum(n,m)
int i,sum = 0;
for(i = n;i <= m ; i++)
{:
sum = sum + i;
}.
}
//Sum of All Odd Numbers
Odd_sum(n,m)
{
int x3=n,x4=m,sum=0;
while(x3 <=×4){
if(x3 % 2 != 0)
sum = sum + x3;
x3++;
}
if(xl % 2 =* 0)
xl++;
int main()
{
int n,c;
printf("Enter the Number:\n");
scanf( %d", &n);
printf("What do you want:\n");
printf("l. Factorial:\n");
prin;f("2. Fibonacci Series:\n");
prifiti("3. Exit:\n");
scanf(,;%d", &c);
switch(c)
{
case 1: factorial(n);
break;
case 2: fibonacci(n);
break;
case 3 : exit(O);
}
getch();
return 0;
}
void factorial(int n) /*calculate the factorial */
{int x, count;
unsigned long long int factorial =1;
x=n;
if (x< 0)
printf("Error!!! Factorial of negative number doesn't exist.");
else {
for(count=l;count<=x;++count) /* for loop terminates if count>n */
{ factorial*=count; /* factorial=factorial*count */
}
printf("Factorial = %lu",factorial);
}
}
void fibonacci(int n) /*calculate the fibonacci series */
{
int count, x, tl=0, t2=l, display=0;
x=n;
printf("Fibonacci Series: %d+%d", tl, t2); /* Displaying first two terms */
count=2; /* count=2 because first two terms are already displayed. */
while (count<x)
{
display=tl+t2;
tl=t2;
t2=display;
++count;
printf("+");
printf("%d",display);
}}
1
Output
C:\Dev-Cpp\Examples\VTU CVF.J . .... '
tnte . 1. 1 Nui ibet ■7
Wl»-> ( yo m •./. t •
1 I '< * *.. « o l* i ., I - /’ I- j-,
*i>it
Program 18: Write a program to reverse a number and check whether it is
palindrome or not.
#include <stdio.h>
main()
{
int n,temp,rem,reverse=0;
printf("Enter the value of n\n");
scanf("%d",&n);
temp=n;
while(n>0)
{
rem=n%10;
reverse=reverse* 10+rem;
n=n/10;
}
if(temp==reverse)
printf("%d is Palindrome\n",temp);
else
printf("%d is not a Plaindrome\n",temp);
getch();
Output
■ C:\Users\pravesh\Desktop\ToWHJ..., 1=3 ®
j E n t e i * t h e v a l u e of n
1441
1441 is Palindrone ■I
* . rrr : *1
3.6. EXERCISE
1) Explain the statement and compound statement.
2) Write a note on labeled and null statement.
3) What is decision making structure?
4) What is Loop control structure?
5) Explain if statement with a suitable program.
6) Explain the switch statement with a suitable program.
7) Write the difference between while and do-while loop with a suitable example.
8) Explain the jump statement.
9) Write the difference between break and continue.