C Programming
C Programming
Overview of C language
C is a structured programming language developed by Dennis Ritchie in 1973
at Bell Laboratories. It is one of the most popular computer languages today
because of its structure, high-level abstraction, machine independent feature.
C language was developed with UNIX operating system, so it is strongly
associated with UNIX, which is one of the most popular network operating
system in use today and heart of internet data superhighway.
C Character Set:
Page 1
variable declaration
A variable definition tells the compiler where and how much storage to create
for the variable. A variable definition specifies a data type and contains a list
of one or more variables of that type as follows
type variable_list;
Here, type must be a valid C data type including char, int, float, double or
any user-defined object; and variable_list may consist of one or more
identifier names separated by commas. Some valid declarations are shown
here
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which
instruct the compiler to create variables named i, j and k of type int.
Variable Initialization
Page 2
int d = 3, f = 5; // definition and initializing d and f.
float z = 2.2; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
Note : For definition without an initializer: the initial value of all other
variables are undefined.
Keywords
The following list shows the reserved words in C. These reserved words may
not be used as constants or variables or any other identifier names.
Constants in C refer to fixed values that program cannot change during the
time of execution. Constants are also known as literals.
C Constants are like normal variables, the only difference is, their values
cannot be changed by the program once they are defined.
Operators in C
Operators are the symbol which operates on value or a variable. For example:
+ is a operator to perform addition.
Operators in C programming
Arithmetic Operators +, -, /, *, %
Increment and Decrement Operators ++, --
Assignment Operators =, +=, -=, *=, /=
Page 3
Relational Operators >, >= , ==, <, <=, !=
Logical Operators &&, ||, !
Conditional Operators ?:
Bitwise Operators &, |, >>, <<, ^,
Special Operators ., ,,
Evaluation of expression
High priority * / %
Low priority + -
ii) Formatted function: These are used to accept or print any type of data.
Page 4
5 marks questions
a) Keywords: These are reserved words which have predefined meanings &
those meanings can not be changed.
e.g. { }, [ ] etc
C Constants are fixed values, their values cannot be changed by the program
once they are defined.
Page 5
a) Numeric constants b) Character constants
Hexa decimal constants. e.g 0x12, 0x4AB, 0xFF (Begins with 0x)
e.g. a, +, etc
Q3. What is a variable? Write the rules & guidelines for naming
variables?
A variable is a name that may be used to store a data value. Unlike constant,
variables
Page 6
A C identifier is a name used to identify a variable, function, or any other user-
defined item. Here are some examples of acceptable identifiers
4. Name of identifier is case sensitive i.e. num and Num are two different
variables.
6. Name of identifier can not include any blank spaces or special character
except under score
High priority * / %
Page 7
Low priority + -
Features of C language
It is a robust language with rich set of built-in functions and operators
that can be used to write any complex program.
The C compiler combines the capabilities of an assembly language with
features of a high-level language.
Programs Written in C are efficient and fast. This is due to its variety of
data type and powerful operators.
It is many time faster than BASIC.
C is highly portable this means that programs once written can be run
on another machines with little or no modification.
Another important feature of C program, is its ability to extend itself.
A C program is basically a collection of functions that are supported by
C library. We can also create our own function and add it to C library.
C language is the most widely used language in operating systems and
embedded system development today.
Page 8
Syntax : epr1 ? expr2 : expr3;
#include <stdio.h>
int main()
{
char feb;
int days;
printf("Enter l if the year is leap year otherwise enter 0: ");
scanf("%c",&feb);
days=(feb=='l')?29:28;
/*If test condition (feb=='l') is true, days will be equal to 29. */
/*If test condition (feb=='l') is false, days will be equal to 28. */
printf("Number of days in February = %d",days);
return 0;
}
Output
The most common assignment operator is =. This operator assigns the value
in right side to the left side variable. To the right of an assignment operator
there can be a constant or variable or an arithmetic expression. But to the left
there should be only one variable. For example:
Page 9
i) Unformatted function: These are used to accept or print only character
or string data.
ii) Formatted function: These are used to accept or print any type of data.
e.g. printf(%d%f%c,v1,v2,v3);
Page 10
int (unsigned octal value) %o
scanf() is the standard input function used to accept input from key board in
the specified format.
e.g. scanf(%d%c%f,&v1,&v2,&v3);
Where & is called as address operator, which specify the address of the
location where data is to be stored.
Void main()
int a,b,c,sum;
float avg;
printf(Enter 3 numbers
scanf(%d%d%d,&a,&b,&c);
sum = a + b + c;
Page 11
}
10 Marks:
a) Prefix increment operator ( ++var) : ++var will increment the value of var
and then return it . e.g. if a=5 then ++a will return a=6;
b) Postfix increment operator (var++) : var++ operator will return the value of
operand first and then only increment it. e.g. if a=5 then a++ will return a=5;
a) Prefix decrement operator ( --var) : --var will decrement the value of var and
then return it . e.g. if a=5 then --a will return a=4;
b) Postfix decrement operator (var--) : var-- operator will return the value of
operand first and then only decrement it. e.g. if a=5 then a-- will return a=5;
#include <stdio.h>
int main()
{
int c=2,d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by
1 to 3.
printf("%d",++c); //this statement increments 1 to c then, only c is
displayed.
return 0;
}
Output
2
4
Page 12
Q3. Explain the basic data types of C language.
Integer Types
The following table provides the details of standard integer types with their
storage sizes and value ranges
Floating-Point Types
The following table provide the details of standard floating-point types with
storage sizes and value ranges and their precision
Character Types
Page 13
Q4. Define the following with an example: a) C Keyword b) variable
c) Constants
a) Keywords: These are reserved words which have predefined meanings &
those meanings can not be changed.
d) Format Specifier: They are used to specify various data types & their
formats in printf() & scanf() functions.
Page 14
Q5. Define the following terms. Five one example each.
e) Conditional Operator
b) Keywords: These are reserved words which have predefined meanings &
those meanings can not be changed.
Q6. WAP to swap the values of two variables without using third
variable.
#include <stdio.h>
int main()
{
int a, b;
printf("Enter value of a: ");
Page 15
scanf("%d",&a);
printf("Enter value of b: ");
scanf("%d",&b);
b=a+b; /* a=1 & b=2 then b=a+b=3*/
a=b-a; /* a=3-1 = 2, i.e. a=2 */
b=b-a; /* b = 3 2 = 1 i.e. b=1 */
printf("\nAfter swapping, value of a = %d\n", a);
printf("After swapping, value of b = %d", b);
return 0;
}
Output
Enter value of a: 1
Enter value of b: 2
Page 16
link functions from the system library.
3. Definition section : The definition section defines all symbolic
constants.
4. Global declaration section : There are some variables that are used
in more than one function. Such variables are called global variables and
are declared in the global declaration section that is outside of all the
functions. This section also declares all the user-defined functions.
5. main () function section : Every C program must have one main
function section. This section contains two parts; declaration part and
executable part
6. Declaration part : The declaration part declares all the variables used
in the executable part.
7. Executable part : There is at least one statement in the executable
part. These two parts must appear between the opening and closing
braces. The program execution begins at the opening brace and ends at
the closing brace. The closing brace of the main function is the logical
end of the program. All statements in the declaration and executable part
end with a semicolon.
8. Subprogram section : The subprogram section contains all the user-
defined functions that are called in the main () function. User-defined
functions are generally placed immediately after the main () function,
although they may appear in any order.
All section, except the main () function section may be absent when they are
not required.
#include <stdio.h>
int main(){
int a, b, c, large;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
large = a;
large = large > b ? large : b;
large = large > c ? large : c;
printf("Largest number = %d", large);
return 0;
}
Output
Largest number = 5
Q9. WAP to swap the values of two variables using third variable.
#include <stdio.h>
int main()
Page 17
{
float a, b, temp;
printf("Enter value of a: ");
scanf("%f",&a);
printf("Enter value of b: ");
scanf("%f",&b);
temp = a; /* Value of a is stored in variable temp */
a = b; /* Value of b is stored in variable a */
b = temp; /* Value of temp(which contains initial value of a) is stored in
variable b*/
printf("\nAfter swapping, value of a = %.2f\n", a);
printf("After swapping, value of b = %.2f", b);
return 0;
}
Output
#include <stdio.h>
int main()
{
float r,area,circum;
printf("Enter value of radius: ");
scanf("%f",&r);
area = 2*3.14 * r;
circum = 3.14 * r * r;
printf("\nArea of a circle = %.2f\n", area);
printf("Circumference of circle = %.2f", circum);
return 0;
}
Output
Page 18
CHAPTER 2:
DECISION MAKING, BRANCHING & LOOPING
Logical operators are used to combine expressions containing relation operators. In C,
there are 3 logical operators:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Relational operators checks relationship between two operands. If the relation is true,
it returns value 1 and if the relation is false, it returns value 0.
Operator Meaning
== Equal to
> Greater than
< Less than
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
1. Simple if statement
2. If....else statement
3. Nested if....else statement
4. else if statement
Loops in C Lanugage
1. while loop
2. for loop
3. do-while loo
5 Marks:
Page 19
Q1. Explain different logical operators with examples.
Meaning of
Operator Example
Operator
If c=5 and d=2 then,((c==5) && (d>5)) returns
&& Logical AND
false.
|| Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) returns true.
! Logical NOT If c=5 then, !(c==5) returns false.
a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then,
it returns 0.
if statement
if( expression )
{
statement-inside;
}
statement-outside;
Page 20
If the expression is true, then 'statement-inside' it will be executed, otherwise
'statement-inside' is skipped and only 'statement-outside' is executed.
if...else statement
if( expression )
{
statement-block1;
}
else
{
statement-block2;
}
Sl no While Do_while
1 Entry controlled loop Exit controlled loop
2 The while statement The do-while statement
verifies the condition executes the first
before entering into the iteration without
loop to see whether the checking the condition, it
next loop iteration should verifies the condition
occur or not. after finishing each
iteration.
3 The while statement will The do-while statement
not execute not even once will always execute the
if the condition is false at body of a loop at least
the beginning. once.
4 The test condition is The test condition is
placed at the begging of placed at the end of the
the loop loop
Sl no if If - else
1 The body of if statement The body of if - else
includes only true part statement includes both
true part & false part
2 The body of if statement In if else statement, if
is executed, if the the condition is true the if
condition is true. part is executed or if the
Otherwise program condition is false the else
control comes out of the part is executed. then the
if statement program control comes
Page 21
out of the if statement
if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{
statement-block 3;
}
Example :
#include <stdio.h>
#include <conio.h>
void main( )
{
int a,b,c;
clrscr();
printf("enter 3 number");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if( a > c)
{
printf("a is greatest");
}
else
{
printf("c is greatest");
}
}
else
Page 22
{
if( b> c)
{
printf("b is greatest");
}
else
{
printf("c is greatest");
}
}
getch();
}
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;
The expression is tested from the top(of the ladder) downwards. As soon as
the true condition is found, the statement associated with it is executed.
Example :
#include <stdio.h>
#include <conio.h>
void main( )
{
int a;
printf("enter a number");
scanf("%d",&a);
if( a%5==0 && a%8==0)
{
printf("divisible by both 5 and 8");
}
else if( a%8==0 )
{
Page 23
printf("divisible by 8");
}
else if(a%5==0)
{
printf("divisible by 5");
}
else
{
printf("divisible by none");
}
getch();
}
#include <stdio.h>
int main(){
float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if (a>=b)
{
if(a>=c)
printf("Largest number = %.2f",a);
else
printf("Largest number = %.2f",c);
}
else
{
if(b>=c)
printf("Largest number = %.2f",b);
else
printf("Largest number = %.2f",c);
}
return 0;
}
1) break statement
Page 24
When break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following
the loop.
2) continue statement
It causes the control to go directly to the test-condition and then continue the
loop process. On encountering continue, cursor leave the current cycle of loop,
and starts with the next cycle.
Page 25
b) goto & label statement: In C programming, goto statement is used for
altering the normal sequence of program execution by transferring control to
some other part of the program with out checking for any condition.
Refer Q1 & Q2
Switch statement
Switch statement is used to solve multiple option type problems for menu like
program, where one value is associated with each option. The expression in
switch case evaluates to return an integral value, which is then compared to
the values in different cases, where it matches that block of code is executed, if
there is no match, then default block is executed. The general form of switch
statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
Page 26
case value-4:
block-4;
break;
default:
default-block;
break;
}
1. It isn't necessary to use break after each block, but if you do not use it,
all the consecutive block of codes will get executed after the matching
block.
2. int i = 1;
3. switch(i)
4. {
5. case 1:
6. printf("A"); // No break
7. case 2:
8. printf("B"); // No break
9. case 3:
10. printf("C");
11. break;
12. }
Output : A B C
do while loop
In some situations it is necessary to execute body of the loop before testing the
condition. Such situations can be handled with the help of do-while loop. do
statement evaluates the body of the loop first and at the end, the condition is
checked using while statement. General format of do-while loop is,
do
{
....
.....
}
while(condition);
#include<stdio.h>
#include<conio.h>
void main()
{
int a,i;
a=5;
i=1;
Page 27
do
{
printf("%d\t",a*i);
i++;
}
while(i <= 10);
getch();
}
output
5 10 15 20 25 30 35 40 45 50
Sl break continue
no
1 A break can appear in both A continue can appear only in loop (for,
switch and loop (for, while, do) while, do) statements.
statements.
2 A break causes the switch or loop A continue doesn't terminate the loop, it
statements to terminate the causes the loop to go to the next
moment it is executed. Loop or iteration. All iterations of the loop are
switch ends abruptly when executed even if continue is
break is encountered. encountered. The continue statement is
used to skip statements in the loop
that appear after the continue.
3 The break statement can be The continue statement can appear only
used in both switch and loop in loops. You will get an error if this
statements. appears in switch statement.
Page 28
Q16. WAP to check whether the given number is odd or even.
#include <stdio.h>
int main()
{
int num;
printf("Enter a number you want to check.\n");
scanf("%d",&num);
if((num % 2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
return 0;
}
Output 1
Output 2
Refer Q1
Refer Q2.
for loop
Page 29
In for loop we have exactly two semicolons, one after initialization and second
after condition. In this loop we can have more than one initialization or
increment/decrement, separated using comma operator. for loop can have
only one condition.
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
for(x=1; x<=10; x++)
{
printf("%d\t",x);
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
10 marks
#include <stdio.h>
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
Output:
y is greater than x
Page 30
one for loop inside another for loop. Basic syntax is,
#include <stdio.h>
#include <math.h> /* This is needed to use sqrt() function.*/
int main()
{
Int n;
float a, b, c, determinant, r1,r2, real, imag;
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
determinant=b*b-4*a*c;
if (determinant>0)
{
N= 1;
}
else if (determinant==0)
{
N = 2;
}
else
{
N= 3;
}
Switch(n)
{
Case 1: r1= (-b+sqrt(determinant))/(2*a);
r2= (-b-sqrt(determinant))/(2*a);
printf("Roots are: %.2f and %.2f",r1 , r2);
break;
case 2: r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f", r1, r2);
break;
case 3: real= -b/(2*a);
imag = sqrt(-determinant)/(2*a);
Page 31
printf("Roots are: %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag);
}
return 0;
}
Output 1
Output 2
Syntax :
variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}
#include<stdio.h>
#include<conio.h>
void main( )
{
Page 32
int x;
x=1;
while(x<=10)
{
printf("%d\t", x);
x++;
}
getch();
}
output
1 2 3 4 5 6 7 8 9 10
Q6. WAP to find the number & sum of all numbers greater than 150
& less than 250 which are divisible by 8.
#include <stdio.h>
int main()
{
int i,sum=0,
for(i=150; i<=250; i++)
{
if(i%8 == 0)
sum = sum+I;
}
printf( sum = %d,sum);
return 0;
}
#include <stdio.h>
int main(){
float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if (a>=b)
{
if(a>=c)
printf("Largest number = %.2f",a);
else
printf("Largest number = %.2f",c);
}
else
{
if(b>=c)
printf("Largest number = %.2f",b);
else
Page 33
printf("Largest number = %.2f",c);
}
return 0;
}
#include <stdio.h>
int main(){
float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if(a<=b && a<=c)
printf("Smallest number = %.2f", a);
else if(b<=a && b<=c)
printf("Smallest number = %.2f", b);
else
printf("Smallest number = %.2f", c);
return 0;
}
#include <stdio.h>
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=1;
break;
}
Page 34
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
Output
Output
#include <stdio.h>
int main(){
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
Page 35
}
printf("Sum=%d",sum);
return 0;
}
Output
#include <stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
printf("Reversed Number = %d",reverse);
return 0;
}
Output
#include <stdio.h>
int main()
{
int num,i,ocount,ecount,n;
printf("Enter a number \n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
if((i%2)==0) //checking whether remainder is 0 or not.
Ecount = ecount + 1;
Else
Ocount = ocount + 1;
Page 36
}
Printf(Number of even numbers = %d,ecount);
Printf(number of odd numbers = %d,ocount);
return 0;
}
Page 37
CHAPTER 3: FUNCTIONS
Define function.
Types of C functions
Defining a Function
Types of parameters
1. actual parameter
2. Formal parameter
1. call by value
2. call by reference
Scope of a variable
Page 38
5 MARKS:
A C program has at least one function main(). Without main() function, there is
technically no C program.
Types of C functions
Library function
User defined function
Library function
main()
printf()
scanf()
Page 39
2. If repeated code occurs in a program. Function can be used to include
those codes and execute when needed by calling that function.
3. Programmer working on large project can divide the workload by
making different functions.
Local Variables
Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of
code. Local variables are not known to functions outside their own. The
following example shows how local variables are used. Here all the variables a,
b, and c are local to main() function.
#include <stdio.h>
int main () {
Page 40
c = a + b;
return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the program.
Global variables hold their values throughout the lifetime of your program and
they can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. The
following program show how global variables are used in a program.
#include <stdio.h>
int main () {
a = g + b;
return 0;
}
#include <stdio.h>
void function_name()
{
................
................
}
int main()
{
Page 41
...........
...........
function_name();
...........
...........
}
Every C program begins from main() and program starts executing the codes
inside main() function. When the control of program reaches to function_name()
inside main() function. The control of program jumps to void function_name() and
executes the codes inside it. When all the codes inside that user-defined
function are executed, control of the program jumps to the statement just after
function_name() from where it is called.
#include <stdio.h>
int main()
{
/* If you write printf() statement without including header file, this program
will show error. */
printf("Catch me if you can.");
}
There is at least one function in any C program, i.e., the main() function (which
is also a library function). This program is called at program starts.
Page 42
Suppose, you want to find the square root of a number. You can write your
own piece of code to find square root but, this process is time consuming and
the code you have written may not be the most efficient process to find square
root. But, in C programming you can find the square root by just using sqrt()
function which is defined under header file "math.h"
#include <stdio.h>
/* function declaration */
int great(int num1, int num2);
int main () {
return 0;
}
Page 43
return result;
}
Defining a Function
Example
Given below is the source code for a function called great(). This function
takes two parameters num1 and num2 and returns the maximum value
between the two
Page 44
return result;
}
b) Actual parameter: The variables used in function call are called actual
parameters. E.g. ret = max(a, b); In this a,b are actual parameters.
In the above example,int add(int a, int b); is a function prototype which provides
following information to the compiler:
10 MARKS:
Page 45
#include<stdio.h>
int factorial(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;
}
int factorial(int n)
{
Int I, f = 1;
For(i=1;i<=n;i++)
F = f * I;
Return(f);
}
Output
#include<stdio.h>
int GCD(int n);
int main()
{
int num1,num2,g=0;
printf("Enter two integers: ");
scanf("%d %d",&num1,&num2);
printf("HCF of %d and %d is ",num1 , num2);
g= GCD(num1,num2)
printf(GCD = %d,g);
return 0;
}
Page 46
Output
As shown in the example the initial value of variable g = 0. After the execution
of the GCD() function the g value is g= 7
While calling a function, there are two ways in which arguments can be passed to a
function
1 This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.
Call by reference
i) A function may return a value. The return_type is the data type of the
value the function returns.e.g int
#include<stdio.h>
float calculate_area(int);
Page 47
int main()
{
int radius;
float area;
printf("\nEnter the radius of the circle : ");
scanf("%d",&radius);
area = calculate_area(radius);
printf("\nArea of Circle : %f ",area);
return(0);
}
float calculate_area(int radius)
{
float areaOfCircle;
areaOfCircle = 3.14 * radius * radius;
return(areaOfCircle);
}
Output :
Enter the radius of the circle : 2
Area of Circle : 12.56
In the above program we can see that inside main function we are calling a
user defined calculate_area() function.
#include<stdio.h>
void area()
{
float area_circle;
float rad;
Page 48
Output :
Enter the radius : 3
Area of Circle = 28.260000
void main()
{
area();
}
We have just called a function , we can see that there is no variable or anything
specified between the pair of round brackets.
void area();
Now in the prototype definition (line No 3) of the function we can see the
return value as Void. Void means it does not return anything to the calling
function.
CHAPTER 4: ARRAYS
Page 49
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays
5 MARKS:
Declaring an Array
Like any other variable, arrays must be declared before they are used. General
form of array declaration is,
data-type variable-name[size];
for example :
int arr[10];
Here int is the data type, arr is the name of the array and 10 is the size of
array. It means array arr can only contain 10 elements of int type. Index of
an array starts from 0 to size-1 i.e first element of arr array will be stored at
arr[0] address and last element will occupy arr[9].
Initialization of an Array
Page 50
67 87 56 77
M[0] M[1] M[2] M[3]
int age[]={2,4,34,3,4};
type array-name[row-size][column-size]
Example :
int a[3][3];
The above array can also be declared and initialized together. Such as,
int A[2][3] = {
{0,0,0},
{1,1,1}
};
0 0 0 0
A[0][0] A[0][1] A[0][2] A[0][3]
1 1 1 1
A[1][0] A[1][1] A[1][2] A[1][3]
Page 51
int c[2][3]={1,3,0,-1,5,9};
Array having only one Array having more than one subscript
subscript variable is called variable is called Multi-Dimensional
2
One-Dimensional array array.
Refer Q2 (5 marks)
#include <stdio.h>
#include <conio.h>
void main()
{
int array[10];
int i, N, keynum, found=0;
clrscr();
Page 52
found = 1;
break;
}
}
if ( found == 1)
printf("SUCCESSFUL SEARCH\n");
else
printf("Search is FAILED\n");
} /* End of main */
Refer Q1 ( 5 marks)
1. Traversing
2. Searching
3. Insertion
4. Deletion
5. Sorting
6. Merging
1. Traversing: It is used to access each data item exactly once so that it can
be processed.
E.g.
We have linear array A as below:
1 2 3 4 5
10 20 30 40 50
Here we will start from beginning and will go till last element and during this
process we will access value of each element exactly once as below:
A [1] = 10
A [2] = 20
A [3] = 30
A [4] = 40
A [5] = 50
2. Searching: It is used to find out the location of the data item if it exists in
the given collection of data items.
E.g.
We have linear array A as below:
Page 53
1 2 3 4 5
15 50 35 20 25
Suppose item to be searched is 20. We will start from beginning and will
compare 20 with each element. This process will continue until element is
found or array is finished. Here:
1) Compare 20 with 15
20 # 15, go to next element.
2) Compare 20 with 50
20 # 50, go to next element.
3) Compare 20 with 35
20 #35, go to next element.
4) Compare 20 with 20
20 = 20, so 20 is found and its location is 4.
3. Insertion: It is used to add a new data item in the given collection of data
items.
E.g.
We have linear array A as below:
1 2 3 4 5
10 20 50 30 15
New element to be inserted is 100 and location for insertion is 3. So shift the
elements from 5th location to 3rd location downwards by 1 place. And then
insert 100 at 3rd location. It is shown below:
Page 54
4. Deletion: It is used to delete an existing data item from the given
collection of data items.
E.g.
We have linear array A as below:
1 2 3 4 5
10 20 50 40 25 60
Page 55
5. Sorting: It is used to arrange the data items in some order i.e. in
ascending or descending order in case of numerical data and in dictionary
order in case of alphanumeric data.
E.g.
We have linear array A as below:
1 2 3 4 5
10 50 40 20 30
After arranging the elements in increasing order by using a sorting technique, the
array will be:
1 2 3 4 5
10 20 30 40 50
6. Merging: It is used to combine the data items of two sorted files into
single file in the sorted form
We have sorted linear array A as below:
1 2 3 4 5 6
10 40 50 80 95 100
1 2 3 4
20 35 45 90
1 2 3 4 5 6 7 8 9 10
10 20 35 40 45 50 80 90 95 100
#include <stdio.h>
int main()
{
Page 56
int temp[5][5];
return 0;
}
Output
#include <stdio.h>
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
Page 57
printf("Transpose of entered matrix :-\n");
return 0;
}
Advantages:
1. It is used to represent multiple data items of same type by using only single
name.
2. It can be used to implement other data structures like linked lists, stacks,
queues, trees, graphs etc.
3. 2D arrays are used to represent matrices.
Disadvantages:
1. We must know in advance that how many elements are to be stored in array.
2. Array is static structure. It means that array is of fixed size. The memory
which is allocated to array can not be increased or reduced.
3. Since array is of fixed size, if we allocate more memory than requirement
then the memory space will be wasted. And if we allocate less memory than
requirement, then it will create problem.
4. The elements of array are stored in consecutive memory locations. So
insertions and deletions are very difficult and time consuming.
#include<stdio.h>
Page 58
int main()
{
int m[4][4]; //Declare 2 Dimensional Array
int i, j, sum = 0;
// Input Matrix
printf("Enter matrix order 4*4 \n");
for (i = 0; i < 4; i++)
{
printf("Enter elements of %d row \n", i);
for (j = 0; j < 4; j++)
{
scanf("%d", &m[i][j]);
}
}
// Compute Sum of main diagonal elements in sum1
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (i == j)
}
}
return 0;
}
10 MARKS:
Refer Q 5 ( 5 marks)
Q2. WAP to find the sum and number of positive & negative
numbers in an array.
# include <stdio.h>
# include <conio.h>
void main()
Page 59
int a[20], i, n, psum = 0, nsum = 0 ;
clrscr() ;
scanf("%d", &n) ;
scanf("%d", &a[i]) ;
if(a[i] > 0)
if(a[i] < 0)
getch() ;
Output
-10 30 50 -20 40
Page 60
Q3. WAP to sort N elements of an array using simple sort.
/*
C program to accept N numbers and arrange them in an ascending order
*/
#include <stdio.h>
void main()
{
int i, j, a, n, number[30];
Output:
Page 61
Q4. Define the following: a) Array b) Searching c) Sorting
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
return 0;
}
Page 62
Output
Refer Q9 ( 5 marks)
Page 63
Strings: In C programming, array of character are called strings. A string is
terminated by null character /0. e.g. hello. Like other variables strings also
must be declared & can be initialized. Strings must be declared using char
data type only.
There are numerous functions defined in "string.h" header file. Few commonly
used string handling functions are discussed below:
Method Description
strcat() It is used to concatenate(combine) two string
strlen() It is used to show length of a string
strrev() It is used to show reverse of a string
strcpy() Copies one string into another
strcmp() It is used to compare two string
Again, the token string is optional but, are used in almost every case. Let us
consider an example of macro definition with argument.
5 MARKS:
Page 64
Q1. Define string. Explain how to declare & initialize string
variables with an example.
Declaration of strings
char s[5];
Initialization of strings
char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};
#include <stdio.h>
#include <string.h>
int main ()
{
Page 65
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
return 0;
}
When the above code is compiled and executed, it produces the following
result
Q3. Explain how to read the string from the terminal & write a
string to the terminal with an example.
Functions gets() and puts() are two string functions to take string input from
user and display string respectively as mentioned in previous chapter.
#include<stdio.h>
int main(){
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Or
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}
Output
Page 66
Q4. Explain with an example the null terminated strings as Array
of Characters.
char c[5]={'a','b','c','d','\0'};
#include <stdio.h>
#include <string.h>
int main () {
/* reverse str2 */
strrev(str2);
printf("Reverse string 2 : %s\n", str2 );
return 0;
}
When the above code is compiled and executed, it produces the following
result
Output 1:
Page 67
String 2 : Hello
Reverse string 2: olleh
The given string is not a palindrome
Output 1:
String 2 : amma
Reverse string 2: amma
The given string is a palindrome
There are numerous functions defined in "string.h" header file. Few commonly
used string handling functions are discussed below:
Page 68
#include <stdio.h>
#include <string.h>
int main () {
char str1[12],str2[12];
printf("Enter string1 ");
scanf("%s",str1);
return 0;
}
When the above code is compiled and executed, it produces the following
result
Output1:
Enter string 1: hello
Enter string 2: hello
The given strings are same
Output2:
Enter string 1: hello
Enter string 2: hell
The given strings are not same
#define MAX_ARRAY_LENGTH 20
Page 69
The directive must be included after defining header files as shown below:
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
#include<filename>
Search File in Standard Library
#include"FILENAME"
Search File in Current Library
If not found , Search File in Standard Library
User defined header files are written in this format
Example :
#include<stdio.h> // Standard Header File
#include<conio.h> // Standard Header File
#include"myfunc.h" // User Defined Header File
Explanation:
Page 70
Q11. Explain with example the #include directive.
#include <stdio.h>
int main() {
return 0;
}
When the above code is compiled and executed, it produces the following
result
value of area : 50
One of the powerful functions of the CPP is the ability to simulate functions
using parameterized macros. For example, we might have some code to square
a number as follows
int square(int x)
{
return x * x;
}
Page 71
We can rewrite above the code using a macro as follows
Macros with arguments must be defined using the #define directive before
they can be used. The argument list is enclosed in parentheses and must
immediately follow the macro name. Spaces are not allowed between the
macro name and open parenthesis. For example
#include <stdio.h>
int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
When the above code is compiled and executed, it produces the following
result
10 MARKS:
Page 72
after strcmp(s1,s2); return < 0 value
Q3. WAP to verify that the given string is palindrome or not using
iterative method.
#include <stdio.h>
#include <conio.h>
void main() {
char *a;
int i,len,flag=0;
clrscr();
gets(a);
len=strlen(a);
for (i=0;i<len;i++) {
if(a[i]==a[len-i-1])
flag=flag+1;
Page 73
if(flag==len)
getch();
Result
ENTER A STRING:Ankit
THE STRING IS NOT PALINDROM
#include <stdio.h>
int main(void) {
printf("The area of a circle %f\n", AREA(10));
return 0;
}
OUTPUT:
OR
#include <stdio.h>
#define PI 3.1415
#define area(r) (PI*(r)*(r))
int main()
{
int radius;
float a;
printf("Enter the radius: ");
scanf("%d",&radius);
a=area(radius);
printf("Area=%.2f",a);
return 0;
}
Page 74
Output:
Enter the radius: 3
Area = 28.27
They look a lot like function calls, but they're not so simple. when it comes to
working with macros. First, remember that the exact text of the macro
argument is "pasted in" to the macro. For instance, if you wrote something
like this:
#define MULT(x, y) x * y
what value do you expect z to end up with? The obvious answer, 30, is wrong!
That's because what happens when the macro MULT expands is that it looks
like this:
int z = 3 + 2 * 4 + 2; // 2 * 4 will be evaluated first!
So z would end up with the value 13! This is almost certainly not what you
want to happen. The way to avoid it is to force the arguments themselves to be
evaluated before the rest of the macro body. You can do this by surrounding
them by parentheses in the macro definition:
Page 75
CHAPTER 6: STRUCTURES & UNION
A union is a special data type available in C that allows user to store different
data types in the same memory location.
5 MARKS:
Page 76
Q1. Define a structure. Explain with an example, the general syntax
of a structure.
Structure is a user-defined data type in C which allows user to combine
different data types to store a particular type of record. Structure helps to
construct a complex data type in more meaningful way.
Defining a structure
struct keyword is used to define a structure. struct define a new data type
which is a collection of different type of data.
Syntax :
struct structure_name
{
//Statements
};
Example of Structure
struct Book
{
char name[15];
int price;
int pages;
};
Here the struct Book declares a structure to hold the details of book which
consists of three data fields, namely name, price and pages. These fields are
called structure elements or members. Each member can have different
data type,like in this case, name is of char type and price is of int type etc.
Book is the name of the structure and is called structure tag.
struct Student
{
char[20] name;
int age;
int rollno;
};
Page 77
struct Student S1 , S2; //declaring variables of Student
struct Student
{
char[20] name;
int age;
int rollno;
} S1, S2 ;
Here S1 and S2 are variables of structure Student. However this approach is
not much recommended.
Structure Initialization
Like any other data type, structure variable can also be initialized at compile
time.
struct Patient
{
float height;
int weight;
int age;
};
or,
A union is a special data type available in C that allows user to store different
data types in the same memory location. You can define a union with many
members, but only one member can contain a value at any given time. Unions
provide an efficient way of using the same memory location for multiple-
purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you
did while defining a structure. The union statement defines a new data type
Page 78
with more than one member for your program. The format of the union
statement is as follows
The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the
end of the union's definition, before the final semicolon, you can specify one
or more union variables but it is optional. Here is the way you would define a
union type named Data having three members i, f, and str
union Data
{
int i;
float f;
char str[20];
} data;
The memory occupied by a union will be large enough to hold the largest
member of the union. For example, in the above example, Data type will
occupy 20 bytes of memory space because this is the maximum space which
can be occupied by a character string.
Page 79
keyword
Sl Array structure
no
1 An array is a collection of related . Structure can have elements of
data elements of same type. different types
2 Static memory allocation. Dynamic memory allocation.
3 It uses the subscript to access the It uses the dot(.)operator to access the
array elements .e.g. a[2] structure members. E.g. s.name
4 Memory (array size) is fixed Memory (structure size) can be
changed dynamically
5 An array is derived data type A structure is a
programmer defined one.
The above code define an array emp of size 5 elements. Each element of array
emp is of type employee
#include<stdio.h>
#include<conio.h>
struct employee
{
char ename[10];
int sal;
};
Page 80
printf("\nSlary is %d",emp[i].sal);
}
}
void main()
{
clrscr();
ask();
getch();
}
e.g. consider a program to read one student name & 3 test marks, then an
array marks[3] is included in side the structure as shown below. Then we can
access individual array element from structure using structure variable
#include <stdio.h>
struct student
{
char sname[20];
int marks[3]; //Note Carefully
}s1;
int main()
{
return 0;
}
Page 81
Output:
Enter the Name of Student : xyz
Enter the Marks in Subject 1 : 67
Enter the Marks in Subject 2 : 77
Enter the Marks in Subject 3 : 76
10 MARKS:
struct complex
{
int imag_value;
float real_value;
};
struct number{
struct complex c1;
int real;
}n1,n2;
#include <stdio.h>
struct date
{
int date;
int month;
int year;
};
struct Employee
{
char ename[20];
int ssn;
float salary;
Page 82
struct date doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
return 0;
}
Output :
Employee Name : Pritesh
Employee SSN : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990
#include<stdio.h>
#include<conio.h>
struct student
{
char sname[10];
int regno;
};
Page 83
void main()
{
clrscr();
ask();
getch();
}
Output
Q4. WAP to create structure with an employee details & display the
same.
#include<stdio.h>
#include<conio.h>
struct employee
{
char ename[10];
int sal;
}emp;
Void main()
{
Page 84
printf("\nEnter employee record\n",i+1);
printf("\nEmployee name\t");
scanf("%s",emp.ename);
printf("\nEnter employee salary\t");
scanf("%d",&emp.sal);
Output
Enter employee record
Employee name ddd
Enter employee salary 10000
Page 85