0% found this document useful (0 votes)
27 views24 pages

C Mod 3

This document discusses input and output functions in C language. It covers: 1. C includes functions to transfer information between the computer and standard input/output devices. The most common I/O functions are getchar, putchar, scanf, printf, gets and puts. 2. I/O functions are divided into formatted (scanf, printf) and unformatted (getchar, putchar) types. Formatted functions use format specifiers while unformatted do not. 3. Common single character I/O functions are getchar for input and putchar for output. Strings can be read and written using gets/puts or scanf/printf.

Uploaded by

arafaiic2022
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)
27 views24 pages

C Mod 3

This document discusses input and output functions in C language. It covers: 1. C includes functions to transfer information between the computer and standard input/output devices. The most common I/O functions are getchar, putchar, scanf, printf, gets and puts. 2. I/O functions are divided into formatted (scanf, printf) and unformatted (getchar, putchar) types. Formatted functions use format specifiers while unformatted do not. 3. Common single character I/O functions are getchar for input and putchar for output. Strings can be read and written using gets/puts or scanf/printf.

Uploaded by

arafaiic2022
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/ 24

Methodology of Programming & C BCA/BSc CS

Language
MODULE 3

INPUT AND OUTPUT FUNCTIONS


C language includes a number of input/output functions. These functions permit the transfer
of information between the computer and the standard input/output devices. An input/output
function can be accessed from anywhere within a program by simply 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 functions do not require arguments, though the
parentheses must still appear.
Most versions of C include a collection of header files that provide necessary information in
support of the various library functions. These files are entered into the program via a #include
statement at the beginning of the program. The header file required by the standard input/output
library functions is called stdio.h.
The six input/output functions are
 getchar
 getch()
 putchar
 scanf
 printf
 gets
 puts
Input output built-in functions in C falls into two categories, namely,
 Formatted input output (I/O) functions and
 Unformatted input output (I/O) functions.
printf() and scanf() are examples for formatted input and output functions and getch(),getchar(),
gets(), puts(), putchar() etc. are examples of unformatted input output functions.
Unformatted functions
SINGLE CHARACTER INPUT---THE getchar FUNCTION
Single characters can be entered into the computer using the C library function getchar. It
returns a single character from a standard input device (typically a keyboard). The function does
not require any arguments.
The getchar takes the following form:
Character_variable = getchar ( );
where character variable refers to some previously declared character variable.

1 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
Example:
char c;

c = getchar ( );
The first statement declares that c is a character-type variable. The second statement causes
a single character to be entered from the standard input device and then assigned to c.
Note: The getchar function can also be used to read multi character strings, by reading one
character at a time within a loop.
getch():-
The getch() in C is a non-standard function used to receive a character as input from the
user. It is defined in the header file conio.h. The character entered by the user is not visible on the
output screen but is stored in the assigned variable. We can also explain the getch() as a function
call that pauses the execution of the program until the user enters a character from the keyboard.

SINGLE CHARACTER OUTPUT---THE putchar FUNCTION

Single characters can be displayed using the C library function putchar. The putchar
function transmits a character to a standard output device. The character being transmitted will
normally be represented as a character-type variable. It must be expressed as an argument to the
function, enclosed in parentheses, following the word putchar.
The putchar takes the following form:
putchar ( character_variable ) ;
Where the character variable refers to some previously declared character variable.
Example:
char c;

putchar (c ) ;
The first statement declares that c is a character-type variable. The second statement causes
the current value of c to be transmitted to the standard output device where it will be displayed.
Note: The putchar function can be used with loops to output a string.
THE gets AND puts FUNCTIONS
The gets and puts functions facilitates the transfer of strings between the computer and the
standard input/output devices. Each of these functions accepts a single argument. The argument
must be a string, (e.g., a character array). The string may include whitespace characters.

2 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
In the case of gets, the string will be entered from the keyboard, and will terminate with a
newline character (i.e., the string will end when the user presses the enter key). The gets and puts
functions offer simple alternatives to the use of scanf and printf for reading and displaying strings.
Example
main()
{
char a[40];
gets(a); /* reads a line of text into the computer */
puts(a); /* writes the text back out in its original form
*/
}
Formatted Functions
ENTERING INPUT DATA --- THE scanf FUNCTION
In C programming language, scanf() function is used to read character, string, numeric data
from keyboard
The general form of scanf is:
scanf (“control string”, arg 1,arg 2,……, arg n ) ;
The control string specifies the field format in which the data is to be entered and the arguments
arg 1, arg 2, ….. ,arg n specify the address of locations where the data is stored. Control string and
arguments are separated by commas. Control string (also known as format string) contains field
specifications, which direct the interpretation of input data. It may include:
 Field (or format) specifications, consisting of the percentage sign %, a conversion
