UNIT II C
UNIT II C
CHAPTER – 3
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);
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
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:
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
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
Simple if statement:
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
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;
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
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.
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.
#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