Académique Documents
Professionnel Documents
Culture Documents
By
Balasore.
Sl Chapter Page
1 Introduction to C 3
2 Conditional Statements 14
3 Loop 20
5 Array
6 String
7 Structure
9 File Handling
Introduction
What is C?
Scenario 1
Both individual agree upon a common language and communicate with each other.
English English
Direct communication is possible
Scenario 2
Both individual do not agree upon a common language and direct communication is not possible.
Hindi English
Direct communication is not possible
possible
Scenario 3
Both individual do not agree upon a common language and communication is possible through a
mediator.
Computer System
C Compiler
Programme
Variables
Constant
Keywords
These are the special words whose meaning is known to the compiler.
There are 32 keywords available in C.
int, char, for, if, else, break, continue etc are the examples of keyword.
Declaration/ Initialization
Input statements are used to take input from the keyboard. scanf() is an example of input statement.
Syntax of scanf():
Output statements are used to print the output/result. printf() is an example of output statement.
Syntax of printf():
scanf(“%d”, &x); means computer will take the value of x which is an integer.
scanf(“%d %c”, &a, &b); means computer will take the value of a and b where a is an integer and b is a
character.
printf(“%d”, x); means computer will print the value of x which is an integer.
printf(“%d %c”, a, b); means computer will print the value of a and b where a is an integer and b is a
character.
printf(“Srinix”); prints srinix on the computer screen.
Escape Character/Sequence
Symbol Meaning
\n New line
\t Tab
\r Carriage return
\b Back space
\a Alert
Example 1.1 Determine the hierarchy of operations and evaluate the following expression:
i=2*3/4+4/4+8-2+5/8
i=2*3/4+4/4+8-2+5/8
i=6/4+4/4+8-2+5/8 operation: *
i=1+4/4+8-2+5/8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i=1+1+8-2+0 operation: /
i=2+8-2+0 operation: +
i = 10 - 2 + 0 operation: +
i=8+0 operation : -
i=8 operation: +
1. Header file
2. void main()
3. Opening Brace( { )
4. Necessary declaration or initialization
5. Take input from keyboard
6. Necessary calculation to get result
7. Print result
8. Closing Brace( } )
Solution:
#include<stdio.h>
void main()
{
int x, y, r;
printf(“Enter two numbers”);
scanf(“%d%d”, &x, &y);
r=x+y;
printf(“%d”, r);
Output:
Enter two numbers
3 4
7
Program 1.2 WAP to find area and perimeter of a rectangle with its length and breadth given
from the keyboard.
Solution:
#include<stdio.h>
void main()
{
int l, b, p, a;
printf(“Enter length and breadth”);
scanf(“%d%d”, &l, &b);
a=l*b;
p=2*(l+b);
printf(“Area=%d and perimeter=%d”, a, p);
}
Output:
Enter length and breadth
2 5
Area=10 and perimeter=20
Program 1.3 WAP to find square and cube of an integer given from the keyboard.
Solution:
#include<stdio.h>
void main()
{
int n, c, s;
printf(“Enter a number”);
scanf(“%d”, &n);
c=n*n*n;
s=n*n;
printf(“Cube is %d and Square is %d”, c,s);
}
Output:
Enter a number
3
Cube is 27 and Square is 9
Solution:
#include<stdio.h>
void main( )
{
int p, n ;
float r, si ;
printf(“Enter value of P, R and T\n”);
scanf(“%d%d%d”, &p, &r, &t);
si = p * n * r / 100 ;
printf ( "\n%f" , si ) ;
}
Output:
Enter value of P, R and T
1000 5 2
100.
C Operators:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulo (%)
Operations of addition, subtraction, multiplication and division literally correspond with their respective
mathematical operators.
Division Rule
Integer/integer=integer
Integer/float=float
Float/integer=float
Float /float=float
Program 1.5
Solution:
#include <stdio.h>
void main ()
{
int a, b, p, q, r, s;
a = 10;
b=4;
p= a/b;
q= a*b;
r= a%b;
s= b%a;
printf(“%d%d%d%d”,p, q, r, s);
}
Out put:
2 40 2 4
Shorthand assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
When we want to modify the value of a variable by performing an operation on the value currently
stored in that variable we can use compound assignment operators:
value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a - 5;
a /= b; is equivalent to a = a / b;
3. Relational and equality operators (==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can use the relational and equality
operators. The result of a relational operation is a Boolean value that can only be true or false,
according to its Boolean result. We may want to compare two expressions, for example, to know if they
are equal or if one is greater than the other is. Here is a list of the relational and equality operators that
can be used in C:
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Important Tips………
Be careful! The operator = (one equal sign) is not the same as the operator == (two equal signs), the first
one is an assignment operator (assigns the value at its right to the variable at its left) and the other one
(==) is the equality operator that compares whether both expressions in the two sides of it are equal to
each other. Thus, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we
compared it to a, that also stores the value 2, so the result of the operation is true.
a b a && b
True True True
True False False
False True False
False False False
The operator || corresponds with Boolean logical operation OR. This operation results true if either one
of its two operands is true, thus being false only when both operands are false themselves. Here are the
possible results of a || b:
a b a || b
True True True
True False True
False True True
False False False
For example:
( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
B=3;
A=++B;
Ans: A contains 4, B contains 4
B=3;
A=B++;
Ans: A contains 3, B contains 4
In Example 7, B is increased before its value is assigned to A. While in Example 8, the value of B is
assigned to A and then B is increased.
6. Conditional operator ( ? : )
The conditional operator evaluates an expression returning a value if that expression is true and a
different one if the expression is evaluated as false. Its format is: condition? result1: result2. If condition
is true the expression will return result1, if it is not it will return result2.
solution:
#include <stdio.h>
void main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
printf(“%d”,c);
}
Output:
7
In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true, thus the first
value specified after the question mark was discarded in favor of the second value (the one after the
colon) which was b, with a value of 7.
7. Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only one
expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost
expression is considered.
For example, the following code:
a = (b=3, b+2); would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end,
variable a would contain the value 5 while variable b would contain value 3.
3. What is a keyword? How many keywords are there in C? Give 5 examples of keyword?
4. Find out the output of the following:
a).#include <stdio.h>
void main()
{
intx=4,y,z;
Y=--x;
Z=x--;
Printf(“%d%d%d”,x,y,z);
}
b).#include<stdio.h>
void main()
{
Int x=0,y=3;
While(x!=y){
Printf(“%d”,y);
If(y==2)
Break;
Y--;
}
c).#include<stdio.h>
void main()
{
Int i=-2;
If(--i)
Printf(“NON-ZERO”);
else
printf(“ZERO”);
}
d).void main()
{
Int i=8;
Printf(“%d%d%d”,i++,++I,i);
}
5. What is a variable? How are keywords different from them?
Chapter 2
Decision Control Structure
if statement
if if else if
if ( condition ) if ( condition )
{ {
// This block works if condition is true /*This block works if condition is true*/
} }
else
{
/*This block works if condition is not
true*/
}
if else if nested if else
if ( condition1 ) if ( condition1 )
{ {
/*This block works if conditio1 is true*/ if ( condition2 )
} {
else if(condition2) /*This block works if both conditio1 and
{ condition 2 are true*/
/*This block works if conditio2 is true */ }
} }
else if ( condition3 ) else
{ {
/*This block works if conditio3 is true*/ if ( condition3 )
Here the condition can be any valid expression including a relational expression.
We can even use arithmetic expressions in if statement.
In C a non-zero value is considered to be true, whereas a 0 is considered to be false.
if ( 3 + 2 % 5 )
printf ( "This works" ) ;
if ( a = 10 )
printf ( "Even this works" ) ;
if ( -5 )
printf ( "Surprisingly even this works" ) ;
Program 2.1 The current year and the year in which the employee joined the organization are
entered through the keyboard. If the number of years for which the employee has served the
organization is greater than 3 then a bonus of Rs. 2500/- is given to the employee. If the years of
service are not greater than 3, then the program should do nothing.
Solution:
#include<stdio.h>
void main( )
{
int bonus, cy, yoj, yr_of_ser ;
printf ( "Enter current year and joining year " ) ;
scanf ( "%d %d", &cy, &yoj ) ;
yr_of_ser = cy - yoj ;
if ( yr_of_ser > 3 )
{
bonus = 2500 ;
printf ( "\n %d", bonus ) ;
}
Output:
Enter current year and year of joining
2010 2002
2500
Solution:
#include<stdio.h>
void main( )
{
int n ;
printf ( "Enter a number " ) ;
scanf ( "%d ", &n) ;
if ( n%2==0 )
{
printf(“\n Even”);
}
else
{
printf(“\n Odd”);
}
}
Output:
Enter a number
9
Odd
Program 2.3 The marks obtained by a student in 5 different subjects are input through the
keyboard. The student gets a division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 – Fail. Write a program to calculate the division obtained by the student.
Solution:
#include<stdio.h>
void main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
Output:
Program 2.4 Write a program to find the roots of a quadratic equation ax2+bx+c=0, where the
values of coefficient a, b and c are given from the keyboard.
Solution:
#include<stdio.h>
void main()
{
int a, b, c, d;
float r1, r2, x, y;
printf(“Enter the coefficients”);
scanf(“%d%d%d”, &a, &b, &c);
d=(b*b) - (4*a*c);
if(d>0)
{
r1=(-b+d^(1/2))/2*a;
r2=(-b-d^(1/2))/2*a;
printf(“%f%f”, r1, r2);
}
else if(d==0)
{
r1=-b/2*a;
printf(“%f”, r1);
}
else
Output:
Enter the coefficients
1 -3 2
1.0 2.0
Program 2.5 If the three sides of a triangle are entered through the keyboard, write a
program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.
Solution:
#include<stdio.h>
void main()
{
int a, b, c;
printf(“Enter 3 sides”);
scanf(“%d%d%d”,&a,&b,&c);
if(a+b>c && b+c>a && c+a>b)
{
if((a*a+b*b)==c*c || (b*b+c*c)==a*a || (c*c+a*a)==b*b)
{
printf(“Right Angled”);
}
else if( (a==b &&b!=c) || (b==c&&c!=a) || (c==a&&a!=b))
{
printf(“Isosceles”);
}
else if(a==b && b==c)
{
printf(“Equilateral”);
}
else
{
printf(“Any Valid Triangle”);
}
}
else
{
printf(“Cannot form a valid triangle”);
}
}
1. List different types of decision control statements. Explain the types of if statement & give
one example for each.
2. Write a C program to solve a quadratic equation.
3. What is the purpose of goto statement? How the associated target statement is identified?
4. Write a program to find the largest of three numbers given from the keyboard. Also draw
the flow chart.
Chapter 3
Loop
The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves
repeating some portion of the program either a specified number of times or until a particular condition
is being satisfied. This repetitive operation is done through a loop control instruction.
There are three methods by way of which we can repeat a part of a program. They are:
It is the most popular looping instruction. The for allows us to specify three things about a loop in a
single line:
(a) Setting a loop counter to an initial value.
(b) Testing the loop counter to determine whether its value has reached the number of repetitions
desired.
(c) Increasing the value of loop counter each time the program segment within the loop has been
executed.
initialization
while(condition)
{
increment/decrement
initialization
do
{
//Body of the loop
Increment/decrement
}while(condition);
Solution:
#include<stdio.h>
Solution:
#include<stdio.h>
void main()
{
int i=1;
while(i<=5)
{
printf(“Ram\n”);
i++;
}
}
Output:
Ram
Ram
Ram
Ram
Ram
Solution:
#include<stdio.h>
void main()
{
int i=1;
do {
printf(“Ram\n”);
i++;
} while(i<=5);
}
23 Programming in C by Er. Sourav Kumar Giri, SCE Balasore. Email: sourav.giri4@gmail.com
Output:
Ram
Ram
Ram
Ram
Ram
Explanation:
When the for statement is executed for the first time, the value of i is set to an initial value 1.
Now the condition i <=5 is tested. Since i is 1 the condition is satisfied and the body of the loop
is executed for the first time.
Upon reaching the closing brace of for, control is sent back to the for statement, where the
value of i gets incremented by 1.
Again the test is performed to check whether the new value of i exceeds 5.
If the value of i is still within the range 1 to 5, the statements within the braces of for are
executed again.
The body of the for loop continues to get executed till i doesn’t exceed the final value 5.
When i reach the value 6 the control exits from the loop and is transferred to the statement (if
any) immediately after the body of for.
Program 3.2 WAP to print all the even integers from 1 to 100.
Solution:
#include<stdio.h>
void main()
{
int i;
for(i=0; i<100 && i%2==0; i++)
{
printf(“%d\n”, i);
}
}
Output:
2
4
6
.
.
.98
Solution:
#include<stdio.h>
void main()
15
Solution:
#include<stdio.h>
void main()
{
int i, n, f=1;
printf(“Enter the value of n”);
scanf(“%d”, &n);
120
Solution:
#include<stdio.h>
void main()
{
int a, n, s=0;
printf(“Enter a number”);
Output:
Enter a number 435
12
Explanation:
Initially n=435(≠0)
So a=435%10=5, s=0+5=5, n=435/10=43
Now n=43(≠0)
So a=3, s=5+3=8, n=4
Now n=4(≠0)
So a=4, s=8+4=12, n=0
Solution:
#include<stdio.h>
void main()
{
int a, n, rn=0;
printf(“Enter a number”);
scanf(“%d”, &n);
while(n!=0)
{
a=n%10;
rn=rn*10+a;
n=n/10;
}
printf(“%d”,rn);
}
Output:
534
Explanation:
Initially n=435(≠0)
So a=435%10=5, s=0*10+5=5, n=435/10=43
Now n=43(≠0)
So a=3, s=5*10+3=53, n=4
Now n=4(≠0)
So a=4, s=53*10+4=534, n=0
Example 3.1 WAP to check whether a no is palindrome number or not. (A number is said to be
palindrome number if it is equal its reverse
Solution:
#include<stdio.h>
void main()
{
int a, n, rn=0, b;
printf(“Enter a number”);
scanf(“%d”, &n);
b=n;
while(n!=0)
{
a=n%10;
rn=rn*10+a;
n=n/10;
}
if(b==rn)
{
printf(“palindrome”);
}
else
{
printf(“not palindrome”);
}
}
Output:
Enter a number 121
palindrome
Solution:
#include<stdio.h>
void main()
{
int a, n,s=0, b;
printf(“Enter a number”);
scanf(“%d”, &n);
b=n;
while(n!=0)
{
a=n%10;
s=s+a*a*a;
n=n/10;
}
if(b==rn)
{
printf(“Armstrong”);
}
else
{
printf(“Not Armstrong”);
}
}
Output:
Enter a number 121
palindrome
Break statement
A break statement takes the control out of the loop.
When break is encountered inside any loop, control automatically passes to the first statement
after the loop.
A break is usually associated with an if.
Example 3.3 WAP to determine whether a number is prime or not. A prime number is one,
which is divisible only by 1 or itself.
Solution:
#include<stdio.h>
void main( )
{
int n, i ;
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
Output:
Enter a number
11
Prime number
Example 3.4 Write a program to print all the prime numbers from 1 to 500
Solution:
. #include<stdio.h>
void main( )
{
int n, i ;
for(n=2; i<=n; n++)
{
for(i=2; i<=n-1; i++)
{
if ( n% i == 0 )
{
break ;
Output:
2
3
5
7
11
13
17
19
23
29
…………..
continue statement
continue statement take the control to the beginning of the loop, bypassing the statements
inside the loop, which have not yet been executed.
The keyword continue allows us to do this.
Flow chart
Flow chart is the structural representation of a program or algorithm.
Shape Meaning
Instruction
Input/Output
Condition
Start/Stop
Solution:
START
Declare n as integer
Input n
YES
n%2=
Even
=0?
NO
Odd
STOP
Solution:
START
Declare i as integer
i=0 i=i+1
YES YES
i <==
Print i
1000
NO
STOP
Assignment-3
1. Write a C program to find the square and cube of 2 digits odd numbers.
2. Write a C program using do while loop, to calculate the sum of all even integers beginning with
i=2 and values of i that are less than 100.
3. Write a C program that will generate a table of values for the equation.
F(x ,y)=2e^x^3+(23+y)^x
Where 1<=x<=5 with an increment 0.5 and 1<=y<=5 with an increment 0.25.
4. Which statement is used to take the control to the beginning of the loop?
5. Explain the difference between while and do while loop.
A function is a self-contained block of statements that perform a coherent task of some kind. Every C
program can be thought of as a collection of these functions.
1. Writing functions avoids rewriting the same code over and over. Suppose you have a section of
code in your program that calculates area of a triangle. If later in the program you want to
calculate the area of a different triangle, you won’t like it if you are required to write the same
instructions all over again. Instead, you would prefer to jump to a ‘section of code’ that
calculates area and then jump back to the place from where you left off. This section of code is
nothing but a function.
2. Using functions it becomes easier to write programs and keep track of what they are doing. If
the operation of a program can be divided into separate activities, and each activity placed in a
different function, then each could be written and checked more or less independently.
Separating the code into modular functions also makes the program easier to design and
understand.
(ii) Function Calling: A function gets called when the function name is followed by a
semicolon.
Syntax is : function_name(list of arguments);
(iii) Function Definition: A function is defined when function name is followed by a pair of
braces in which one or more statements may be present.
Syntax is:
return_type function_name(list of arguments with their types)
{
//Function Body
}
#include<stdio.h>
void add(int, int);
void main()
{
int x, y;
printf(“enter two nos:”);
scanf(“%d%d”, &x, &y);
add(x, y);
}
void add(int a, int b)
{
int c;
c=a+b;
printf(“%d”, c);
}
#include<stdio.h>
int add(int, int);
void main()
{
int x, y, r;
printf(“enter two nos:”);
scanf(“%d%d”, &x, &y);
r =add(x, y);
printf(“%d”, r);
}
int add(int a, int b)
{
int c=a+b;
return(c);
}
Solution:
#include<stdio.h>
int factorial(int);
void main( )
{
int a, fact ;
printf ( "\nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = factorial ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
int factorial ( int x )
{
int f = 1, i ;
for ( i = 1 ; i<=x ; i++ )
{
f=f*i;
}
return ( f ) ;
}
main( )
{
message1( ) ;
message2( ) ;
}
message2( )
{
printf ( "\nBut the butter was bitter" ) ;
}
message1( )
{
printf ( "\nMary bought some butter" ) ;
}
7. A function can call itself. Such a process is called ‘recursion’. We would discuss this aspect of C
functions later in this chapter.
Return statement
If return type of a function is not void, then the function must return some value to the calling function.
This is done using return statement.
1) There is no restriction on the number of return statements that may be present in a function.
Also, the return statement need not always be present at the end of the called function. The
following program illustrates these facts.
fun( )
{
char ch ;
printf ( "\nEnter any alphabet " ) ;
scanf ( "%c", &ch ) ;
if ( ch >= 65 && ch <= 90 )
return ( ch ) ;
else
return ( ch + 32 ) ;
}
In this function different return statements will be executed depending on whether ch is capital
or not.
2) Whenever the control returns from a function some value is definitely returned. If a meaningful
value is returned then it should be accepted in the calling program by equating the called
function to some variable. For example,
sum = calsum ( a, b, c ) ;
3) All the following are valid return statements.
return ( a ) ;
return ( 23 ) ;
return ( 12.34 ) ;
return ;
Calling Convention
Calling convention indicates the order in which arguments are passed to a function when a function call
is encountered. There are two possibilities here:
Arguments might be passed from left to right.
Arguments might be passed from right to left.
Recursion
A function is said to be recursive if it calls itself.
Example 4.2 Write program to find factorial of a number using recursive function.
Solution:
#include<stdio.h>
int factorial(int);
void main( )
{
int a, fact ;
printf ( "\nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = factorial ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
int factorial ( int x )
{
int f ;
if ( x == 1 )
return ( 1 ) ;
else
f = x * factorial ( x - 1 ) ;
return ( f ) ;
}
Example 4.3 Write program to print fibonacii series up to n terms using recursion.
Solution:
#include<stdio.h>
void fibo(int, int, int);
Pointers
Pointer is variable which holds the address of another variable.
Symbol Meaning
& Address of
* Value at address of
int *p; means p is a pointer variable which will hold the address of an integer variable.
float *q; means q is a pointer variable which will hold the address of a float variable.
Consider the following example:
#include<stdio.h>
void main( )
{
int i = 3, *p;
p=&i;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *p) ;
}
Conclusions :
From the above programs that we discussed here we can draw the following conclusions:
If we want that the value of an actual argument should not get changed in the function being
called, pass the actual argument by value.
If we want that the value of an actual argument should get changed in the function being called,
pass the actual argument by reference.
Solution:
#include<stdio.h>
void areaperi(int, float *, float *);
void main( )
{
int radius ;
float area, perimeter ;
printf ( "\nEnter radius of a circle " ) ;
scanf ( "%d", &radius ) ;
areaperi ( radius, &area, &perimeter ) ;
printf ( "Area = %f", area ) ;
printf ( "\nPerimeter = %f", perimeter ) ;
}
void areaperi ( int r, float *a, float *p )
{
*a = 3.14 * r * r ;
*p = 2 * 3.14 * r ;
}
Output:
Important…………..
If a function is to be made to return more than one value at a time then return these values indirectly by
using a call by reference.
1. Define pointer in C language. How the declarations are made for pointer variables? What is the
difference between the function to pointer and pointer to function? What is far pointer?
2. What is a function? What is meant by function call? Define and differentiate between formal and
actual argument.
3. Write a function in c that takes a string as the single parameter and return the integer 1 if the
string is a palindrome, otherwise zero should be returned.
4. Explain the difference between call by value and call by reference with suitable example.
5. Can a function return more than one value? If yes, explain.
6. Write a function power (a, b) to calculate the value of a raised to b both recursively and non
recursively.
7. Any year is entered through the keyboard. Write a function to determine whether the year is a
leap year or not.
8. Write a recursive function to obtain the running sum of first 25 natural numbers.
9. Write a function to find the binary equivalent of a given decimal integer and display it.
10. Write a program to calculate GCD of two integers using recursion.
The first element in the array is numbered 0, so the last element is 1 less than the size of the
array.
An array is also known as a subscripted variable.
Before using an array its type and dimension must be declared.
Example 5.1 Write a program to find average marks obtained by a class of 30 students in a
test.
Solution:
#include<stdio.h>
void main( )
{
int i, sum = 0, marks[30];
float avg;
for ( i = 0 ; i <30 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ;
}
for ( i = 0 ; i <30; i++ )
{
sum = sum + marks[i] ;
}
avg = sum / 30.0 ;
printf ( "\nAverage marks = %d", avg ) ;
}
1. Write an algorithm to multiply two matrix of size m*n and also write a c program.
2. Write a c program to find out the largest number of matrix of size m*n.
3. Write a c program to perform insertion, deletion in a one dimensional array.
4. There are two arrays A & B. A contains 25 elements, whereas B contains 30 elements.
Write a function to create an array c that contains only those elements that are
common to A and B.
5. Write a program to subtract two sparse matrices implemented as an array.
6. Write a program to build a sparse matrix as an array. Write functions to check if the
sparse matrix is a square, diagonal, lower triangular or upper triangular matrix.
7. What is a subscript? What range of values is permitted for the subscript of a one
dimensional n element array?
8. What is an array? How initialization of an array occurs?
9. Write a program that interchanges the odd and even components of an array.
10. Write a program to find if a square matrix is symmetric.
The %s used in printf( ) is a format specification for printing out a string. The same specification can be
used to receive a string from the keyboard, as shown below.
main( )
{
char name[25] ;
printf ( "Enter your name " ) ;
scanf ( "%s", name ) ;
printf ( "Hello %s!", name ) ;
}
Output:
Enter your name Debashish
Hello Debashish!
While entering the string using scanf( ) we must be cautious about two things:
The length of the string should not exceed the dimension of the character array. This is because
the C compiler doesn’t perform bounds checking on character arrays. Hence, if you carelessly
exceed the bounds there is always a danger of overwriting something important, and in that
event, you would have nobody to blame but yourselves.
scanf( ) is not capable of receiving multi-word strings. Therefore names such as ‘Debashish Roy’
would be unacceptable. The way to get around this limitation is by using the function gets().
The usage of functions gets( ) and its counterpart puts( ) is shown below.
main( )
{
char name[25] ;
printf ( "Enter your full name " ) ;
gets ( name ) ;
puts ( "Hello!" ) ;
puts ( name ) ;
To do all the operations described here it is essential to include string.h library header file in the
program.
strlen() function
This function counts and returns the number of characters in a string. The length does not include a
nullcharacter.
Syntax: n=strlen(string);
Where n is integer variable, which receives the value of length of the string.
Example:
length =strlen(“Hollywood”);
The function will assign number of characters 9 in the string to a integer variable length.
Example 6.1 WAP to find the length of the string using strlen() function
Solution:
string1 & string2 are character arrays. When the function strcat is executed string2 is appended to
string1. the string at string2 remains unchanged.
Example:
strcpy(string1,”sri”);
strcpy(string2,”Bhagavan”);
printf(“%s”,strcat(string1,string2);
From the above program segment the value of string1 becomes sribhagavan. The string at str2 remains
unchanged as bhagawan.
strcmp() function
In c you cannot directly compare the value of 2 strings in a condition like if(string1==string2)
Most libraries however contain the strcmp() function, which returns a zero if 2 strings are equal, or a
non zero number if the strings are not the same. The syntax of strcmp() is given below:
strcmp(string1,string2);
String1 & string2 may be string variables or string constants. String1, & string2 may be string variables
or string constants some computers return a negative if the string1 is alphabetically less than the
second and a positive number if the string is greater than the second.
Example:
strcmp(“Newyork”,”Newyork”) will return zero because 2 strings are equal.
strcmp(“their”,”there”) will return a 9 which is the numeric difference between ASCII ‘i’ and ASCII ’r’.
strcmp(“The”, “the”) will return 32 which is the numeric difference between ASCII “T” & ASCII “t”.
strcmpi() function:
This function is same as strcmp() which compares 2 strings but not case sensitive.
Example
strcmpi(“THE”,”the”); will return 0.
Assignment-6
(c) main( )
{
char s[ ] = "No two viruses work similarly" ;
int i = 0 ;
while ( s[i] != 0 )
{
printf ( "\n%c %c", s[i], *( s + i ) ) ;
printf ( "\n%c %c", i[s], *( i + s ) ) ;
i++ ;
}
}
(d) main( )
{
char s[ ] = "Churchgate: no church no gate" ;
char t[25] ;
char *ss, *tt ;
(3). The array char name[10] can consist of a maximum of ______ characters.
(4). The array elements are always stored in _________ memory locations.
3. Write a program that converts all lowercase characters in a given string to its equivalent
uppercase character.
5. Write a program to delete all vowels from a sentence. Assume that the sentence is not more
than 80 characters long.
struct structure_name
{
Structure members
};
The variables which are declared inside structure definition are called as structure member.
Example:
struct book
{
char name[20];
char auth[25];
int page;
float price;
};
struct book b1, b2; here b1 and b2 are two structure variables of type book.
Name of b1 is b1.nm
Author of b1 is b1.auth
Page of b1 is b1.page
Price of b1 is b1.price
Similarly,
Name of b2 is b2.nm
Author of b2 is b2.auth
Page of b2 is b2.page
Price of b2 is b2.price
So access the structure member by using a structure variable through dot (.) operator.
Example 7.1 WAP to accept name, roll, age and marks in 3 different subjects of 80 students
and display the names of the student having percentage greater than 60.
Solution:
#include<stdio.h>
void main()
{
int i;
struct stud
{
char name[20];
char roll[10];
int age, m1, m2, m3;
float avg;
};
struct stud s[80];
Solution:
#include<stdio.h>
void main()
{
struct Complex
{
int real;
int img;
};
struct Complex c1, c2, c3;
c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
union union_name
{
Union members
};
Structure Union
1) Syntax: 1. Syntax:
struct structure_name union union_name
{ {
//Data types //Data types
} }
2) All the members of the structure can 2. In a union only one member can be used at a
be accessed at once. time.
3) Structure allocates memory to each 3. Union allocates the memory equal to the
structure member. maximum memory required by the member of
the union.
struct example{
int x; union example{
float y; int x;
} float y;
Here memory allocated is size }
of(x)+sizeof(y). Here memory allocated is sizeof(y), because
size of float is more than size of integer.
4) Takes more memory. 4. Takes less memory.
Storage Class
To fully define a variable one needs to mention not only its ‘type’ but also its ‘storage class’. In other
words, not only do all variables have a data type, they also have a ‘storage class’. From C compiler’s
point of view, a variable name identifies some physical location within the computer where the string of
bits representing the variable’s value is stored. There are basically two kinds of locations in a computer
where such a value may be kept— Memory and CPU registers. It is the variable’s storage class that
determines in which of these two locations the value is stored.
Storage Memory.
Following program shows how an automatic storage class variable is declared, and the fact that if the
variable is not initialized it contains a garbage value.
main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
}
The output of the above program could be...
1211 221
where, 1211 and 221 are garbage values of i and j. When you run this program you may get different
values, since garbage values are unpredictable. So always make it a point that you initialize the
automatic variables properly, otherwise you are likely to get unexpected results. Note that the keyword
for this storage class is auto, and not automatic.
A value stored in a CPU register can always be accessed faster than the one that is stored in memory.
Therefore, if a variable is used at many places in a program it is better to declare its storage class as
register. A good example of frequently used variables is loop counters. We can name their storage class
as register.
main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}
Storage Memory
Default initial value Zero
Scope Local to the block in which the
variable is defined.
Life Value of the variable persists
between different function calls.
Storage Memory.
Default initial value Zero.
Scope Global.
Life As long as the program’s
execution doesn’t come to an
end.
int x = 21 ;
main( )
{
int y = 31 ;
Here, x and y both are global variables. Since both of them have been defined outside all the functions
both enjoy external storage class. Note the difference between the following:
extern int y ;
int y = 31 ;
Here the first statement is a declaration, whereas the second is the definition. When we declare a
variable no space is reserved for it, whereas, when we define it space gets reserved for it in memory. We
had to declare y since it is being used in printf( ) before it’s definition is encountered. There was no
need to declare x since its definition is done before its usage. Also remember that a variable can be
declared several times but can be defined only once.
int x = 10 ;
main( )
{
int x = 20 ;
printf ( "\n%d", x ) ;
display( ) ;
}
display( )
{
printf ( "\n%d", x ) ;
}
Here x is defined at two places, once outside main ( ) and once inside it. When the control reaches the
printf( ) in main( ) which x gets printed? Whenever such a conflict arises, it’s the local variable that gets
preference over the global variable. Hence the printf( ) outputs 20. When display ( ) is called and
control reaches the printf ( ) there is no such conflict. Hence this time the value of the global x, i.e. 10
gets printed.
Dennis Ritchie has made available to the C programmer a number of storage classes with varying
features, believing that the programmer is in a best position to decide which one of these storage
classes is to be used when. We can make a few ground rules for usage of different storage classes in
different programming situations with a view to:
o Use static storage class only if you want the value of a variable to persist between
different function calls.
o Use register storage class for only those variables that are being used very often in a
program. Reason is, there are very few CPU registers at our disposal and many of them
might be busy doing something else. Make careful utilization of the scarce resources. A
typical application of register storage class is loop counters, which get used a number
of times in a program.
o Use extern storage class for only those variables that are being used by almost all the
functions in the program. This would avoid unnecessary passing of these variables as
arguments when making a function call. Declaring all the variables as extern would
amount to a lot of wastage of memory space because these variables would remain
active throughout the life of the program.
o If you don’t have any of the express needs mentioned above, then use the auto storage
class. In fact most of the times we end up using the auto variables, because often it so
happens that once we have used the variables in a function we don’t mind loosing
them.
Preprocessor
The preprocessor offers several features called preprocessor directives. Each of these preprocessor
directives begins with a # symbol. The directives can be placed anywhere in a program but are most
often placed at the beginning of a program, before the first function definition.
Have a look at the following program.
#define UPPER 25
void main( )
{
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;
}
In this program instead of writing 25 in the for loop we are writing it in the form of UPPER, which has
already been defined before main( ) through the statement,
#define UPPER 25
This statement is called ‘macro definition’ or more commonly, just a ‘macro’. What purpose does it
serve? During preprocessing, the preprocessor replaces every occurrence of UPPER in the program with
25.
Here is another example of macro definition.
UPPER and PI in the above programs are often called ‘macro templates’, whereas, 25 and 3.1415 are
called their corresponding ‘macro expansions’.
#define SQUARE(n) n * n
main( )
{
int j ;
j = 64 / SQUARE ( 4 ) ;
printf ( "j = %d", j ) ;
}
Enumeration
An enumeration consists of a set of named integer constants.
enum rainbowcolors { red, orange, yellow, green, blue, indigo, violet };
Now internally, the compiler will use an int to hold these and if no values are supplied, red will be 0,
orange is 1 etc.
Now internally, the compiler will use an int to hold these and x=6, y=7, z=8 and w=9.
Function Task
malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated
space
calloc Allocates space for an array of elements initializes them to zero and returns a pointer to the
memory
free Frees previously allocated space
realloc Modifies the size of previously allocated space.
ptr=(cast-type*)malloc(byte-size);
ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with
size byte-size.
Example:
x=(int*)malloc(100*sizeof(int));
This function allocates new memory space of size newsize to the pointer variable ptr ans returns a
pointer to the first byte of the memory block. The allocated new block may be or may not be at the
same region.
Assignment-8
The file <stdio.h> contains declarations for the Standard I/O library and should always be included at the very
beginning of C programs using files.
The function fopen is one of the Standard Library functions and returns a file pointer which you use to refer to
the file you have opened e.g.
Example 9.1 Write a program to read a file and display its contents on the screen.
Solution:
# include <stdio.h>
main( )
{
FILE *fp ;
char ch ;
fp = fopen ( "PR1.C", "r" ) ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
{
break ;
}
printf ( "%c", ch ) ;
}
fclose ( fp ) ;
}
Solution:
# include <stdio.h>
void main( )
{
FILE *fp ;
char ch ;
int nol = 0, not = 0, nob = 0, noc = 0 ;
fp = fopen ( "PR1.C", "r" ) ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
noc++ ;
if ( ch == ' ' )
nob++ ;
if ( ch == '\n' )
nol++ ;
if ( ch == '\t' )
not++ ;
}
fclose ( fp ) ;
printf ( "\nNumber of characters = %d", noc ) ;
printf ( "\nNumber of blanks = %d", nob ) ;
printf ( "\nNumber of tabs = %d", not ) ;
printf ( "\nNumber of lines = %d", nol ) ;
}
Solution:
#include <stdio.h>
void main( )
{
FILE *fs, *ft ;
int ch ;
fs = fopen ( "pr1.exe", "rb" ) ;
if ( fs == NULL )
{
puts ( "Cannot open source file" ) ;
exit( ) ;
}
Assignment-9