character (or type specifier), and an optional number, specifying the field width.
 Whitespace characters (Blanks, tabs, or newlines).

Example
main()
{
char a[20];
int b;
float c;
………
scanf (“ %s %d %f ”,a, &b, &c );
………….
}
Within the scanf function, the control string is “%s %d %f “. It contains three character groups.
3 Dept. of CS, IGCAS
Methodology of Programming & C BCA/BSc CS
Language
The first character group %s represents a string.
The second character group %d represents a decimal integer value.
The third character group %f represents a floating-point value.
Numerical variables b and c are preceded by ampersands within the scanf function.

WRITING OUTPUT DATA--- THE printf FUNCTION

In C programming language, printf() function is used to print the (“character, string, float,
integer, octal and hexadecimal values”) onto the output screen.
 We use printf() function with %d format specifier to display the value of an integer variable.
 Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for
double and %x for hexadecimal variable.
 To generate a newline,we use “\n” in C printf() statement.
The general form of printf is:
printf ( "control string”, arg 1, arg 2, …..,arg n) ;
Control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n,\t,\b.
The control string indicates how many arguments follow and what their types are. The
arguments arg1,arg2,….,argn are the variables whose values are formatted and printed according to
the specification of control string. The arguments should match in number, order and type with the
format specifications.
Some examples of formatted printf statements are:
printf(“Programming in C”);
printf(“ ”);
printf(“ \n ”);
printf(“ %d ”, x); printf(“a=
%f \n b= %f”,a,b);
printf(“sum= %d”, 1234);
printf(“\n \n”);

4 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
Commonly Used Conversion Characters For Data Input/output

Conversion character Meaning


c dataitem is a single character
d dataitem is a decimal integer
e dataitem is a floating-point value
f dataitem is a floating-point value
h dataitem is a short integer
i dataitem is a decimal, hexadecimal or octal integer
o dataitem is a octal integer
dataitem is a string followed by a whitespace character (the
s
null character \0 will automatically be added at the end)
u dataitem is an unsigned decimal integer
x dataitem is a hexadecimal integer

COMMONLY USED LIBRARY FUNCTIONS

5 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
DECISION MAKING AND BRANCHING
Decision making helps us to change the order of execution of the statements based on certain
conditions. Decision making capabilities are supported by following statements
 if statement
 Switch statement
 Conditional operator statement
 goto statement
These statements ‘control’ the flow of execution, so they are also known as control statements.

DECISION MAKING WITH IF STATEMENT


The if statement is a powerful decision making statement and is used to control the flow of
execution of statements. It is a two way decision statement and is used in conjunction with an
expression.
It takes the following form:
if (test expression)

Entry

test expression False


?

True

The if statement may be implemented in different forms depending on the complexity of


conditions to be tested. The different forms are:
 simple if statement
 if.....else statement
 Nested if…else statement
 Else if ladder
simple if statement
The general form of a simple if statement is
if ( expression
) statement;
or

6 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
if ( expression )
{
statement-block;
}
statement-x;

The ‘statement-block’ may be a single statement or a group of statements. If the expression is true,
the statement/statement-block will be executed; otherwise the statement/statement block will be
skipped and the execution will jump to the statement-x. When the condition is true both the
statement-block and the statement-x are executed in sequence.

The if.....else statement


The if…else statement is an extension of the simple if statement. The general form is:
if (expression )
{
Statement-block 1;
}
else
{
Statement-block 2;
}
Statement-x;

7 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
If the expression is true, then the statement-block 1 will be executed. Otherwise (the
expression is false), statement-block 2 will be executed. In either case, either statement-block 1 or
statement-block 2 will be executed, not both. In both cases, the control is transferred subsequently
to the statement-x.

P7. Write a program to fine the largest of two numbers


P8. Write a program to check whether the number is even or odd.
P9. Write a program to input a number and check whether which is divisible by 7.
Nested if…else statement
When a series of decisions are involved, we may have to use more than one if..else
statement in nested form. The general form is:

If ( expression 1)
{
If ( expression 2 )
{
statement-1 ;
}
else
{
statement-2;
}
}
else

8 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
{
statement-3 ;
}
Statement-x;
One complete if-else statement will be executed if expression-1 is true, and another complete
if-else statement will be executed if expression-1 is false.

P10. Write program to print the largest of three numbers.

void main()
{
int a,b,c;
printf(“Enter three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
printf(“The largest value is ”);
if(a>b)
{
if(a>c)

printf(“%d”,a);
else

printf(“%d”,c);
}

9 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
Els
e
{
if(b>c)
printf(“%d”,b);
else
printf(“%d”,c);

}
getch();
}

P11. Write a program to input two numbers and check whether the first number is divisible by the
second number.
P12. Write a program to input two numbers and check the sum is even or odd.
P13. Write program to print the largest of three numbers using logical AND.
#include <stdio.h>
void main()
{
int a, b, c;
printf("Enter three numbers: \n ");
scanf("%d%d%d",&a,&b,&c);
if (a > b && a > c)
printf("Biggest number is %d", a);
if (b > a && b > c)
printf("Biggest number is %d",
b); if (c > a && c > b)
printf("Biggest number is %d", c);
getch();
}
P14. Write a program to input two numbers and find the largest among them using conditional
operator.
P15. Write a program to find he roots of the quadratic equation of the form ax2+bx+c=0.
Roots= -
b+ b2-4ac
2a
#include <math.h>
#include <stdio.h>

10 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
void main()

11 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
{
float a, b, c, dis, root1, root2;
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f", &a, &b, &c);
dis= b * b - 4 * a * c;
if (dis > 0)
{
root1 = (-b + sqrt(dis)) / (2 * a);
root2 = (-b - sqrt(dis)) / (2 * a);
printf("root1 = %.2f and root2 = %.2f", root1, root2);
}
else if (dis == 0) {
{
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
els
e
printf(“The roots are imaginary”);
getch();
}
else if ladder
else if ladder can be used to choose an option from more than two alternatives. else if
ladder is multiple branch decision statement.
General form/Syntax

12 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
Working
1. The conditions are evaluated from the top to downwards, as soon as a true condition is
found, the statement associated with it is executed and the control is transferred to the
statement x skipping the rest of the ladder.
2. When all the n conditions become false then final else containing default statement will be
executed.

The switch Statement

Switch statement is multiple branch decision statement. The switch statement tests the
value of a given variable(expression) against a list of case values and when a match is found, a
block of statements associated with that case is executed.
General form/Syntax:
switch(expression)
{
case value-1:
block
1;
break;
case value-2:
block-
2;
break;
…………
………
13 Dept. of CS, IGCAS
Methodology of Programming & C BCA/BSc CS
Language
… default:

14 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
default-
block; break;
}
Statement-x;
Where expression can be an integer constant or characters. Value-1,value-2 are constants or
constant expressions and are known as case labels. switch statement is a multiple branch decision
statement.
Working:
1. Evaluates the expression.
2. The resulted integer value is compared with case constants.
3. If match is found, the statements associated with that particular case are executed.
4. If no match is found, statements under default are executed.
5. When break statement is encountered, the switch is
terminated. Note: Each case statement must have break
statement.

P16. Write a program to print name of day based on a given number (1-7) using switch statement.
#include <stdio.h>
void main()
{
int day;
printf("Enter Day Number\n");
scanf("%d", &day);

switch(day)
{
case 1 : printf("Monday\n");
break;
case 2 : printf("Tuesday\n");
break;
case 3 : printf("Wednesday\n");
break;
case 4 : printf("Thursday\n");
break;
case 5 : printf("Friday\n");
break;
15 Dept. of CS, IGCAS
Methodology of Programming & C BCA/BSc CS
Language
case 6 : printf("Saturday\n");
break;
case 7 : printf("Sunday\n");
break;
default: printf("Invalid Input !!!!\n");
}
getch();
}

Conditional operator statement


The conditional operator is a combination of ? and : ,and takes three operands.This operator
is popularly known as the conditional operator. The general form of conditional operator is:
Conditional expression? expression1: expression2;
The conditional expression is evaluated first. If the result is true, expression1 is evaluated
and is returned as the value of the conditional expression. Otherwise, expression2 is evaluated and
its value is returned.
Example:
a = (10>6) ? 10 : 6 ;
If (10>6) then return a=10 else return a= 6.
goto statement
C supports the goto statement to branch unconditionally from one point to another in the
program. The goto requires a label in order to identify the place where the branch is to make. A label

16 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
is any valid variable name, and must be followed by a colon. The label is placed immediately
before the statement where the control is to be transferred. The general forms of goto and label
statements are:

Forward jump Backward jump


The ‘label:’ can be anywhere in the program either before or after the ‘goto label;’
statement. goto breaks the normal sequential execution of the program. If the label: is before the
statement goto label; a loop will be formed and some statements will be executed repeatedly.Such
a jump is known as a backward jump. On the other hand, if the label: is placed after the goto label;
some statements will be skipped and the jump is known as a forward jump.
Looping(control structures)
Looping statements are used to execute a statement or group of statements repeatedly for a
specified number of times or as long as the condition is true/ until the condition is false. A loop is a
particular area of a program where some executable statements are written which gets executed by
testing one or more conditions. So, in looping, a sequence of statements is executed until some
conditions for termination are satisfied.
A program loop therefore consists of two segments; the body of the loop and the control statement.
 “body of the loop”. Consists of set of statements.
 “Control statement” .The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop, a control structure can be
classified into two types;
 entry controlled and
 exit controlled.
Entry-controlled loops:-
In Entry controlled loop the test condition is checked first and if that condition is true than
the block of statement in the loop body will be executed.
Example: while loop and for loop.

17 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
Exit controlled loop: -
In exit controlled loop the body of loop will be executed first and at the end the test
condition is checked, if condition is satisfied then body of loop will be executed again.
Example: do-while loop.

C programming language provides three constructs for performing loop operations.


1. The while statement
2. The do statement
3. The for statement
THE while STATEMENT
The while is an entry-controlled loop statement. The test-condition is evaluated and
if the condition is true, then the body of the loop is executed. This process of repeated execution of
the body continues until the test-condition finally becomes false and the control is transferred out
of the loop. On exit, the program continues with the statement immediately after the body of the
loop. The basic format of the while statement is:

while(condition)
{
Body of the loop
}

18 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language

Example
P17. Write a program to find the sum first five natural numbers
void main()
{
int n, sum;
i=1; /*initialization*/
sum=0;
whie( i<=5) /* testing*/
{
sum=sum+i;
i=i+1; /*incrementing*/
}
printf(“sum =%d”, sum);
}
Output
sum =15
THE do STATEMENT
On some occasions it might be necessary to execute the body of the loop before the test is
performed. Such situations can be handled with the help of the do statement.
The general form is:
do
{
Body of the loop
} while(condition);

19 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
On reaching the do statement, the program first evaluates the body of the loop. At the end of the
loop, the test-condition in the while statement is evaluated. The process continues as long as the
condition is true. When the condition becomes false, the loop will be terminated and the control
goes to the statement that appears immediately after the while statement. Since the test-condition is
evaluated at the bottom of the loop, the do…while construct provides an exit-controlled loop and
therefore the body of the loop is always executed at least once.
Example
void main()
{
int n, sum;
i=1; /*initialization*/
sum=0;
do /* testing*/
{
sum=sum+i;
i=i+1; /*incrementing*/
} whie( i<=5);
printf(“sum =%d”, sum);
}
Output

sum =15
THE for STATEMENT
The for loop is another entry-controlled loop. The general form of the for loop is :
for ( initialization ; test-condition ; increment )
{
Body of the loop;
}
The execution of the for statement is as follows:
1. Initialization of the control variables is done first, using assignment statements.
2. The value of the control variable is tested using the test condition. If the condition is true, the
body of the loop is executed; otherwise the loop is terminated and the execution continues with the
statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for statement after
evaluating the last statement in the loop. Now the control variable is incremented /decremented and
the new value of the control variable is again tested to see whether it satisfies the loop condition. If

20 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
the condition is satisfied, the body of the loop is again executed. This process continues till the
value of the control variable fails to satisfy the test-condition.
Example
for ( i=0 ;i<=9 ; i= i+1)
{
printf (“ %d”, i);
}
Output
for loop is executed 10 times and prints the digits 0 to 9 in one line.

Nested For Loop


One for statement within another for statement is known as nesting of for loop.
Syntax
for ( initialization ; test-condition ; increment )
{
…………….
for ( initialization ; test-condition ; increment )
{
……………………………….
}
}
Eg
:
for(i=0;i<10;i++)
{
……………
for(j=0;J<5;j++)
{
………………
}
}
break AND continue
When a break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop. When the loops are nested,
the break would only exit from the loop containing it. That is, the break will exit only a single
loop.
General form of break is:
21 Dept. of CS, IGCAS
Methodology of Programming & C BCA/BSc CS
Language
for( -)
{

-
if(error)
break;

}
-
Example
for(i=0; i<50; i++)
{
if(i==10)
break;
printf("%d\n",i);
}
output
Only numbers 0 through 9 are printed.
The continue causes the loop to be continued with the next iteration after skipping any
statements in between. In while and do loops, continue causes the control to go directly to the test-
condition and then to continue the iteration process. In the case of for loop, the increment section
of the loop is executed before the test-condition is evaluated.
General form of continue is:

22 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language
Examples:
for (i=0;i<100;i++)
{
if (i==50)
continue;
printf ("%d\n",i);
}
The numbers 0 through 99 are printed except for 50.

23 Dept. of CS, IGCAS


Methodology of Programming & C BCA/BSc CS
Language

24 Dept. of CS, IGCAS

You might also like