Unit II Notes C
Unit II Notes C
Unit II Notes C
UNIT II - Managing simple Input and Output operations - Operators and Expressions -
Decision Making: Branching statements, looping statements - Function: Declaration,
Definition - Passing arguments by value - Recursion - Storage classes.
b) putchar()
The putchar( ) is an output function that writes a single character on the standard output device (
monitor ).
Syntax
putchar (variable);
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
char ch;
printf (“Enter any one character : ”);
ch = getchar ( );
printf (“The character you typed is ”);
putchar(ch);
}
Output :
Enter any one character : S
The character you typed is S
c) gets()
This function is used to accept a string from standard input device until ENTER key is pressed.
Syntax
String_variable = gets();
d) puts()
This function is used to display a string to the standard output device.
Syntax
puts (String_variable)
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
char name[20];
printf (“Enter your name : ”);
name = gets( );
printf (“Your name is : ”);
puts(name);
}
Output :
Enter your name : Anand
Your name is : Anand
e) getc()
The getc( ) is an input function that reads a single character from the standard input device (
keyboard ).
Syntax:
char variable;
variable = getc( );
Example:
char ch;
ch = getc( );
f) putc()
The putc( ) is an output function that writes a single character on the standard output device (
monitor ).
Syntax
putc(variable);
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
char ch;
printf (“Enter any one character : ”);
ch = getc( );
printf (“The character you typed is ”);
putc(ch);
}
Output :
Enter any one character : S
The character you typed is S
The control string and variables data type should match each other.
(b) printf ( )
Output data can be displayed in the standard output device (monitor) using printf( ) function.
Syntax
printf (“Control String”, var1, var2, . . .);
Example
printf (“%d %d”, a, b);
printf (“Factorial = %d”, fact);
The variable must be separated by commas and need not be preceded with „&‟ symbol.
Program:
# include<stdio.h>
#include<conio.h>
void main ( )
{
int A, B, C;
printf (“Enter values for A and B : ”);
scanf (“%d %d”, &A, &B);
C = A + B;
printf(“Sum is %d”, C);
getch();
}
Output:
Enter values of A and B : 4 3
Sum is 7
(c) fscanf
This function is used in file processing to read data from a file.
(d) fprintf
This function is used in file processing to write data into a file.
The fscanf() & fprintf() are similar to scanf and printf except that they are used in file processing.
i) Arithmetic Operators:
Arithmetic operations like addition, subtraction, multiplication, division etc can be performed by
using arithmetic operators.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a =15;
int b=10;
int add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul=a*b;
div= a/b;
mod= a%b;
printf( “addition=%d”,add);
prtintf(“subtraction=%d”,sub);
printf”multiplication=%d”,mul);
printf(“division=%d”,div);
printf(“modulo=%d”,mod);
getch();
}
Output:
Addition= 25
Subtraction=5
Multiplication=150
Division=1
Modulo=5
ii) Relational Operators:
Relational operators are used to compare two or more operands.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a =15;
int b=10;
printf( “a<b:%d”,a<b);
prtintf(“a<=b:%d”,a<=b);
printf”a>b:%d”,a>b);
printf(“a>=b:%d”,a>=b);
printf(“a==b:%d”,a==b);
printf(“a!=b:%d”,a!=b);
getch();
}
Output
a<b: 0
a<=b:0
a>b:1
a>=b:1
a==b:0
a!=b:1
Logical NOT is a unary operator that negates the logical value of its single operand.
Logical NOT convert a 1 to 0, and 0 to 1.
Example:
a=10;
++a =11
a++ =10
--a =9
a-- =10
Syntax
condition ? exp1 : exp 2;
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5
int b = 3
int max;
max = a > b ? a : b ;
printf(“Maximum is %d”, max);
getch();
}
Output:
Maximum is 5
In this example, it checks the condition „a > b‟, if it is true, then the value of „a‟ is assigned to
„max‟, otherwise the value of „b‟ is assigned to „max‟.
sizeof Operator: It is used to return the size of the data type or variable.
Example :
sizeof(Y);
Example:
Result= 6+4/ 2.
Phase1: (4/2 operation is evaluated first)
Result= 6+2
Phase2: (6+2 operation is evaluated next)
Result= 8
Program
#include<stdio.h>
#include<conio.h>
void main()
{
Result= 6+4/ 2;
printf(“Result=%d”,Result);
getch();
}
Output
Result= 8
(III) EXPRESSIONS
An expression is a sequence of operators and operands that specifies the computation. An
operand can be a variable, constant or a function call. An operator is a symbol that is used to write
a mathematical, logical or relational expression.
Simple Expression
An expression that has only one operator is known as simple expression.
Example:
X=a+b;
X=++a;
Compound Expression
An expression that has more than one operator is known as compound expression.
Example:
X=a+b*c/f;
Arithmetic Expression
An expression consisting of arithmetic operators is known as arithmetic expression.
Example:
X=a+b;
Logical Expression
An expression consisting of logical operators is known as Logical expression.
Example:
X=a>b;
Program
#include<stdio.h>
#include<conio.h>
void main()
{
Result= 6+4/ 2;
printf(“Result=%d”,Result);
getch();
}
Output
Result= 8
In conditional branching, program control is transferred from one point to another based
upon the outcome of the condition. The conditional branching statements are:
a) if Statement
b) if-else Statement
c) Nested if Statement
e) switch Statement
a) Simple if Statement
It check the given condition in if statement. If it is true then it will execute the body of if
statement, otherwise it skipped the body of if statement.
Syntax:
if (condition)
{
Statement block
}
Flow Chart:
# include<stdio.h>
#include<conio.h>
void main ( )
{
int a;
printf (“\n Enter a number : ”);
scanf (“%d”, &a);
if ( a > 0)
printf (“The given number is positive number”);
getch();
}
Output
Enter a number :7
The given number is positive number
b) if - else Statement
It is a two way branching statement. If the condition is true then the True part statement will be
executed.If the condition is false then the False part statement will be executed.
Flowchart:
Syntax:
if ( condition)
c) Nested if Statement
The if statement within another if statement is called as nested if statement.
Syntax:
if ( condition1 )
{
if ( condition2)
{
Inner if True part Statement
}
else
{
Inner if False part Statement
}
}
else
{
Outer if False part Statement
}
It checks the condition1 and if it is true it check the inner if condition2. This type of nested if is
useful when a series of decisions are involved.
Program :
# include<stdio.h>
#include<conio.h>
void main ( )
{
int Mark;
printf (“Give your Mark”);
scanf (“%d”, &Mark);
if ( Mark < 50 )
printf(“Failed”);
else
{
if ( Mark < 60 )
printf(“Second Class”);
else
printf (“First Class”);
}
getch();
}
Output
Give your mark : 68
First class
Syntax :
if ( condition1 )
Statement block 1
else if ( condition2)
Statement block 2
else if ( condition3 )
Statement block 3
else
Statement block 4
If the condition1 evaluated is true, the statement block1 is executed. If the condition2 is
true, then statement block2 is executed and so on. If none of the conditions are true, then the
statement block4 is executed.
e) switch Statement
It is a multiway branching statement. It first evaluates the expression in switch statement.
That result is compared with each case value one by one. Whenever a match found, it execute the
statements given in the corresponding case statement.If none of the case value matches with the
result it executes the default section.
Syntax:
switch (Expression)
{
case value 1:
Statement block 1
break;
case value 2:
Statement block 2
break;
...
case value n:
Statement block n
break;
default:
Each case block must be terminated by break statement. Otherwise, all statements that are
followed by matched cases are executed.
i) goto Statement
C‟ provides the goto statement to transfer control unconditionally from one place to
another place in the program.
The goto statement can move the program control almost anywhere in the program.
Program : Check Whether the Given Number is Prime or Not Using goto & return.
# include<stdio.h>
# include<conio.h>
void main ( )
{
int No, i;
printf (“Give the number : ”);
scanf (“%d” , &No);
for ( i = 2 ; i <= No / 2; i++ )
{
if ( No / i == 0 )
goto stop;
}
printf (“ Given Number is a Prime Number”);
return;
stop : printf (“ Given Number is not a Prime Number”);
}
Output:
Give the number : 17
Given Number is a Prime Number
In switch statement each case block must be terminated with break statement to exit from
switch.
Syntax:
break;
Example:
Refer switch example program.
iii) continue Statement
It is used within looping statements.
When the continue statement is used inside the loop, it skip the statements which are
available after this statement in the loop and go for the next iteration.
Syntax:
continue;
return Statement
A return statement terminates the execution of a function and returns the control to the calling
function.
The general form of a return statement is
return;
OR
return expression;
OR
return(expression);
If there is a single statement in the loop, the blocking braces is not necessary. If more than
one statement in the loop then the loop statements must be placed within braces.
The following are the loop statements in „C‟.
a) for
b) while
c) do – while
a) for Loop
We use for loop when we know exactly how many times the loop statements are repeated.
Syntax:
for (initialization; condition; incrementing / decrementing)
{
Statements
}
Initialization:
It has the initial value for the counter variable. In a for loop, initialization is executed first.
It is executed only once i.e., for the first iteration only.
Condition:
The condition represents a test expression.
Incrementing / decrementing:
After completing every iteration, the counter variable must be increased or decreased. Otherwise
it may leads to an infinite loop.
Flowchart
Output
Enter the number of terms 5
Sum=15
b) while Loop
while loop is a pre testing loop. The conditional expression is tested before the body is
executed. If the condition is true the loop will be repeated otherwise stop the iteration. If the very
first time itself the condition failed the loop will not be executed at least one time.
Syntax:
while (condition)
{
Body of the loop
}
Flowchart:
void main ( )
{
int i, sum = 0, n;
printf (“Enter the number of terms”);
scanf (“%d”, &n);
i=1;
while( i <= n)
{
sum = sum+ i;
i++;
}
printf (“ Sum = %d”, sum);
getch();
}
Output
Enter the number of terms 5
Sum=15
c) do…while Loop
It is an exit checking loop. In do...while loop the test condition is given at the end of the
loop. Therefore the body of the loop will be executed at least once. If the test condition is true,
then repeat the body of the loop otherwise exit from loop.
Syntax:
do
{
Body of loop statements
} while (test expression);
{
int i, sum = 0, n;
printf (“Enter the number of terms”);
scanf (“%d”, &n);
i=1;
do
{
sum = sum+ i;
i++;
} while( i <= n);
printf (“ Sum = %d”, sum);
getch();
}
Output
Enter the number of terms 5
Sum=15
2. Better readability
User-defined functions
3. Function Definition
1. FUNCTION PROTOTYPE
Function prototype is a declaration statement that identifies function with function name,
data type, a list of a arguments. All the function need to be declared before they are used. (i.e.
called)
Syntax: returntype functionname (parameter list);
Return type – data type of return value. It can be int, float, double, char, void etc.
Function name – name of the function
Parameter type list –It is a comma separated list of parameter types.
Example:
int add(int a, int b);
Function declaration must be terminated with a semicolon(;).
Types of function prototypes:
1. Function with no arguments and no return values
2. Function with arguments and no return values
3. Function with arguments and one return values
4. Function with no arguments and with return values
Output:
Enter the value for a: 10
Value = 10
int r;
float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r);
printf(“Area of a circle =%d\n”, area);
getch();
}
int circlearea(int r1)
{
return 3.14 * r1 * r1;
}
Output:
Enter the radius
2
Area of circle = 12.000
{
float area;
area=circlearea();
printf(“Area of a circle =%d\n”, area);
getch();
}
int circlearea()
{
int r=2;
return 3.14 * r * r;
}
Output:
Enter the radius
2
Area of circle = 12.000
2. FUNCTION DEFINITION
It is also known as function implementation. When the function is defined, space is
allocated for that function in memory.
Syntax
returntype functionname (parameter list)
{
statements;
return (value);
}
Example
int abc(int, int, int) // Function declaration
void main()
{
int x,y,z;
abc(x,y,z) // Function Call
…
…
}
int abc(int i, int j, int k) // Function definition
{
…….
….
return (value);
}
The return statement is used to return the result of the called function to the calling function.
Program:
#include<stdio.h>
#include<conio.h>
float circlearea(int); //function prototype
void main()
{
int r;
float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r); //function call
printf(“Area of circle =%f\n”, area);
getch();
}
float circlearea(int r1)
{
return 3.14 * r1 * r1; //function definition
}
Output:
Enter the radius
2
Area of circle = 12.000
3. FUNCTION CALL
Function call is used to invoke the function. So the program control is transferred to that
function. A function can be called by using its name & actual parameters.
Function call should be terminated by a semicolon ( ; ).
Syntax:
Functionname(argumentlist);
Example
int abc(int, int, int) // Function declaration
void main()
{
int x,y,z;
abc(x,y,z) // Function Call
…
…
}
Calling function – The function that calls a function is known as a calling function.
Called function – The function that has been called is known as a called function.
Actual arguments – The arguments of the calling function are called as actual arguments.
Formal arguments – The arguments of called function are called as formal arguments.
2. The execution of the calling function is suspended and the called function starts execution.
3. After the execution of the called function, the program control returns to the calling function
and the calling function resumes its execution.
Program:
#include<stdio.h>
#include<conio.h>
float circlearea(int); //function prototype
void main()
{
int r;
float area;
printf(“Enter the radius \n”);
scanf(“%d”,&r);
area=circlearea(r); //function call
printf(“Area of a circle =%f\n”, area);
getch();
}
ARGUMENTS
Argument is the value, supply to function call. This value is assigned to corresponding
parameter in the function definition. Arguments are specified within a pair of paranthesis,
separated by commas.
Types of arguments
i) Required arguments
ii) Keyword arguments
iii) Default arguments
iv) Variable-Length arguments
i) Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here
number of arguments in function call should match exactly with function definition.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(6,4))
Output:
The sum is:10
Default argument is an argument that assume default value if value is not provided in function call.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(a=5))
Output:
The sum is:15
iv)Variable-Length arguments
Variable-Length arguments are arguments that makes function call with any number of arguments.
Here (*) is placed before the name of the variable.
Example Program:
def greeting(*name):
print(“Hai”,name)
greeting(“Welcome”)
greeting(“Welcome”,”Hello”)
Output:
Hai Welcome
Hai Welcome Hello
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int ,int);
a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf(“\n In Swap, x=%d and y=%d”, x,y);
}
Output:
Before swapping: a =10 and b =20
In Swap, x=20 and y=10
After swapping: a =10 and b = 20
Explanation:
In the above program, before calling the swap function, the value of a is 10 and the value of b is
20. During the function call, the values of a and b are passed to x and y. In the swap function, the
values of x and y are swapped. Now, x has the value 20 and y has the value 10. But this change
does not get reflected in the value of a and b.
Example:
#include<stdio.h>
#include<conio.h>
void swap(int *, int *)
void main()
{
int a = 10, b = 20;
printf(“Before swap a = %d, b = %d \n”, a,b);
swap (&a, &b);
printf(“After swap a = %d, b = %d”, a, b);
getch();
}
void swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf(“\n In Swap, x=%d and y=%d”, *x,*y);
}
Output:
Before swap a = 10, b = 20
In Swap, x=20 and y=10
After swap a = 20, b = 10
Explanation:
In the above program, before calling the swap function, the value of a is 10 and the value of b is
20. During the function call, the references of a and b are passed to x and y. In the swap function,
the values of x and y are swapped. Now, x has the value 20 and y has the value 10. This change
gets reflected in the value of a and b.
2.7 RECURSION
Recursion is defined as the function that calls itself repeatedly until condition is reached.
But while using recursion, programmers need to be careful to define an exit condition from the
function; otherwise it will go into an infinite loop.
Syntax:
Function1()
{
Function1();
}
Example:
Calculating the factorial of a number
Fact (n)= n*fact(n-1);
6! = 6*fact(n);
6! = 6 *5*fact(4)
6! = 6 * 5 * 4 *fact(3)
6! = 6 * 5 * 4 * 3 *fact(2)
6! =6 *5 * 4 * 3 *2 * fact(1)
6! = 6 *5 * 4 * 3 *2 * 1
6!=120
Advantage of recursion
Recursion makes program elegant and cleaner.
All algorithms can be defined recursively which makes it easier to visualize and prove.
Reduce unnecessary calling of function
Easy to solve complex problems
Direct Recursion:
A function is directly recursive if it calls itself.
A( )
{
….
A( ); // call to itself
….
}
Indirect Recursion:
Function calls another function, which in turn calls the original function.
A( )
{
…
B( );
…
}
B( )
{
…
A( );// function B calls A
…
}
Linear Recursion - It makes only one recursive call.
Binary Recursion - It calls itself twice.
N-ary recursion - It calls itself n times.
Syntax:
auto datatype var1,var2,…..,varn;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
// or
//or
int a;
void main()
{
…..
}