Programming in c

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 157

DHANALAKSHMI SRINIVASAN COLLEGE OF ARTS AND SCIENCE FOR WOMEN (AUTONOMOUS)

PERAMBALUR-621 212

DEPARTMENT OF COMPUTER APPLICATIONS

PROGRAMMING IN C

CLASS: I BCA

SUBMITTED BY

Mrs.P.ANITHA

ASSISTANT PROFESSOR

DEPARTMENT OF COMPUTER APPLICATIONS

PROGRAMMING IN C

UNIT – I

Overview of C

1
A brief history

C is a programming language developed at “AT & T’s Bell Laboratories” of USA in 1972. It was written
by Dennis Ritchie (Fig 2).

Fig 2. Dennis Ritchie

The programming language C was first given by Kernighan and Ritchie, in a classic book called “The C
Programming Language, 1st edition”. For several years the book “The C Programming Language, 1st edition”
was the standard on the C programming. In 1983 a committee was formed by the American National Standards
Institute (ANSI) to develop a modern definition for the programming language C . In 1988 they delivered the
final standard definition ANSI C.

Features of C

 Portability
 Modularity
 Extensible
 Speed
 Mid-level programming language
 Flexibility
 Rich Library

Advantages of C
1. C programming is the building block for many other high level programming languages existing today

2. A C program written in one computer can easily run on another computer without making any change

3. It has variety of data types and powerful operators

2
4. A C program is a collection of functions supported by the C library. So we can easily add our own
functions to C library. Hence we can extend any existing C program according to the need of our
applications

5. Since C is a structured language, we can split any big problem into several sub modules. Collection of
these modules makes up a complete program. This modular concept makes the testing and debugging
easier

Structure of a C program

Documentation Section:
 It consist of a set of comment lines
 The comment lines begins with /* and ends with */ or a single set of // in the beginning of the line
 These lines are not executable
 Comments are very helpful in identifying the program features

3
Preprocessor Section:
 It is used to link system library files, for defining the macros and for defining the conditional inclusion
 Eg: #include<stdio.h>, #include<conio.h>, #define MAX 100, etc.,

Global Declaration Section:


 The variables that are used in more than one function throughout the program are called global variables
 Should be declared outside of all the functions i.e., before main().

main():
Every ‘C’ program must have one main() function, which specifies the starting of a ‘C’ program. It
contains the following two parts

Declaration Part:
 This part is used to declare the entire variables that are used in the executable part of the program and
these are called local variables

Execution Part:
 It contains at least one valid C Statement.
 The Execution of a program begins with opening brace ’{‘ and ends with closing brace ’}’
 The closing brace of the main function is the logical end of the program

Sub Program section:


 Sub programs are basically functions are written by the user (user defined functions)
 They may be written before or after a main () function and called within main () function
 This is optional to the programmer

Constraints while writing a C program


 All statements in ‘C’ program should be written in lower case letters. Uppercase letters are only used for
symbolic constants
 Blank space may be inserted between the words. Should not be used while declaring a variable, keyword,
constant and function
 The program statements can be written anywhere between the two braces following the declaration part
 All the statements should end with a semicolon (;)

Example Program
/* addition.c – To find the average of two numbers and print them out together with their average */
#include <stdio.h>
void main( )
{
int first, second;
float avg;
printf("Enter two numbers: ");
scanf("%d %d", &first, &second);
printf("The two numbers are: %d, %d", first, second);
avg = (first + second)/2;
printf("Their average is %f", avg);
}

4
Compilation and Execution of C program
1. Creating the program
2. Compiling the Program
3. Linking the Program with system library
4. Executing the program

Creating the program:


 Type the program and edit it in standard ‘C’ editor and save the program with .c as an extension.
 This is the source program

Compiling (Alt + F9) the Program:


 This is the process of converting the high level language program to Machine level Language (Equivalent
machine instruction) -> Compiler does it!
 Errors will be reported if there is any, after the compilation
 Otherwise the program will be converted into an object file (.obj file) as a result of the compilation
 After error correction the program has to be compiled again

Linking the program with system Library:


 Before executing a c program, it has to be linked with the included header files and other system libraries
-> Done by the Linker

Executing the Program:


 This is the process of running (Ctrl + F9) and testing the program with sample data. If there are any run
time errors, then they will be reported

5
6
The above illustration provides a lucid description of how to compile and execute a C program.

C Tokens

C tokens, Identifiers and Keywords are the basic elements of a C program. C tokens are the basic
buildings blocks in C. Smallest individual units in a C program are the C tokens. C tokens are of six types. They
are,

1. Keywords (eg: int, while),


2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)

1. Keywords
Keywords are those words whose meaning is already defined by Compiler. They cannot be used as
Variable Names. There are 32 Keywords in C. C Keywords are also called as Reserved words. There are 32
keywords in C. They are given below:

7
2. Identifiers

Identifiers are the names given to various program elements such as variables , arrays & functions.
Basically identifiers are the sequences of alphabets or digits.

Rules for forming identifier name


The first character must be an alphabet (uppercase or lowercase) or an underscore.
All succeeding characters must be letters or digits.
No space and special symbols are allowed between the identifiers.
No two successive underscores are allowed.
Keywords shouldn’t be used as identifiers.
3. Constants

The constants refer to fixed values that the program may not change or modify during its execution.
Constants can be of any of the basic data types like an integer constant, a floating constant and a character
constant. There is also a special type of constant called enumeration constant.
(OR)
Constant is a any value that cannot be changed during program execution. In C, any number, single
character, or character string is known as a constant.

C constants can be divided into two major categories:

 Primary Constants
 Secondary Constants

These constants are further categorized as

8
 Numeric constant
 Character constant
 String constant

Numeric constant:
Numeric constant consists of digits. It required minimum size
of 2 bytes and max 4 bytes.
It may be positive or negative but by default sign is always positive. No comma or space is allowed
within the numeric constant and it must have at least 1 digit. The allowable range for integer constants is -32768
to 32767. Truly speaking the range of an Integer constant depends upon the compiler.
For a 16-bit compiler like Turbo C or Turbo C++ the range is –32768 to 32767.
For a 32-bit compiler the range would be even greater. Mean by a 16-bit or a 32- bit compiler, what
range of an Integer constant has to do with the type of compiler.

It is categorized a integer constant and real constant.

An integer constants are whole number which have no decimal point.


Types of integer constants are:
 Decimal constant: 0-------9(base 10)
 Octal constant: 0-------7(base 8)
 Hexa decimal constant: 0----9, A------F(base 16)
In decimal constant first digit should not be zero unlike octal constant first digit must be zero(as 076,
0127) and in hexadecimal constant first two digit should be 0x/ 0X (such as 0x24, 0x87A).
By default type of integer constant is integer but if the value of integer constant is exceeds range then
value represented by integer type is taken to be unsigned integer or long integer.
It can also be explicitly mention integer and unsigned integer type by suffix l/L and u/U.

Real constant is also called floating point constant. To construct real constant we
must follow the rule of ,
 real constant must have at least one digit.

9
 It must have a decimal point.
 It could be either positive or negative.
 Default sign is positive.
 No commas or blanks are allowed within a real constant.

Ex.: +325.34
426.0
-32.76

To express small/large real constant exponent(scientific) form is used where


number is written in mantissa and exponent form separated by e/E. Exponent can
be positive or negative integer but mantissa can be real/integer type, for example
3.6*105=3.6e+5. By default type of floating point constant is double, it can also be
explicitly defined it by suffix of f/F.

Character constant

Character constant represented as a single character enclosed within a single


quote. These can be single digit, single special symbol or white spaces such as
‘9’,’c’,’$’, ‘ ’ etc. Every character constant has a unique integer like value in
machine’s character code as if machine using ASCII (American standard code for
information interchange). Some numeric value associated with each upper and
lower case alphabets and decimal integers are as:
 A------------ Z ASCII value (65-90)
 a-------------z ASCII value (97-122)
 0-------------9 ASCII value (48-59)
 ; ASCII value (59)

String constant

Set of characters are called string and when sequence of characters are
enclosed within a double quote (it may be combination of all kind of symbols) is a
string constant.
String constant has zero, one or more than one character and at the
end of the string null character(\0) is automatically placed by compiler.
Some examples are “,sarathina” , “908”, “3”,” ”, “A” etc.
In C although same characters are enclosed within single and double quotes it represents different
meaning such as “A” and ‘A’ are different because first one is string attached with null character at the end but
second one is character constant with its corresponding ASCII value is 65.

Symbolic constant

Symbolic constant is a name that substitute for a sequence of characters and,


characters may be numeric, character or string constant.
These constant are generally defined at the beginning of the program as
#define name value , here name generally written in upper case for example

#define MAX 10
#define CH ‘b’

10
#define NAME “sony”

Eg:
Integer Constants- 45, 215u
Floating Constants- 3.14, 4513E-5L
Character Constants- \t, \n

4. Strings

A string in C is actually a one-dimensional array of characters which is terminated by a null character '\0'.
Eg:
char str = {‘S’, ’A’, ’T’, ’H’, ’Y’, ’A’, ’B’, ’A’, ’M’, ’A’}

5. Special Symbols

The symbols other than alphabets, digits and white spaces for example - [] () {} , ; : * … = # are the special
symbols.

6. Operators

An Operator is a symbol that specifies an operation to be performed on the operands. The data items that
operators act upon are called operands. Operators which require two operands are called Binary operators.
Operators which require one operand are called Unary Operators.

Types of Operators

Depending upon their operation they are classified as

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Sizeof() Operators

Variable:

 A variable is an identifier that is used to represent some specified type of information within a designated
portion of the program.

11
 A variable may take different values at different times during the execution
(Or)
 Variable is a data name which is used to store some data value or symbolic names for storing program
computations and results. The value of the variable can be change during the execution.

Rules for naming the variable

 A variable name can be any combination of 1 to 8 alphabets, digit, or underscore


 The first character must be an alphabet or an underscore (_ ).
 The length of variable should not exceed 8 characters length, and some of the ‘C’ compiler can be
recognize upto 31 characters.

Syntax:

Data-type variable-name;
Example:
int number;
float average;

Variable initialization

When we assign any initial value to variable during the declaration, is called initialization of variables.
When variable is declared but contain undefined value then it is called garbage value. The variable is initialized
with the assignment operator such as
Syntax:
Data type variable name=constant;

Example:

int a=20;
Or int a;
a=20;

statements

Assignment statement

A value can be stored in a variable with the use of assignment operator. The assignment operator(=) is used in
assignment statement and assignment expression. Operand on the left hand side should be variable and the
operand on the right hand side should be variable or constant or any expression. When variable on the left hand
side is occur on the right hand side then we can avoid by writing the
compound statement.

For example,

int x= y;
int Sum=x+y+z;

Data Types in C

12
C has a concept of 'data types' which are used to define a variable before its use. The definition of a
variable will assign storage for the variable and define the type of data that will be held in the location. The value
of a variable can be changed any time.

C has the following 4 types of data types

 basic built-in data types: int, float, double, char


 Enumeration data type: enum
 Derived data type: pointer, array, structure, union
 Void data type: void

C has the following basic built-in datatypes.

 int
 float
 double
 char

The bytes occupied by each of the primary data types are

Scope of a variable

A scope in any programming is a region of the program where a defined variable can have its existence and
beyond that variable cannot be accessed. There are three places where variables can be declared in C
programming language:

1. Inside a function or a block is called local variable,

2. Outside of all functions is called global variable.

3. In the definition of function parameters which is called formal parameters.

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. Local variables are not known to functions outside their own. Following
is the example using local variables. Here all the variables a, b and c are local to main() function.

13
#include <stdio.h>
main ()
{
/* local variable declaration */
int a, b, c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
}

Global Variables

Global variables are defined outside of a function, usually on top of the program. The global variables will hold
their value 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. Following is the example using global and local variables:

#include <stdio.h>
/* global variable declaration */
int g;
main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
}

Qualifier

There are two types of type qualifier in c

 Size qualifier: short, long


 Sign qualifier: signed, unsigned

14
When the qualifier unsigned is used the number is always positive, and when
signed is used number may be positive or negative.

If the sign qualifier is not mentioned, then by default sign qualifier is assumed. The range of values for
signed data types is less than that of unsigned data type.

Because in signed type, the left most bit is used to represent sign, while in unsigned type this bit is also
used to represent the value. The size and range of the different data types on a 16 bit machine is given below:

Type conversion in expressions.

Type conversion is the method of converting one type of data into another data type.

There are two types of type conversion.

1. Automatic type conversion


2. Type casting

Automatic type conversion

This type of conversion is done automatically. The resultant value of an expression depends upon
the operand which occupies more space, which means the result value converted into highest
data type.
The compiler converts all operands into the data type of the largest operand.
This type of type conversion is done implicitly,this method is called as implicit type conversion.

Eg.1

float a,b,c;
a=10,b=3;
c=a/b
output= > c= 3.3 {4 bytes(float) (All the variables are same datatype}

Eg.2

15
int a,b,c;
a=10,b=3;
c=a/b;
output= >c=3{2 bytes(int)}

Eg.3

int a;
float b,c;
a=10,b=3;
c=a/b;
output=> c=3.3 {4 bytes(float) highest datatype is float}

Type casting

This method is used,when user wants to change the type of the data.

General Format for type casting is

(datatype)operand

Eg.1

int x=10, y=3;


z=(float)x/y;(ie z=10.0/3;)
output=>z=3.3(float)

Eg:2

int x=10,y=3;
z=x/(float)y;(ie z=10/3.0;)
output=>3.3(float)

 The type of the x is not changed, only the type of the value can be changed
 Since the type of conversion is done explicitly, this type conversion is called as explicit type conversion

The following rules have to be followed while converting the expression from one type to another to avoid the
loss of information:

1. All integer types to be converted to float.


2. All float types to be converted to double.
3. All character types to be converted to integer

Input and Output statements

In ‘c’ language several functions are available for input/output operations. These
functions are collectively known as the standard I/O library.

16
1.Unformatted input /output statements

2. Formatted input /output statements

Unformatted Input /Output statements

These statements are used to input /output a single /group of characters from/to the input/output devices .Here the
user cannot specify the type of data that is going to be input/output.
The following are the Unformatted input /output statements available in ‘C’.

single character input-getchar( ) function:

A getchar( ) function reads only one character through the keyboard.

Syntax: char variable=getchar( );

Example:

char x;
x=getchar( );

single character output-putchar( ) function:

A putchar( ) function is used to display one character at a time on the standard output device.

Syntax: putchar(charvariable);

Example:

char x;
putchar(x);

Formatted input /output statements

The function which is used to give the value of variable through keyboard is called input function. The
function which is used to display or print the value on the screen is called output function.

Note : - In C language we use two built in functions, one is used for reading and another is used for displaying
the result on the screen. They are scanf() and printf() functions. They are stored in the header file named stdio.h.

17
General format for scanf( ) function

scanf(“control string”, &variable1, &variable2,……)

The control sting specifies the field format in which the data is to be entered.

%d –integer
%f – float
%c- char
%s – string
% ld – long integer
%u – Unsigned Integer

Example:

scanf(“%d”,&x) – reading an integer value, the value will be stored in x

scanf(“%d%f”,&x,&a) - reading a integer and a float value In the above scanf ( ) function , we don’t use any
format. This type of Input is called as the Unformatted Input function.

Output Function : To print the value on the screen or to store the value on the file, the output functions are used.
printf() is the function which is use to display the output on the screen.

The General format of the printf() function is

printf(“control string”,variable1,variable2,…..);

Example

printf(“%d”,x) – printing the integer value x.


printf(“%d%f”, x,a)- printing a integer and float value using a single printf function.

Formatted Output of Integer :Similar to formatted input , there is a formatted output also to have the output in
a format manner.

In this control string consists of three types of items.

 Characters that will be printed on the screen as they appear


 Format specification that define the output format for display of each item
 Escape sequence characters such as

\n – new line
\b – back space
\f – form feed
\r – carriage return
\t - horizontal tab
\v – vertical tab

18
The format speciation is as follows

%wd

Where w – is the field width of the number to be write . d will indicates as data type in integer number.

Examples:

Printf(“%d”,9876); // output: 9876


printf(“%6d”,9876);

output:

printf(“%-6d”,9876);

output:

printf(“%06”,9876);

output:

Formatted input of Real(float) Numbers:

. The field speciation for reading the real number is:

%w.pf
Where w – is the field width of the number to be read . p indicates the number of digits to be read after
the decimal point f – indicates that data type in float(real) number.

Formatted output of Real(float) Numbers:

The field speciation for reading the real number is:

%w.pf

Where w – is the field width of the number to be read . p indicates the number of digits to be displayed
after the decimal point f – indicates that data type in float(real) number.

Example:

19
Float y = 98.7682
Printf(“ %f ”, y); // output: 98.7682
printf(“%7.2f ”,y);

output:

printf(“%-7.2f ”,y);

output:

Formatted input of Single characters or strings:

The field speciation for reading the character strings:

%ws or %wc

where,
%c is used to read a single character.

Example:

Char name;
Scanf(“%c”, &name); \\ I / P : a
Char name[20];
Scanf(%s”,&name); \\ I / P : sathyabama

Printing of a Single Character:

The field speciation for reading the character strings:


%ws or %wc
where,
%s – A sequence of characters can be displayed.
%c – A single character can be displayed.

The character will be displayed right-justified in the field of w, left-justified by placing a minus sign
before the integer w.

20
Example:

Char x = ‘a’;
Char name[20] = “anil kumar gupta”;
Printf(“%c”, x); // output: a
Printf(“%s”,name); // output: anil kumar gupta
Printf(“%20s”, name);

Output:

Printf(“%-20.10s”, name);

Output:

Printf(“%.5s”, name);

Output:

UNIT – II

PRECEDENCE AND ASSOCIATIVELY OF OPERATORS

If an arithmetic expression is given, there are some rules to be followed to evaluate the value of it. These rules are
called as the priority rules. They are also called as the hierarchy rules. According to these rules, the expression is
evaluated as follows;

21
Rule 1 :- If an expression contains parentheses , the expression within the parentheses will be performed first.
Within the parentheses , the priority is to be followed.

Rule 2 :- If it has more than parentheses , the inner parenthesis is performed first.

Rule 3:- If more than one symbols of same priority , it will be executed from left to right.

C operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of
equal precedence in an expression are applied

22
Example for evaluating an expression

Let X = 2 , Y =5 then the value of the expression


((( Y - 1 ) / X ) * ( X + Y ) ) is calculated as:-
( Y - 1) = ( 5 - 1 ) = 4 = T1
( T 1 / X ) = ( 4 / 2 ) = 2 = T2
( X + Y ) = ( 2 + 5 ) = 7 = T3
( T2 * T3 ) = ( 2 * 7 ) = 14
The evaluations are made according to the priority rule.

Operators

An Operator is a symbol that specifies an operation to be performed on the operands. The data items that
operators act upon are called operands. Operators which require two operands are called Binary operators.
Operators which require one operand are called Unary Operators.

Types of Operators

Depending upon their operation they are classified as

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Sizeof() Operators

Arithmetic Operators

Arithmetic Operators are used to perform mathematical calculations like addition, subtraction, multiplication,
division and modulus.

23
Rules For Arithmetic Operators

1. C allows only one variable on left hand side of = eg. c=a*b is legal, but a*b=c is not legal.
2. Arithmetic operations are performed on the ASCII values of the characters and not on characters themselves
3. Operators must be explicitly written.
4. Operation between same type of data yields same type of data, but operation between integer and float yields a
float result.

Example Program
#include <stdio.h>
int main()
{
int m=40,n=20, add,sub,mul,div,mod;
add = m+n;
sub = m-n;
mul = m*n;
div = m/n;
mod = m%n;
printf(“Addition of m, n is : %d\n”, add);
printf(“Subtraction of m, n is : %d\n”, sub);
printf(“Multiplication of m, n is : %d\n”, mul);
printf(“Division of m, n is : %d\n”, div);
printf(“Modulus of m, n is : %d\n”, mod);
}

Output

Addition of m, n is : 60
Subtraction of m, n is : 20
Multiplication of m, n is : 800
Division of m, n is : 2
Modulus of m, n is : 0

Relational Operators

24
Relational Operators are used to compare two or more operands. Operands may be variables, constants or
expression

Example Program
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf(“m and n are equal”);
}
else
{
printf(“m and n are not equal”);
}
}

Output

m and n are not equal

Logical Operators

Logical Operators are used to combine the results of two or more conditions. It is also used to test more
than one condition and make decision.

25
Example Program
#include <stdio.h>
int main()
{
int a=40,b=20,c=30;
if ((a>b )&& (a >c))
{
printf(“ a is greater than b and c”);
}
else
if(b>c)
printf(“b is greater than a and c”);
else
prinf(“c is greater than a and b”);
}

Output

a is greater than b and c.

Conditional Operator
It itself checks the condition and executed the statement depending on the condition.

Syntax:
Condition? Exp1:Exp2

26
Example:

X=(a>b)?a:b

The ‘?:’ operator acts as ternary operator. It first evaluate the condition, if it is true then exp1 is
evaluated, if condition is false then exp2 is evaluated. The drawback of Assignment operator is that after the ?
or : only one statement can occur.

Example Program

#include <stdio.h>
int main()
{
int x,a=5,b=3;
x = (a>b) ? a : b ;
printf(“x value is %d\n”, x);
}

Output

x value is 5

Bitwise Operators

Bitwise Operators are used for manipulation of data at bit level. It operates on integer only.

Example Program
#include <stdio.h>
main()
{
int c1=1,c2;
c2=c1<<2;
printf(“Left shift by 2 bits c1<<2=%d”,c2);
}

27
Output

Left shift by 2 bits c1<<2=4

Special operators:

sizeof () operator:

1. Sizeof operator is used to calcualte the size of data type or variables.


2. Sizeof operator will return the size in integer format.
3. Sizeof operator syntax looks more like a function but it is considered as an operator in c programming

Example of Size of Variables

#include<stdio.h>
int main()
{
int ivar = 100;
char cvar = 'a';
float fvar = 10.10;
printf("%d", sizeof(ivar));
printf("%d", sizeof(cvar));
printf("%d", sizeof(fvar));
return 0;
}

Output :

214

In the above example we have passed a variable to size of operator. It will print the value of variable
using sizeof() operator.

Example of Sizeof Data Type

#include<stdio.h>
int main()
{
printf("%d", sizeof(int));
printf("%d", sizeof(char));
printf("%d", sizeof(float));
return 0;
}

Output :

214

28
In this case we have directly passed an data type to an sizeof.

Example of Size of constant

#include<stdio.h>
int main()
{
printf("%d", sizeof(10));
printf("%d", sizeof('A'));
printf("%d", sizeof(10.10));
return 0;
}

Output :

214

In this example we have passed the constant value to a sizeof operator. In this case sizeof will print the size
required by variable used to store the passed value.

Example of Nested sizeof operator

#include<stdio.h>
int main()
{
int num = 10;
printf("%d", sizeof(sizeof(num)));
return 0;
}

Output:

We can use nested sizeof in c programming. Inner sizeof will be executed in normal fashion and the result of
inner sizeof will be passed as input to outer sizeof operator.
Innermost Sizeof operator will evaluate size of Variable “num” i.e 2 bytes Outer Sizeof will evaluate Size of
constant “2” .i.e 2 bytes

Comma(,) Operator:

1. Comma Operator has Lowest Precedence i.e it is having lowest priority so it is evaluated at last.
2. Comma operator returns the value of the rightmost operand when multiple comma operators are used inside an
expression.
3. Comma Operator Can acts as –
 Operator : In the Expression
 Separator: Function calls, Function definitions, Variable declarations and Enum declarations

29
Example:

#include<stdio.h>
void main()
{

int num1 = 1, num2 = 2;


int res;
res = (num1, num2);
printf("%d", res);
}

Output

Consider above example


int num1 = 1, num2 = 2;// In variable Declaration as separator
res = (num1, num2);// In the Expression as operator

In this case value of rightmost operator will be assigned to the variable. In this case value of num2 will
be assigned to variable res.

Examples of comma operator:

Type 1 : Using Comma Operator along with Assignment

#include<stdio.h>
int main()
{
int i;
i = 1,2,3;
printf("i:%d\n",i);
return 0;
}

Output:

i:1

Explanation:
i = 1,2,3;
1. Above Expression contain 3 comma operator and 1 assignment operator.
2. If we check precedence table then we can say that “Comma” operator has lowest precedence than assignment
operator
3. So Assignment statement will be executed first .

30
4. 1 is assigned to variable “i”.

Type 2 : Using Comma Operator with Round Braces

#include<stdio.h>
int main()
{
int i;
i = (1,2,3);
printf("i:%d\n",i);
return 0;
}

Output:

i:3

Explanation:

i = (1,2,3);
1. Bracket has highest priority than any operator.
2. Inside bracket we have 2 comma operators.
3. Comma operator has associativity from Left to Right.
4. Comma Operator will return rightmost operand
i = (1,2,3) Assign 3 to variable i.

Type 3 : Using Comma Operator inside printf statement

#include<stdio.h>
#include< conio.h>
void main()
{
clrscr();
printf("Computer","Programming");
getch();
}

Output:

Computer
You might feel that answer of this statement should be “Programming” because comma operator always
returns rightmost operator, in case of printf statement once comma is read then it will consider preceding things
as variable or values for format specifier.

Type 4 : Using Comma Operator inside Switch cases.

#include<stdio.h>
#include< conio.h>

31
void main()
{
int choice = 2 ;
switch(choice)
{
case 1,2,1:
printf("\nAllas");
break;
case 1,3,2:
printf("\nBabo");
break;
case 4,5,3:
printf("\nHurray");
break;
}
}

Output :

Babo

Type 5 : Using Comma Operator inside For Loop

#include<stdio.h>
int main()
{
int i,j;
for(i=0,j=0;i<5;i++)
{
printf("\nValue of J : %d",j);
j++;
}
return(0);
}

Output:

Value of J : 0
Value of J : 1
Value of J : 2
Value of J : 3
Value of J : 4

Type 6 : Using Comma Operator for multiple Declaration

#include<stdio.h>
int main()
{

32
int num1,num2;
int a=10,b=20;
return(0);
}
Note : Use of comma operator for multiple declaration in same statement.

Expressions

An expression is a combination of variables, constants, operators and function call. It can be arithmetic,
logical and relational for example:-
int z= x+y // arithmatic expression
a>b //relational
a==b // logical
func(a, b) // function call
Expressions consisting entirely of constant values are called constant expressions.
So, the expression
121 + 17 - 110
is a constant expression because each of the terms of the expression is a constant
value. But if i were declared to be an integer variable, the expression
180 + 2 – j
would not represent a constant expression

Input and Output statements

In ‘c’ language several functions are available for input/output operations. These
functions are collectively known as the standard I/O library.

1.Unformatted input /output statements

2. Formatted input /output statements

Unformatted Input /Output statements

These statements are used to input /output a single /group of characters from/to the input/output devices .Here the
user cannot specify the type of data that is going to be input/output.
The following are the Unformatted input /output statements available in ‘C’.

single character input-getchar( ) function:

33
A getchar( ) function reads only one character through the keyboard.

Syntax: char variable=getchar( );

Example:

char x;
x=getchar( );

single character output-putchar( ) function:

A putchar( ) function is used to display one character at a time on the standard output device.

Syntax: putchar(charvariable);

Example:

char x;
putchar(x);

the getc( ) function

This is used to accept a single character from the standard input to a character variable.

Syntax: character variable=getc( );

Example:

char c;
c=getc( );

the putc( ) function

This is used to display a single character variable to standard output device.

Syntax: putc(character variable);

Example:
char c;
putc(c );
the gets( ) and puts( ) function

The gets( ) function is used to read the string from the standard input device.

Syntax: gets(string variable);

Example:

gets( s);

The puts( ) function is used to display the string to the standard output device
.
Syntax: puts(string variable);

34
Example:

puts( s);

Proram using gets and puts function

#include<stdio.h>
main()
{
char scientist[40];
puts("Enter Name");
gets(scientist);
puts("Print the Name");
puts(scientist);
}

output:

Enter Name:Abdul Kalam


Print the Name:Abdul Kalam

Formatted input /output statements

The function which is used to give the value of variable through keyboard is called input function. The
function which is used to display or print the value on the screen is called output function.

Note : - In C language we use two built in functions, one is used for reading and another is used for displaying
the result on the screen. They are scanf() and printf() functions. They are stored in the header file named stdio.h.

General format for scanf( ) function

scanf(“control string”, &variable1, &variable2,……)

The control sting specifies the field format in which the data is to be entered.

%d –integer
%f – float
%c- char
%s – string
% ld – long integer
%u – Unsigned Integer

Example:

scanf(“%d”,&x) – reading an integer value, the value will be stored in x

scanf(“%d%f”,&x,&a) - reading a integer and a float value In the above scanf ( ) function , we don’t use any
format. This type of Input is called as the Unformatted Input function.

35
Formatted Input of Integer

The field speciation for reading the integer number is:


%wd
Where The percentage sign(%) indicates that a conversion specification follows. w – is the field width of
the number to be read. d will indicates as data type in integer number.

Example:

scanf(“%2d %5d”, &num1,&num2);


data line is 50 31425
the value 50 is assigned to num1 and 31425 is assigned to num2. suppose the input data is as follows
31425 50 , then the variable num1 will be assigned 31 and num2 will be assigned to 425 and the 50 is unread.
An input field may be skipped by specifying * in the place of field width.

Example the statement scanf(“%d %*d %d),&a,&b); will assign the data 123 456 789
as follows: 123 is assigned to a , 456 skipped because of * and 789 to b

Output Function : To print the value on the screen or to store the value on the file, the output functions are used.
printf() is the function which is use to display the output on the screen.
The General format of the printf() function is

printf(“control string”,variable1,variable2,…..);

Example

printf(“%d”,x) – printing the integer value x.


printf(“%d%f”, x,a)- printing a integer and float value using a single printf function.
Formatted Output of Integer :Similar to formatted input , there is a formatted output also to have the output in
a format manner.

In this control string consists of three types of items.

 Characters that will be printed on the screen as they appear


 Format specification that define the output format for display of each item
 Escape sequence characters such as

\n – new line
\b – back space
\f – form feed
\r – carriage return
\t - horizontal tab
\v – vertical tab

The format speciation is as follows

%wd

36
Where w – is the field width of the number to be write . d will indicates as data type in integer number.

Examples:

Printf(“%d”,9876); // output: 9876


printf(“%6d”,9876);

output:

printf(“%-6d”,9876);

output:

printf(“%06”,9876);

output:

Formatted input of Real(float) Numbers:

. The field speciation for reading the real number is:

%w.pf
Where w – is the field width of the number to be read . p indicates the number of digits to be read after
the decimal point f – indicates that data type in float(real) number.

Example

scanf(“%2.1f %5.2f”,&num1,&num2);
data line is 50.1 31425.20
the value 50.1 is assigned to num1 and 31425.20 is assigned to num2.
An input field may be skipped by specifying * in the place of field width.
Example: the statement scanf(“%f %*f %f), &a,&b); will assign the data 12.3 4.56 78.9
as follows: 12.3 is assigned to a , 4.56 skipped because of * and 78.9 to b.

Formatted output of Real(float) Numbers:

The field speciation for reading the real number is:

37
%w.pf

Where w – is the field width of the number to be read . p indicates the number of digits to be displayed
after the decimal point f – indicates that data type in float(real) number.

Example:

Float y = 98.7682
Printf(“ %f ”, y); // output: 98.7682
printf(“%7.2f ”,y);

output:

printf(“%-7.2f ”,y);

output:

Formatted input of Single characters or strings:

The field speciation for reading the character strings:

%ws or %wc

where,
%c is used to read a single character.

Example:

Char name;
Scanf(“%c”, &name); \\ I / P : a
Char name[20];
Scanf(%s”,&name); \\ I / P : sathyabama

Printing of a Single Character:

The field speciation for reading the character strings:


%ws or %wc
where,
%s – A sequence of characters can be displayed.
%c – A single character can be displayed.

38
The character will be displayed right-justified in the field of w, left-justified by placing a minus sign
before the integer w.

Example:

Char x = ‘a’;
Char name[20] = “anil kumar gupta”;
Printf(“%c”, x); // output: a
Printf(“%s”,name); // output: anil kumar gupta
Printf(“%20s”, name);

Output:

Printf(“%-20.10s”, name);

Output:

Printf(“%.5s”, name);

Output:

LIBRARY FUNCTIONS
Definition
C Library functions are inbuilt functions in C language which are clustered in a group and stored in a
common place called Library. Each and every library functions in C executes explicit functions. In order to get
the pre- defined output instead of writing our own code, these library functions will be used. Header file consists
of these library functions like Function prototype and data definitions.

 Every input and output operations (e.g., writing to the terminal) and all mathematical operations (e.g.,
evaluation of sines and cosines) are put into operation by library functions.
 The C library functions are declared in header files (.h) and it is represented as [file_name].h
 The Syntax of using C library functions in the header file is declared as “#include<file_name.h>”. Using
this syntax we can make use of those library functions.

39
 #include<filename.h>” command defines that in C program all the codes are included in the header files
followed by execution using compiler.
 It is required to call the suitable header file at the beginning of the program in terminal in order to use a
library function. A header file is called by means of the pre-processor statement given below,

#include<filename.h>

Whereas the filename represents the header file name and #include is a pre- processor directive.

To access a library function the function name must be denoted, followed by a list of arguments, which
denotes the information being passed to the function.

Example

In case if you want to make use of printf() function, the header file <stdio.h> should be included at the
beginning of the C program.

#include <stdio.h>
int main()
{
/* NOTE: Error occurs if printf() statement is written without using the header file */
printf(" Hello World");
}

The „main() function‟ is also a library function which is called at the initial of the program.

Example

To find the square root of a number we use our own part of code to find them but this may not be most
efficient process which is time consuming too. Hence in C programming by declaring the square root function
sqrt() under the library function “math.h” will be used to find them rapidly and less time consuming too. Square
root program using the library functions is given below:

Finding Square root Using Library Function

#include <stdio.h>
#include <math.h>
int main()
{
float num,root;
printf("Enter a number to find square root."); scanf("%f",&num);
root=sqrt(num); /* Computes the square root of num and stores in root. */
printf("Square root of %.2f=%.2f",num,root);
return 0;
}

List of Standard Library Functions in C Programming

40
Adding User Defined functions in C library:

 In C Programming we can declare our own functions in C library which is called as user-defined
functions.
 It is possible to include, remove, change and access our own user defined function to or from C library
functions.
 Once the defined function is added to the library it is merely available for all C programs which are more
beneficial of including user defined function in C library function
 Once it is declared it can be used anywhere in the C program just like using other C library functions.
 By using these library functions in GCC compilers (latest version), compilation time can be consumed
since these functions are accessible in C library in the compiled form.
 Commonly the header files in C program are saved as ”file_name.h” in which all librar
functions are obtainable. These header files include source code and this source code is
further added in main C program file where we include this header file via “#include
<file_name.h>” command.

Steps for adding user defined functions in C library:

Step 1:

For instance, hereby given below is a test function that is going to be included in the C library function.
Write and save the below function in a file as “addition.c”

addition(int a, int b)
{
int sum;
total =a + b; return sum;
}

Step 2:

Compile “addition.c” file by using Alt + F9 keys (in turbo C).

step 3:

A compiled form of “addition.c” file would be created as “addition.obj”.

41
Step 4:

To add this function to library, use the command given below (in turbo C). c:\> tlib math.lib + c:\
addition.obj

+ represents including c:\addition.obj file in the math library. We can delete this file using –
(minus).

Step 5:

Create a file “addition.h” and declare sample of addition() function like below. int addition (int a,
int b);
Now “addition.h” file has the prototype of function “addition”.

Note : Since directory name changes for each and every IDE, Kindly create, compile and add
files in the particular directory.

Step 6:

Here is an example to see how to use our newly added library function in a C program.

# include <stdio.h>
// User defined function is included here.

# include “c:\\addition.h”

int main ( )
{

42
int total;
// calling function from library total = addition (10, 20);
printf ("Total = %d \n", total);
}
Output:
Total = 30

 Source code checking for all header files can be checked inside “include” directory following C compiler
that is installed in system.
 For instance, if you install DevC++ compiler in C directory in our system, “C:\Dev-Cpp\include” is the
path where all header files will be readily available.

Mostly used header files in C:

C library functions and header files in which they are declared in conio.h is listed below:

C – conio.h library functions

The entire C programming inbuilt functions that are declared in conio.h header file are given below. The source
code for conio.h header file is also given below for your reference.
List of inbuilt conio.h file C functions:

43
C – stdio.h library functions

Inbuilt functions of C declared in stdio.h header file are given below.

44
UNIT – III
DECISION STATEMENT AND ARRAYS

CONTROL STRUCTURES

CONDITIONAL STATEMENT
Decision Making Statement
If Statement:
 The if statement is a decision making statement.
 It is used to control the flow of execution of the statement and also used to the logically whether the
condition is true or false
 It is always used in conjunction with condition.

45
Syntax:

If(condition)
{
True statements;
}

 If the condition is true, then the true statements are executed.


 If the condition is false then the true statements are not executed, instead the program skips past them.
 The condition is given by relational operators like ==,<=,>=,!=,etc.

Example 1: //program to check whether the entered number is less than 25

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf(“Enter one value”);
scanf(“%d”,&i);
if(i<=25)
printf(“The entered no %d is < 25”,i);
getch();
}
Output:
Enter one value 5
The entered no 5 is < 25

if.. else statement:

 It is basically two way decision making statement and always used in conjunction with condition.

46
 It is used to control the flow of expression and also used to carry the logical test and then pickup one of
the two possible actions depending on the logical test.
 If the condition is true, then the true statements are executed otherwise false statements are executed.
 The true and false statements may be single or group of statements.

Syntax:

If (condition)
True statements;
else
False statements;

Example 1: //program to find the greatest of two number.

#include<stdio.h>
#include<conio.h> void main()
{
int a,b;
printf(“Enter two value”); scanf(“%d%d”,&a,&b);
if(a>b)
printf(“The given no %d is greatest”,a);
else
printf(“The given no %d is greatest”,b);
}

Output:

Enter two value 5 10


The given no 10 is greatest

47
Nested if..else Statement:

When a series of if_else statements are needed in a program, we can write an entire if_else statement
inside another if and it can be further nested. This is called nesting if.

Syntax:

if(condition 1)
{
if(condition 2)
{
True statement 2;
else
False statement 2;
}
else
False statement 1;
}
Example 1: //program to find the greatest of three numbers.

#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */
if( a == 100 )
{
/* if condition is true then check the following */
if( b == 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}

Output:

Value of a is 100 and b is 200


Exact value of a is : 100
Exact value of b is : 200
48
Else if Ladder:

 Nested if statements will become complex, if several conditions have to be checked.


 In such situations we can use the else if ladder .

Syntax:

if(condition 1)
{
True ststement 1;
}
else if(condition 2)
{
True statement 2;
}
else if(condition 3)
{
True statement 3;
else
Default statement;
}

Switch Statement

 The switch statement is used to execute a particular group of statements from several available groups of
statements.
 It allows us to make a decision from the number of choices.
 It is a multi-way decision statement.

Rules for writing switch () statement.

 The expression in switch statement must be an integer value or a character constant.


 No real numbers are used in an expression.
 Each case block and default block must be terminated with break statement.
 The default is optional and can be placed anywhere, but usually placed at end.
 The ‘case’ keyword must terminate with colon(:).
 Cases should not be identical.
 The values of switch expression is compared with the case constant expression in the order specified i.e.,
from top to bottom.

Syntax:

switch(expression)

49
{
case 1: state ment; break;
case 2: state ment; break;
default: statement;
break;
}

// program to print the give number is odd / even using switch case statement.

#include<stdio.h>
#include<conio.h> void main()
{
int a,b,c;
printf(“Enter one value”); scanf(“%d”,&a);
switch(a%2)
{
case 0:
printf(“The given no %d is even”, a);
break;
default :
printf(“The given no %d is odd”, a);
break;
}
}

50
Output:

Enter one value 5


The given no 5 is odd

Unconditional statement

Break statement

 The break statement is used to terminate the loop.


 When the keyword break is used inside any loop, control automatically transferred to the first statement after
the loop.

Syntax:

break;

//program to print the number upto 5 using break statement

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==6)
break;
printf(“%d”,i); }
}

Output:

1 2 3 4 5

51
Continue Statement

 In some situation, we want to take the control to the beginning of the loop, bypassing the statement
inside the loop which have not been executed, for this purpose the continue is used.
 When the statement continue is encountered inside any loop, control automatically passes to the
beginning of the loop.

Syntax:

continue;
While(condition)
{
……..
if(condition)
continue;
……….
}

Difference between break and continue

52
Goto Statement:

 C provides the goto statement to transfer control unconditionally from one place to another place in the
program.
 A goto statement can change the program control to almost anywhere in the program unconditionally.
 The goto statement require a label to identify the place to move the execution.
 The label is a valid variable name and must be ended with colon(:).

Syntax:

/* program to print the given both number is equal or not*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(“Enter the numbers”);
scanf(“%d%d”,&a,&b);
if(a==b)
goto equal;
} else
{
printf(“%d and %d are not equal”,a,b);
exit(0);
Output:
}
equal: printf(“%d and %d are equal”,a,b);

53
LOOPING STATEMENTS

A loop statement allows us to execute certain block of code repeatedly until test condition is false.

There are 3 types of loops in C programming:

1. for loop
2. while loop
3. do...while loop

for loop:

The syntax for a for loop is

for ( variable initialization; condition; variable update )


{
Code to execute while the condition is true
}
The initialization statement is executed only once at the beginning of the for loop. Then the test expression is
checked by the program. If the test expression is false, for loop is terminated. But if test expression is true then
the code/s inside body of for loop is executed and then update expression is updated. This process repeats until
test expression is false.

for loop example


54
Write a program to find the sum of first n natural numbers where n is entered by user. Note: 1,2,3... are
called natural numbers.
#include <stdio.h>
void 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 */
}
printf("Sum=%d",sum);
}
Output
Enter the value of n. 19
Sum=190
In this program, the user is asked to enter the value of n. Suppose you entered 19 then, count is initialized to 1 at
first. Then, the test expression in the for loop,i.e., (count<= n) becomes true. So, the code in the body of for loop
is executed which makes sum to 1. Then, the expression ++count is executed and again the test expression is
checked, which becomes true. Again, the body of for loop is executed which makes sum to 3 and this process
continues. When count is 20, the test condition becomes false and the for loop is terminated.
/* C program to check whether a number is prime or not. */
#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;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
Output
Enter a positive integer: 29 29 is a prime number.

This program takes a positive integer from user and stores it in variable n. Then, for loop is executed
which checks whether the number entered by user is perfectly divisible by i or not starting with initial value of i
equals to 2 and increasing the value of i in each iteration. If the number entered by user is perfectly divisible by i
then, flag is set to 1 and that number will not be a prime number but, if the number is not perfectly divisible by i
until test condition i<=n/2 is true means, it is only divisible by 1 and that number itself and that number is a
prime number.
55
While Loop
while loop repeatedly executes a target statement as long as a given condition is true.
Initialization;
while(condition)
{
----------
---------
----------
------
Increment/decrement;
}

For Single Line of Code – Opening and Closing braces are not needed. while(1) is used for Infinite Loop
 Initialization, Increment/Decrement and Condition steps are on different Line.
 While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and then only code is
executed ]
C Program to Find Number of Digits in a Number
#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
n/=10; /* n=n/10 */
++count;
}
printf("Number of digits: %d",count);
}
Output:
Enter an integer: 34523 Number of digits: 5

56
Types of infinite while loop
Semicolon at the end of while loop
#include<stdio.h> void main()
{
int num=300;
while(num>255); //Note it Carefully printf("Hello");
}
Output :
Will not print anything

1. In the above program , Condition is specified in the While Loop


2. Semicolon at the end of while indicated while without body.

3. In the program variable num doesn‟t get incremented , condition remains true forever.

4. As Above program does not have Loop body , It won‟t print anything

DO..WHILE

DO..WHILE loops executes the body of the loop atleast once.


The structure is
initialization; do
{
--------------
--------------
incrementation;
}while(condition);
The condition is tested at the end of the block instead of the beginning, so the block will be executed at least
once. If the condition is true, it go back to the beginning of the block and execute it again. A do..while loop is
almost same as a while loop except that the loop body is guaranteed to execute at least once.
 It is Exit Controlled Loop.
 Initialization , Incrementation and Condition steps are on different Line.
 It is also called Bottom Tested.
 Semicolon must be added after the while

57
Using Do-While Loop
#include<stdio.h>
void main() { int i = 1;
do {
printf("%d", i); i++;
} while (i <= 5);
}

Output
1
2
3
4
5

ARRAYS

Introduction:

So far we have used only single variable name for storing one data item. If we need to store multiple
copies of the same data then it is very difficult for the user. To overcome the difficulty a new data
structure is used called arrays.

An array is a linear and homogeneous data structure

An array permits homogeneous data. It means that similar types of elements are stored contiguously
in the memory under one variable name.

An array can be declared of any standard or custom data type.

Example of an Array:

Suppose we have to store the roll numbers of the 100 students the we have to declare 100 variables named
as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C programming arrays is
introduced in C which gives the capability to store the 100 roll numbers in the contiguous memory which
has 100 blocks and which can be accessed by single variable name.

1. C Programming Arrays is the Collection of Elements


2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Programming Arrays

58
The above array is declared as int a [5];

a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1;

In the above figure 4, 5, 33, 13, 1 are actual data items. 0, 1, 2, 3, 4 are index variables.

Index or Subscript Variable:

1. Individual data items can be accessed by the name of the array and an integer enclosed in square
bracket called subscript variable / index

2. Subscript Variables helps us to identify the item number to be accessed in the contiguous memory.
What is Contiguous Memory?

1. When Big Block of memory is reserved or allocated then that memory block is called as
Contiguous Memory Block.
2. Alternate meaning of Contiguous Memory is continuous memory.
3. Suppose inside memory we have reserved 1000-1200 memory addresses for special purposes then
we can say that these 200 blocks are going to reserve contiguous memory.
Contiguous Memory Allocation

1. Two registers are used while implementing the contiguous memory scheme. These registers are
base register and limit register.
2. When OS is executing a process inside the main memory then content of each register are as

Register Content of register

Base register Starting address of the memory location where process


execution is happening

Limit register Total amount of memory in bytes consumed by process

Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non - contiguous
allocation of memory.

3. When process try to refer a part of the memory then it will firstly refer the base address from base
register and then it will refer relative address of memory location with respect to base address.

59
How to allocate contiguous memory?

1. Using static array declaration.


2. Using alloc ( ) / malloc ( ) function to allocate big chunk of memory dynamically.
Array Terminologies:

Size: Number of elements or capacity to store elements in an array. It is always mentioned in square
brackets [ ].

Type: Refers to data type. It decides which type of element is stored in the array. It is also instructing the
compiler to reserve memory according to the data type.

Base: The address of the first element is a base address. The array name itself stores address of the first
element.

Index: The array name is used to refer to the array element. For example num[x], num is array and x is
index. The value of x begins from 0.The index value is always an integer value.

Range: Value of index of an array varies from lower bound to upper bound. For example in num[100] the
range of index is 0 to 99.

Word: It indicates the space required for an element. In each memory location, computer can

store a data piece. The space occupation varies from machine to machine. If the size of element is more
than word (one byte) then it occupies two successive memory locations. The variables of data type int,
float, long need more than one byte in memory.

Characteristics of an array:

1. The declaration int a [5] is nothing but creation of five variables of integer types in memory
instead of declaring five variables for five values.
2. All the elements of an array share the same name and they are distinguished from one another
with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the other
elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or array
variable of its type.
6. Array elements are stored in contiguous memory locations.
Array Declaration:

60
Array has to be declared before using it in C Program. Array is nothing but the collection of elements of
similar data types.

Syntax:

<data type> array name [size1][size2].....[sizen];

Syntax Parameter Significance

Data type Data Type of Each Element of the array

Array name Valid variable name


Array declaration requirements

Requirement Explanation
Data Type specifies the type of the array. We can compute the size
Data Type required for storing the single cell of array.

Valid identifier is any valid variable or name given to the array. Using this
Valid Identifier identifier name array can be accessed.

Size of Array It is maximum size that array can have.

What does Array Declaration tell to Compiler?

1. Type of the Array


2. Name of the Array
3. Number of Dimension
4. Number of Elements in Each Dimension

Types of Array

1. Single Dimensional Array / One Dimensional Array


2. Multi Dimensional Array

Single / One Dimensional Array:

1. Single or One Dimensional array is used to represent and store data in a linear form.
2. Array having only one subscript variable is called One-Dimensional array

61
3. It is also called as Single Dimensional Array or Linear Array
Single Dimensional Array Declaration and initialization:
Syntax for declaration: <data type> <array name> [size];

Examples for declaration: int iarr[3]; char carr[20]; float farr[3];

Syntax for initialization: <data type> <array name> [size] = {val1, val2, …, valn};
Examples for initialization:

int iarr[3] = {2, 3, 4};

char carr[20] = “program”;

float farr[3] = {12.5, 13.5, 14.5};

Different Methods of Initializing 1-D Array

Whenever we declare an array, we initialize that array directly at compile time.Initializing 1-D Array is
called as compiler time initialization if and only if we assign certain set of values to array element before
executing program. i.e. at compilation time.

Here we are learning the different ways of compile time initialization of an array.

Ways of Array Initializing 1-D Array:

1. Size is Specified Directly


2. Size is Specified Indirectly
Method 1: Array Size Specified Directly

In this method, we try to specify the Array Size directly. int


num [5] = {2,8,7,6,0};

62
In the above example we have specified the size of array as 5 directly in the initialization statement.
Compiler will assign the set of values to particular element of the array.

num[0] = 2; num[1] = 8; num[2] = 7; num[3] = 6; num[4] = 0;

As at the time of compilation all the elements are at specified position So This initialization scheme is
Called as “Compile Time Initialization“.

Graphical Representation:

Method 2: Size Specified Indirectly

In this scheme of compile time Initialization, We do not provide size to an array but instead we provide set
of values to the array.

int num[ ] = {2,8,7,6,0};

Explanation:

1. Compiler Counts the Number Of Elements Written Inside Pair of Braces and Determines the Size
of An Array.
2. After counting the number of elements inside the braces, The size of array is considered as 5
during complete execution.
3. This type of Initialization Scheme is also Called as “Compile Time Initialization“
Example Program
#include <stdio.h> int
main()

int num[] = {2,8,7,6,0};

63
int i;
for (i=0;i<5;i++) {
printf(“\n Array Element num [%d] = %d”,i, num[i]); } return
0; }
Output:

Array Element num[0] = 2


Array Element num[1] = 8
Array Element num[2] = 7
Array Element num[3] = 6
Array Element num[4] = 0

Accessing Array

1. We all know that array elements are randomly accessed using the subscript variable.
2. Array can be accessed using array-name and subscript variable written inside pair of square
brackets [ ].
Consider the below example of an array

In this example we will be accessing array like this arr[3] =


Forth Element of Array

arr[5] = Sixth Element of Array

whereas elements are assigned to an array using below way

arr[0] = 51; arr[1] = 32; arr[2] = 43; arr[3] = 24; arr[4] = 5; arr[5] =26;

Example Program1: Accessing array


#include<stdio.h>
#include<conio.h>

void main()
{

64
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\nElement at arr[%d] is %d",i,arr[i]);
}
getch();
}
Output:
Element at arr[0] is 51
Element at arr[1] is 32
Element at arr[2] is 43
Element at arr[3] is 24
Element at arr[4] is 5
Element at arr[5] is 26
How a[i] Works?
We have following array which is declared like int arr[] = { 51,32,43,24,5,26};

As we have elements in an array, so we have track of base address of an array. Below things are
important to access an array.

Expression Description Example

arr It returns the base address of an array Consider 2000

*arr It gives zeroth element of an array 51

Expression Description Example

*(arr+0) It also gives zeroth element of an array 51

*(arr+1) It gives first element of an array 32

So whenever we tried accessing array using arr[i] then it returns an element at the location*(arr

+ i)

65
Accessing array a[i] means retrieving element from address (a + i).

Example Program2: Accessing array


#include<stdio.h>
#include<conio.h>

void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i),i[arr]);
}
getch();
}
Output:

51 51 51 51
32 32 32 32
43 43 43 43
24 24 24 24
55 5 5
26 26 26 26
Operations with One Dimensional Array

1. Deletion – Involves deleting specified elements form an array.


2. Insertion – Used to insert an element at a specified position in an array.
3. Searching – An array element can be searched. The process of seeking specific elements in an
array is called searching.
4. Merging – The elements of two arrays are merged into a single one.
5. Sorting – Arranging elements in a specific order either in ascending or in descending order.
Example Programs:

1. C Program for deletion of an element from the specified location from an


Array
#include<stdio.h>
int main() {
66
int arr[30], num, i, loc; printf("\
nEnter no of elements:"); scanf("%d",
&num);
//Read elements in an array printf("\nEnter
%d elements :", num); for (i = 0; i < num;
i++) { scanf("%d", &arr[i]); }
//Read the location
printf("\nLocation of the element to be deleted :");
scanf("%d", &loc);
/* loop for the deletion

*/ while (loc < num) {


arr[loc - 1] = arr[loc];
loc++; }
num--; // No of elements reduced by 1
//Print Array
for (i = 0; i < num; i++)
printf("\n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5 Enter 5
elements: 3 4 1 7 8
Location of the element to be deleted: 3 3 4 7 8

2. C Program to insert an element in an array


#include<stdio.h>
int main() {
int arr[30], element, num, i, location;
printf("\nEnter no of elements:");
scanf("%d", &num);
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]); }
printf("\nEnter the element to be inserted:"); scanf("%d",

67
&element);
printf("\nEnter the location");
scanf("%d", &location);
//Create space at the specified location for
(i = num; i >= location; i--) { arr[i] =
arr[i - 1]; }
num++;
arr[location - 1] = element;
//Print out the result of insertion for
(i = 0; i < num; i++)
printf("n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5 1 2 3
45
Enter the element to be inserted: 6 Enter
the location: 2
16234 5

1. C Program to display array elements with addresses


#include<stdio.h>
#include<stdlib.h>
#define size 10 int
main() {
int a[3] = { 11, 22, 33 };
printf("\n a[0],value=%d : address=%u", a[0], &a[0]);
printf("\n a[1],value=%d : address=%u", a[1], &a[1]);
printf("\n a[2],value=%d : address=%u", a[2], &a[2]); return
(0);
}
Output:
a[0],value=11 : address=2358832
68
a[1],value=22 : address=2358836
a[2],value=33 : address=2358840

2. gram to calculate addition of all elements in an array


#include<stdio.h>
int main() {
int i, arr[50], sum, num; printf("\
nEnter no of elements :"); scanf("%d",
&num);
//Reading values into Array
printf("\nEnter the values :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);
//Computation of total
sum = 0;
for (i = 0; i < num; i++)
sum = sum + arr[i];
//Printing of all elements of array for
(i = 0; i < num; i++) printf("\na[%d]=
%d", i, arr[i]);
//Printing of total
printf("\nSum=%d", sum);
return (0);
}
Output:
Enter no of elements : 3 Enter
the values : 11 22 33 a[0]=11
a[1]=22
a[2]=33
Sum=66

Multi Dimensional Array:

1. Array having more than one subscript variable is called Multi-Dimensional array.
2. Multi Dimensional Array is also called as Matrix.
Syntax: <data type> <array name> [row subscript][column subscript];
69
Example: Two Dimensional Arrays
Declaration: Char name[50][20];
Initialization:

int a[3][3] = { 1, 2, 3
5, 6, 7
8, 9, 0};
In the above example we are declaring 2D array which has 2 dimensions. First dimension will refer the
row and 2nd dimension will refer the column.

Example: Three Dimensional Arrays Declaration:


Char name[80][20][40];

The following information are given by the compiler after the declaration

Example Type Array Dimension No. of Elements in


Name No. Each Dimension

1 integer roll 1 10

2 character name 2 80 and 20

3 character name 3 80 and 20 and 40

Two Dimensional Arrays:

1. Two Dimensional Array requires Two Subscript Variables


2. Two Dimensional Array stores the values in the form of matrix.
3. One Subscript Variable denotes the “Row” of a matrix.
4. Another Subscript Variable denotes the “Column” of a matrix.

70
Declaration and use of 2D Arrays:

int a[3][4];
for(i=0;i<row,i++)
for(j=0;j<col,j++) {
printf("%d",a[i][j]); } Meaning
of Two Dimensional Arrays:

1. Matrix is having 3 rows ( i takes value from 0 to 2 )


2. Matrix is having 4 Columns ( j takes value from 0 to 3 )
3. Above Matrix 3×4 matrix will have 12 blocks having 3 rows & 4 columns.
4. Name of 2-D array is „a„ and each block is identified by the row & column number.
5. Row number and Column Number Starts from 0.
Two-Dimensional Arrays: Summary with Sample Example:

Summary Point Explanation

No of Subscript Variables Required 2

Declaration a[3][4]

No of Rows 3

No of Columns 4

No of Cells 12

No of for loops required to iterate 2

Memory Representation:

1. 2-D arrays are stored in contiguous memory location row wise.


2. 3 X 3 Array is shown below in the first Diagram.
3. Consider 3×3 Array is stored in Contiguous memory location which starts from 4000.
4. Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next memory
location i.e. Elements stored row-wise
5. After Elements of First Row are stored in appropriate memory locations, elements of
next row get their corresponding memory locations.

71
6. This is integer array so each element requires 2 bytes of memory.
Basic Memory Address Calculation:

a[0][1] = a[0][0] + Size of Data Type

Element Memory Location

a[0][0] 4000

a[0][1] 4002

a[0][2] 4004

a[1][0] 4006

a[1][1] 4008

a[1][2] 4010

a[2][0] 4012

a[2][1] 4014

a[2][2] 4016

72
73
Initializing 2D Array

Method 1: Initializing all Elements row wise

For initializing 2D Array we need to assign values to each element of an array using the below syntax.

int a[3][2] = { {1, 4}, {5, 2}, {6, 5} };

Example Program
#include<stdio.h> int
main()

{
int i, j;
int a[3][2] = { { 1, 4 }, { 5, 2 }, { 6, 5 } };
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]); }
printf("\n"); }
return 0;
}
Output:
1 4
5 2
6 5
We have declared an array of size 3 X 2, it contains overall 6
elements.
74
Row 1: {1, 4},
Row 2: {5, 2},
Row 3: {6, 5}
We have initialized each row independently a[0]
[0] = 1
a[0][1] = 4
Method 2: Combine and Initializing 2D Array

Initialize all Array elements but initialization is much straight forward. All values are assigned sequentially
and row-wise

int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };

Example Program:
#include <stdio.h> int
main() {

int i, j;
int a[3][2] = { 1, 4, 5, 2, 6, 5 };
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);

} printf("\n"); }
return 0;
}
Output:
1 4
5 2
6 5
Method 3: Some Elements could be initialized

int a[3][2] = { { 1 }, { 5 , 2 }, { 6 } };
Now we have again going with the way 1 but we are removing some of the elements from the array.
Uninitialized elements will get default 0 value. In this case we have declared and initialized 2-D array like
this

75
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { { 1 }, { 5, 2 }, { 6 }};
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]); }
printf("\n"); }
return 0;
}
Output:
1 0
5 2
6 0
Accessing 2D Array Elements:

1. To access every 2D array we requires 2 Subscript variables.


2. i – Refers the Row number
3. j – Refers Column Number
4. a[1][0] refers element belonging to first row and zeroth column
Example Program: Accept & Print 2×2 Matrix from user
#include<stdio.h>
int main() {
int i, j, a[3][3];
// i : For Counting Rows
// j : For Counting Columns for
(i = 0; i < 3; i++) { for (j
= 0; j < 3; j++) {
printf("\nEnter the a[%d][%d] = ", i, j);
scanf("%d", &a[i][j]); } }
//Print array elements for
(i = 0; i < 3; i++) { for
(j = 0; j < 3; j++) {

76
printf("%d\t", a[i][j]); }
printf("\n"); }
return (0);
}
How it Works?

1. For Every value of row Subscript , the column Subscript incremented from 0 to n-1 columns
2. i.e. For Zeroth row it will accept zeroth, first, second column (a[0][0], a[0][1], a[0][2]) elements
3. In Next Iteration Row number will be incremented by 1 and the column number again initialized to 0.
4. Accessing 2-D Array: a[i][j]  Element From ith Row and jth Column

77
UNIT IV

ARRAYS AND STRING VARIABLES

Passing array element by element to function:

1. Individual element is passed to function using Pass By Value parameter passing scheme
2. An original Array element remains same as Actual Element is never passed to Function. Thus function body
cannot modify Original Value.
3. Suppose we have declared an array „arr[5]‟ then its individual elements are arr[0],arr[1]…arr[4].
Thus we need 5 function calls to pass complete array to a function.
Consider an array int arr[5] = {11, 22, 33, 44, 55};

Iteration Element Passed to Function Value of Element


1 arr[0] 11
2 arr[1] 22
3 arr[2] 33
4 arr[3] 44
5 arr[4] 55

Example Program #1: #include<


stdio.h> #include< conio.h>
void fun(int num)

{
printf("\nElement : %d",num);
}
void main() { int
arr[5],i;
clrscr();
printf("\nEnter the array elements : "); for(i=0;i<
5;i++)
scanf("%d",&arr[i]);
printf("\nPassing array element by element....."); for(i=0;i< 5;i++)
fun(arr[i]); getch();
}
Output:

78
Enter the array elements : 1 2 3 4 5 Passing array
element by element..... Element : 1
Element : 2
Element : 3
Element : 4
Element : 5
Disadvantage of this Scheme:

1. This type of scheme in which we are calling the function again and again but with different array element is
too much time consuming. In this scheme we need to call function by pushing the current status into the
system stack.
2. It is better to pass complete array to the function so that we can save some system time required for pushing
and popping.
3. We can also pass the address of the individual array element to function so that function can modify the
original copy of the parameter directly.
Example Program #2: Passing 1-D Array Element by Element to function

#include<stdio.h> void
show(int b); void main() {
int arr[3] = {1,2,3}; int i;
for(i=0;i<3;i++) show(arr[i]);
}
void show(int x)
{
printf("%d ",x);
}
Output:
12 3

STRINGS

A string is a sequence of character enclosed with in double quotes (“ ”) but ends with

\0. The compiler puts \0 at the end of string to specify the end of the string.

To get a value of string variable we can use the two different types of formats.

Using scanf() function as: scanf(“%s”, string variable);

79
Using gets() function as : gets(string variable);

STRING HANDLING FUNCTIONS

C library supports a large number of string handling functions. Those functions are stored under the header file string.h
in the program.

Let us see about some of the string handling functions.

(i) strlen() function


strlen() is used to return the length of the string , that means counts the number of characters present
in a string.

Syntax

integer variable = strlen (string variable);

Example:

#include<stdio.h>
#include<conio.h> void
main()
{
char str[20]; int
strlength; clrscr();
printf(‚Enter String:‛); gets(str);
strlength=strlen(str);
printf(‚Given String Length Is: %d‛, strlength); getch();
}
Output:

Enter String Welcome


Given String Length Is:7

(ii) strcat() function


The strcat() is used to concatenate two strings. The second string will be appended to the end of the first
string. This process is called concatenation.

Syntax

80
strcat (StringVariable1, StringVariable 2);

Example:

#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20],str2[20]; clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
printf(‚ Concatenation String is:%s‛, strcat(str1,str2)); getch();
}
Output:

Enter First String Good


Enter Second String Morning
Concatenation String is: GoodMorning

(iii) strcmp() function


strcmp() function is used to compare two strings. strcmp() function does a case sensitive comparison
between two strings. The two strings are compared character by character until there is a mismatch or end of one of
the strings is reached (whichever occurs first). If the two strings are identical, strcmp( ) returns a value zero. If
they‟re not, it returns the numeric difference between the ASCII values of the first non-matching pairs of characters.

Syntax

strcmp(StringVariable1, StringVariable2);

Example:

#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20], str2[20]; int res;

81
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmp(str1,str2);
printf(‚ Compare String Result is:%d‛,res); getch();
}
Output:

Enter First String Good


Enter Second String Good
Compare String Result is: 0

(iv) strcmpi() function

strcmpi() function is used to compare two strings. strcmpi() function is not case sensitive.

Syntax

strcmpi(StringVariable1, StringVariable2);

Example:

#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20], str2[20]; int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmpi(str1,str2);
printf(‚ Compare String Result is:%d‛,res); getch();
}
82
Output:

Enter First String WELCOME


Enter Second String welcome
Compare String Result is: 0
(v) strcpy() function:

strcpy() function is used to copy one string to another. strcpy() function copy the contents of second string to first
string.

Syntax

strcpy(StringVariable1, StringVariable2);

Example:

#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20], str2[20]; int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2); strcpy(str1,str2)
printf(‚ First String is:%s‛,str1); printf(‚
Second String is:%s‛,str2); getch();
}
Output:

Enter First String Hello


Enter Second String welcome
First String is: welcome Second String
is: welcome
(vi) strlwr () function:
This function converts all characters in a given string from uppercase to lowercase letter.

83
Syntax

strlwr(StringVariable);

Example:

#include<stdio.h>
#include<conio.h> void
main()
{
char str[20]; clrscr();
printf(‚Enter String:‛); gets(str);
printf(‚Lowercase String : %s‛, strlwr(str)); getch();
}
Output:

Enter String WELCOME


Lowercase String : welcome
(vii) strrev() function:
strrev() function is used to reverse characters in a given string.

Syntax

strrev(StringVariable);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
char str[20]; clrscr();
printf(‚Enter String:‛); gets(str);
printf(‚Reverse String : %s‛, strrev(str)); getch();
}
Output:

Enter String WELCOME


84
Reverse String : emoclew
(viii) strupr() function:
strupr() function is used to convert all characters in a given string from lower case to uppercase letter.

Syntax

strupr(Stringvariable);

Example:

#include<stdio.h>
#include<conio.h> void
main()
{
char str[20]; clrscr();
printf(‚Enter String:‛); gets(str);
printf(‚Uppercase String : %s‛, strupr(str)); getch();
}
Output:

Enter String welcome


Uppercase String : WELCOME

Local, Global and Static variable Local variable:-

variables that are defined with in a body of function or block. The local variables can be used only
in that function or block in which they are declared.
Same variables may be used in different functions such as function()

int a,b; function 1();

function2 ()

int a=0;

85
b=20;

Global variable:-
the variables that are defined outside of the function is called global variable. All functions in the program can
access and modify global variables. Global variables are automatically initialized at the time of initialization.

Example:

#include<stdio.h> void

function(void); void

function1(void); void

function2(void); int a, b=20;

void main()

printf(“inside main a=%d,b=%d \n”,a,b); function();

function1();

function2();

function()

Prinf(“inside function a=%d,b=%d\n”,a,b);

function 1()

{
prinf(“inside function a=%d,b=%d\n”,a,b);

function 2()

{
86
prinf(“inside function a=%d,b=%d\n”,a,);

Static variables: static variables are declared by writing the key word static.

-syntax:-

static data type variable name; static int a;

-the static variables initialized only once and it retain between the function call. If its variable is not
initialized, then it is automatically initialized to zero.

Example:

void fun1(void); void

fun2(void); void main()

fun1();

fun2();

void fun1()

{
int a=10, static int b=2; printf(“a=%d,

b=%d”,a,b); a++;

b++;

Output:a= 10 b= 2

a=10 b= 3

87
POINTERS

Definition:-

A pointer is a variable whose value is the address of another variable. Like any variables, we must declare
a pointer variable at the beginning of the program. We can create pointer to any variable type as given in
te below examples.

The general format of a pointer variable declaration is as follows:-

datatype *pointervariable;

Examples: int *ip; //pointer to an integer variable


float *fp; //pointer to a float variable
double *dp; //pointer to a double variable
char *cp; //pointer to a character variable

POINTER OPERATORS:

Operator Operator Name Purpose

* Value at address Operator Gives Value stored at Particular address

& Address Operator Gives Address of Variable

POINTER ADDRESS OPERATOR

1. Pointer address operator is denoted by ‘&’ symbol


2. When we use ampersand symbol as a prefix to a variable name ‘&’, it gives the address of that
variable.
88
Take an example –
&n - It gives an address of variable n

WORKING OF ADDRESS OPERATOR


Examples:

(1) #include<stdio.h>
void main()
{

89
int n = 10;
printf("\nValue of n is : %d",n); printf("\nAddress of
n is : %u",&n);
}

Output :
Value of n is : 10
Address of n is : 1002

Explanation:
Consider the above example, where we have used to print the address of the variable using ampersand
operator.
In order to print the variable we simply use name of variable while to print the address of the variable we
use ampersand along with %u
printf("\nValue of &n is : %u",&n);

(2) #include<stdio.h>
Void main()
{
Int n=20;
Printf(“The value of n is: %d”,n);
Printf(“The address of n is: %u”,&n);
Printf(“The value of n is: %d”,*(&n));
}

OUTPUT:
The value of n is:20
The address of n is:1002 The
value of n is:20

Explanation:
In the above program, first printf displays the value of n. The second printf displays the address of the
variable n i.e) 1002, which is obtained by using &n(address of variable n). The last printf can be
explained as follows,
*(&n) = *(Address of variable n)
=*(1002)
=Value at address 1002
Therefore *(&n)=20

90
UNDERSTANDING ADDRESS OPERATOR

Initialization of Pointer can be done using following 4 Steps :

i. Declare a Pointer Variable and Note down the Data Type.


ii. Declare another Variable with Same Data Type as that of Pointer Variable.
iii. Initialize Ordinary Variable and assign some value to it.
iv. Now Initialize pointer by assigning the address of ordinary variable to pointer variable.

Below example will clearly explain the initialization of Pointer Variable. #include<stdio.h>
int main()
{

int a; // Step 1 int


*ptr; // Step 2 a
= 10; // Step 3
ptr = &a; // Step 4

return(0);
}

Explanation of Above Program :


 Pointer should not be used before initialization.
 “ptr” is pointer variable used to store the address of the variable.
 Stores address of the variable ‘a’ .
 Now “ptr” will contain the address of the variable “a” .

Note :
Pointers are always initialized before using it in the program

Consider the following program –

#include<stdio.h>
void main()
{
int i = 5;
int *ptr;
ptr = &i;
printf("\nAddress of i : %u",&i);
printf("\nValue of ptr is : %u",ptr);
}

91
OUTPUT:
Address of i : 65524
Value of ptr is : 65524

After declaration memory map will be like this – int i


= 5;
int *ptr;

After assigning the address of variable to pointer, i.e after the execution of this statement – ptr =
&i;

Program : accessing value and address of Pointer

/* Program to display the contents of the variable and their address using pointer variable*/
(1) #include<stdio.h>
main()
{
int i = 3, *j; j
= &i;

printf("\nAddress of i = %u", &i); printf("\


nAddress of i = %u", j); printf("\nAddress of j =
%u", &j); printf("\nValue of j = %u", j); printf("\
nValue of i = %d", i); printf("\nValue of i =
%d", *(&i)); printf("\nValue of i = %d", *j);
}
Output :
Address of i = 65524

92
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3 Value
of i = 3 Value of i = 3

Variable Actual Value

Value of i 3
Value of j 65524
Address of i 65524
Address of j 65522

POINTER EXPRESSIONS

Like any other variables pointer variables can be used in an expression. In general, expressions
involving pointer conform to the same rules as other expressions. The pointer expression is a linear
combination of pointer variables, variables and operators. Pointer expression gives either numerical
output or address output.
Example:
y = *p1 * *p2; sum
= sum + *p1; z = 5
- *p2/*p1;
*p2 = *p2 + 10;

/*Pointer expression and pointer arithmetic*/


#include< stdio.h >
void main()
{
int *ptr1,*ptr2;
int a,b,x,y;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 –b; y=b -
*ptr1/ *ptr2 +a;
printf(“\nAddress of a %u”,ptr1);
printf(“\nAddress of b %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
}

OUTPUT:
Address of a 65522
Address of b 65524
a=30 b=6

93
x=30 y=31

EXPLANATION OF PROGRAM:
In the above example program, ptr1, ptr2 are the pointer variables which are used to store the
address of the two variables a and b respectively using the statements ptr1=&a, ptr2=&b. In the pointer
expressions which are given below, the value of x and y are calculated as follows,
x=*ptr1+ *ptr2 - b;
=30 + 6 – 6
x=30
y=b - *ptr1/ *ptr2 +a;
=6 - 30/6 + 30
=6 – 5 + 30
y=31

POINTER ASSIGNMENT

We can use a pointer on the right-hand side of an assignment statement to assign its value to
another pointer. For example,
#include< stdio.h >
void main()
{
int *p1,*p2;
int x=99;

p1=&x;
p2=p1; /*pointer assignment*/
printf(“\nValues at p1 and p2: %d %d”,*p1,*p2); /*print the value of x twice*/ printf(“\nAddresses
pointed to by p1 and p2: %u %u”,p1,p2); /*print the address of x twice*/
}

OUTPUT:
Values at p1 and p2: 99 99
Addresses pointed to by p1 and p2: 5000 5000

EXPLANATION OF PROGRAM:
After the assignment sequence,
p1=&x;
p2=p1;
Both p1and p2 point to x. Thus both p1 and p2 refer to the same value.

ARRAYS USING POINTER

When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address gives location of the first element which is also allocated by the
compiler.
94
Suppose we declare an array arr,

int arr[5]={ 1, 2, 3, 4, 5 };

Assuming that the base address of arr is 1000 and each integer requires two byte, the five element will be
stored as follows

Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0].
Therefore arr is containing the address of arr[0] i.e 1000.

arr is equal to &arr[0] // by default

We can declare a pointer of type int to point to the array arr. int
*p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.

NOTE : You cannot decrement a pointer once incremented. p-- won't work.

POINTER TO ARRAY

As studied above, we can use a pointer to point to an Array, and then we can use that pointer to access the
array. Lets have an example,

int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]

for (i=0; i<5; i++)


{
printf("%d", *p);
p++;
}
In t Pointer and Function
Function Pointer

95
#include <stdio.h>
void subtractAndPrint(int x, int y); void
subtractAndPrint(int x, int y) { int z = x -
y;
printf("Simon says, the answer is: %d\n", z);
}
int main()
{
void (*sapPtr)(int, int) = subtractAndPrint; (*sapPtr)(10, 2);
sapPtr(10, 2);
}
The pointer can be used as an argument in functions. The arguments or parameters to the function
are passed in two ways.
 Call by value
 Call by reference
 In ‘C Language there are two ways that the parameter can be passed to a function they are

o Call by value
o Call by reference
Call by Value:
 This method copies the value of actual parameter into the formal parameter of the
function.
 The changes of the formal parameters cannot affect the actual parameters, because formal
arguments are photocopy of the actual argument.
 The changes made in formal argument are local to the block of the called functions. Once control
return back to the calling function the changes made disappear.

Example:
#include<stdio.h>
#include<conio.h>
void cube(int);
int cube1(int);
void main() Output:
{
int a; Enter one values 3
clrscr();
printf(“Enter one values”); scanf(“%d”,&a); Value of cube function is 3
printf(“Value of cube function is=%d”, cube(a)); Value of cube1 function is 729
printf(“Value of cube1 function is =%d”, cube1(a ));
getch();
}
void cube(int x)
{
x=x*x*x*;
return x;
}

int cube1(int x)
{
x=x*x*x*;
96
return x;
}

Call by reference
 Call by reference is another way of passing parameter to the function.
 Here the address of argument are copied into the parameter inside the function, the
address is used to access arguments used in the call.
 Hence changes made in the arguments are permanent.
 Here pointer are passed to function, just like any other arguments.
Example:-
#include<stdio.h>
#include<conio.h>
void swap(int,int);
void main()
{ Output:
int a=5,b=10; clrscr();
printf(“Before swapping a=%d b=%d”,a,b); Before swapping a=5 b=10
swap(&a,&b);
After swapping a=10 b=5
printf(“After swapping a=%d b=%d”,a,b); getch();
}
void swap(int *x,int *y)
{
int *t;
t=*x;
*x=*y;
*y=t;
}

Function Returning Pointer

A function can return a single value by its name or return multiple values through pointer parameters.
Since pointers are a data type in c, we can also force a function to return a pointer to the calling function.
Program:
int *larger(int*,int*);
void main() Output:
{
int a=10; 20
int b=20;
int *p;
p =larger(&a,&b);
printf(“%d”,*p);
}
int *larger(int *x, int *y)
{
if(*x>*y)
return(x);
else }

97
return (y);

98
};

-------- Inside function -------

struct name *ptr;

Here, the pointer variable of type struct name is created.

Structure's member through pointer can be used in two ways:

1. Referencing pointer to another address to access memory


2. Using dynamic memory allocation
Consider an example to access structure's member through pointer.

#include <stdio.h>

struct name{int a;

float b;

};

int main()

struct name *ptr,p;

ptr=&p; /* Referencing pointer to memory address of p */

printf("Enter integer: ");

scanf("%d",&(*ptr).a);

printf("Enter number: ");

scanf("%f",&(*ptr).b);

printf("Displaying: ");

99
printf("%d%f",(*ptr).a,

(*ptr).b); return 0;

In this example, the pointer variable of type struct name is referenced to the address of p.
Then, only the structure member through pointer can can accessed.
Structure pointer member can also be accessed using -> operator.

(*ptr).a is same as ptr->a

(*ptr).b is same as ptr->b

ACCESSING STRUCTURE MEMBERS WITH POINTER

To access members of structure with structure variable, we used the dot . operator. But when we

have a pointer of structure type, we use arrow -> to access structure members.

struct Book

char name[10];

int price;

int main()

struct Book b;

struct Book* ptr = &b;


100
ptr->name = "Dan Brown"; //Accessing Structure Members

ptr->price = 500;

Example program for C structure using pointer:

In this program, “record1″ is normal structure variable and “ptr” is pointer structure variable. As
you know, Dot(.) operator is used to access the data using normal structure variable and arrow(-

>) is used to access data using pointer variable.

#include <stdio.h>
#include <string.h>

struct student

int id;

char name[30]; float


percentage;
};

int main()

int i;

struct student record1 = {1, "Raju", 90.5}; struct student *ptr;

ptr = &record1;

printf("Records of STUDENT1: \n"); printf(" Id


is: %d \n", ptr->id); printf(" Name is: %s \n",
ptr->name);

printf(" Percentage is: %f \n\n", ptr->percentage); return 0;

}
101
Output:

Records of STUDENT1:
Id is: 1
Name is: Raju Percentage is: 90.500000

he above program, the pointer *p will print all the values stored in the array one by one. We can also use
the Base address (a in above case) to act as pointer and print all the values.

/*Program to print the addresses of array elements */

#include <stdio.h> void


main(){
char c[4]; int
i;
for(i=0;i<4;++i){
printf("Address of c[%d]=%x\n",i,&c[i]);
}
102
}
OUTPUT:
Address of c[0]=28ff44
Address of c[1]=28ff45
Address of c[2]=28ff46
Address of c[3]=28ff47

Notice, that there is equal difference (difference of 1 byte) between any two consecutive elements
of array.

Consider the following:

int my_array[] = {1,23,17,4,-5,100};


Here we have an array containing 6 integers. We refer to each of these integers by means of a subscript
to my_array, i.e. using my_array[0] through my_array[5]. But, we could alternatively access them via a
pointer as follows:

int *ptr;
ptr = &my_array[0]; /* pointer points to the first integer in our array */
And then we could print out our array either using the array notation or by dereferencing our pointer. The
following code illustrates this:

#include <stdio.h> int


main(void)
{
int my_array[] = {1,23,17,4,-5,100}; int
*ptr;
int i;
ptr = &my_array[0] ; /* point pointing to the first element of the array */
printf("\n\n");
for (i = 0; i < 6; i++)
{
printf("my_array[%d] = %d ",i,my_array[i]); /*<-- A */
printf("ptr + %d = %d\n",i, *(ptr + i)); /*<-- B */
}
return 0;
}
Compile and run the above program and carefully note lines A and B and that the program prints out the
same values in either case. Also observe how we dereferenced our pointer in line B, i.e. we first added i to
it and then dereferenced the new pointer. Change line B to read:

printf("ptr + %d = %d\n",i, *ptr++);

and run it again. then change it to:

printf("ptr + %d = %d\n",i, *(++ptr));

and try once more.Each time try and predict the outcome and carefully look at the actual outcome.

103
In C, the standard states that wherever we might use &var_name[0] we can replace that with var_name,
thus in our code where we wrote:

ptr = &my_array[0];

we can write:

ptr = my_array;

to achieve the same result.

/* Example program to print the array elements using pointer */

#include <stdio.h> int


main(){
int data[5], i;
printf("Enter elements: ");
for(i=0;i<5;++i)
scanf("%d",data[i]);
printf("You entered: ");
for(i=0;i<5;++i)
printf("%d\n",*(data+i));
return 0;
}
Output
Enter elements: 1
2
3
5
4
You entered: 1
2
3
5
4

/* Program to find sum of array elements using pointer */

#include<stdio.h>
#include<conio.h>
void main()
{
int numArray[10]; int
i, sum = 0;
int *ptr;

printf("\nEnter 10 elements : ");

104
for (i = 0; i < 10; i++)
scanf("%d", &numArray[i]);

ptr = numArray;

for (i = 0; i < 10; i++) {


sum = sum + *ptr;
ptr++;
}
printf("The sum of array elements :
%d", sum);
}
OUTPUT
Enter 10 elements : 11 12 13 14 15 16 17 18 19 20 The
sum of array elements is 155

EXPLANATION OF PROGRAM:

Accept the 10 elements from the user in the array.


1 for (i = 0; i < 10; i++)
2 scanf("%d", &numArray[i]);
We are storing the address of the array into the pointer.
1 ptr = numArray; /* a=&a[0] */
Now in the for loop we are fetching the value from the location pointer by pointer variable. Using
De-referencing pointer we are able to get the value at address.
1 for (i = 0; i < 10; i++)
2 { sum = sum + *ptr;
3 ptr++;
4 }
Suppose we have 2000 as starting address of the array. Then in the first loop we are fetching the value at
2000. i.e
1 sum = sum + (value at 2000)
2 = 0 + 11
3 = 11

In the Second iteration we will have following calculation –


1 sum = sum + (value at 2002)
2 = 11 + 12
3 = 23
Pointer example-1
#include <stdio.h>
#include <math.h>
main()
{
int num [ ] = { 10,20,30,40,50 }

105
print ( &num, 5, num);
}
print ( int *j, int n, int b[5])
{
int i;
for(i=0;i<=4;i++)

106
{
printf ( " %u %d %d %u \n ", &j[i] , *j , *(b+i) , &b); j++;
}
}

In this example we have a single dimensional array num and a function print . We are passing, the address
to the first element of the array, the number of elements and the array itself, to this function. When the
function receives this arguments, it maps the first one to another pointer j and the array num is
copied into another array b . (The type declarations are made here itself. Note that these declarations can
also be given just below this line). j is now a pointer to the array b.
Inside the function we are printing out the address of the array element and the value of the array element in two
ways. One using the pointer j and the other using the array b. If we compile and run this code we get the following
out put,
3221223408 10 10
3221223376
3221223416 20 20
3221223376
3221223424 30 30
3221223376
Note that as we increment j it points to the successive elements of the array. We can get both the address
of the array elements and the value stored there using this. However the array name, which acts also as
the pointer to its base address, is not able to give us the address of its elements. Or in other words, the
array name is a constant pointer. Also note that while j ispoints to the elements of the array num, b is
pointing to its copy.

Next we have an example that uses a two dimensional array. Here care should be taken to declare
the number of columns correctly.

Pointer example-2
#include <stdio.h>
#include <math.h>
main()

int arr [ ][3] = {{11,12,13}, {21,22,23},{31,32,33},{41,42,43},{51,52,53}};

107
int I , j ;

int *p , (*q) [3], *r ; p


= (int *) arr ;
q = arr;
r = (int *) q ;

printf ( " %u %u %d %d %d %d \n ", p , q , *p , *(r) , *(r+1), *(r+2)); p++ ;


q++ ;
r = (int *) q ;
printf ( " %u %u %d %d %d %d \n ", p , q , *p , *(r) , *(r+1), *(r+2));

Here we have a pointer p and a pointer array q. The first assignment statement is
to make the pointer p points to the array arr. While assigning, we also declare the type
of the variable arr. Note that variables on both side of this statement should have the
same type. Next line is a similar statement, now with q and arr. Since q is a pointer
array, the array can be directly assigned to it and there is no need for specifying the type
of the variable. In the next line we make the pointer r to point to the pointer array q .
Then we will print out the different values. Here is what we get from this,

ARRAY OF POINTERS

Just like array of integers or characters, there can be array of pointers too. An array of pointers can be
declared as :

<datatype> *<pointername> [number-of-elements];

For example :

char *ptr[3];
The above line declares an array of three character pointers. Let’s take a working example :

108
#include<stdio.h
> int main(void)
{
char *p1 =
"Himanshu"; char *p2
= "Arora"; char *p3 =
"India";

char *arr[3];

arr[0] =
p1; arr[1]
= p2;
arr[2] =
p3;

printf("\n p1 = [%s] \n",p1);


printf("\n p2 = [%s] \n",p2);
printf("\n p3 = [%s] \n",p3);

printf("\n arr[0] = [%s] \n",arr[0]);


printf("\n arr[1] = [%s] \n",arr[1]);
printf("\n arr[2] = [%s] \n",arr[2]);
In the above code, we took three pointers pointing to three strings. Then we declared an array
that can contain three pointers. We assigned the pointers ‘p1′, ‘p2′ and ‘p3′ to the 0,1 and 2 index of
array.

Let’s see the output :

p1 =
[Himanshu] p2
= [Arora]
p3 = [India]
arr[0] =
[Himanshu] arr[1]
= [Arora] arr[2] =
So we see that array now holds the address of strings.

Let us consider the following example, which makes use of an array of 3 integers:

int main ()
{

109
int var[] = {10, 100, 200};
int i;

for (i = 0; i < 3; i++)


{
printf("Value of var[%d] = %d\n", i, var[i] );
}
return 0;
}

OUTPUT:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

There may be a situation when we want to maintain an array, which can store pointers to an int or char or
any other data type available. Following is the declaration of an array of pointers to an integer:
int *ptr[3];
This declares ptr as an array of 3 integer pointers. Thus, each element in ptr, now holds a pointer to an int
value.

Following example makes use of three integers, which will be stored in an array of pointers as follows:

#include <stdio.h> int


main ()
{
int var[] = {10, 100, 200};
int i, *ptr[3];

ptr[0] = &var[0]; /* assign the address of 1st integer element */ ptr[1] =


&var[1]; /* assign the address of 2nd integer element */ ptr[2] =
&var[2]; /* assign the address of 3rd integer element */

for ( i = 0; i < 3; i++)


{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}

OUTPUT:
Value of var[0] = 10
Value of var[1] = 100

110
Value of var[2] = 200

111
UNIT V

STRUCTURES

Arrays are used for storing a group of SIMILAR data items. In order to store a group of data
items, we need structures. Structure is a constructed data type for packing different types of data that are
logically related. The structure is analogous to the “record” of a database. Structures are used for
organizing complex data in a simple and meaningful way.

Example for structures:

Student : regno, student_name, age, address

Book : bookid, bookname, author, price, edition, publisher, year Employee

: employeeid, employee_name, age, sex, dateofbirth, basicpay

Customer : custid, cust_name, cust_address, cust_phone

Structure Definition
Structures are defined first and then it is used for declaring structure variables. Let us see how to
define a structure using simple example given below:

struct book

int bookid;

char bookname[20];

char author[20];

float price;

int year;

int pages;

char publisher[25];

};
The keyword “struct” is used for declaring a structure. In this example, book is the name of the structure
or the structure tag that is defined by the struct keyword. The book structure has six fields and they are
known as structure elements or structure members. Remember each structure member may be of a

112
different data type. The structure tag name or the structure name can be used to declare variables of the
structure data type.

The syntax for structure definition is given below:

struct tagname

Data_type member1;

Data_type member2;

…………….

……………

};

Note:

1. To mark the completion of the template, semicolon is used at the end of the template.
2. Each structure member is declared in a separate line.

Declaring Structure Variables

First, the structure format is defined. Then the variables can be declared of that structure type. A structure
can be declared in the same way as the variables are declared. There are two ways for declaring a
structure variable.

1) Declaration of structure variable at the time of defining the structure (i.e structure
definition and structure variable declaration are combined)

struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
} b1,b2,b3;

The b1, b2, and b3 are structure variables of type struct book.

2) Declaration of structure variable after defining the structure


113
struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};

struct book b1, b2, b3;

NOTE:
 Structure tag name is optional.

E.g.

struct
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
}b1, b2, b3;

114
Declaration of structure variable at a later time is not possible with this type of declaration. It is a
drawback in this method. So the second method can be preferred.

 Structure members are not variables. They don‟t occupy memory until they are
associated with a structure variable.

Accessing Structure Members


There are many ways for storing values into structure variables. The members of a structure can be
accessed using a “dot operator” or “period operator”.

E.g. b1.author -> b1 is a structure variable and author is a structure member.

Syntax

STRUCTURE_Variable.STRUCTURE_Members

The different ways for storing values into structure variable is given below:

Method 1: Using Simple Assignment Statement

b1.pages = 786;

b1.price = 786.50;

Method 2: Using strcpy function

strcpy(b1.title, ‚Programming in C‛);

strcpy(b1.author, ‚John‛);

Method 3: Using scanf function

scanf(‚%s \n‛, b1.title);

scanf(‚%d \n‛, &b1.pages);

Example

115
#include<stdio.h>

#include<conio.h>

struct book

int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};

struct book b1, b2, b3;


main()
{
struct book b1;
clrscr();
printf("Enter the Book Id: ");
scanf("%d", &b1.bookid); printf("Enter
the Book Name: ");
scanf("%s", b1.bookname); printf("Enter
the Author Name: ");
scanf("%s", b1.author); printf("Enter
the Price: ");
scanf("%f", &b1.price); printf("Enter
the Year: ");
scanf("%d", &b1.year);
printf("Enter the Total No. of Pages: ");
scanf("%d", &b1.pages);
printf("Enter the Publisher Name: ");
scanf("%s", b1.publisher);
printf("%d %s %d %f %d %d %s", b1.bookid, b1.bookname, b1.author,
b1.price, b1.year, b1.pages, b1.publisher);
getch();
}
Output

116
Enter the Book Id: 786
Enter the Book Name: Programming Enter
the Author Name: John Enter the
Price: 123.50
Enter the Year: 2015
Enter the Total No. of Pages: 649 Enter the
Publisher Name: Tata McGraw
786 Programming 2118 123.500000 2015 649 Tata

Structure Initialization

Like variables, structures can also be initialized at the compile time.

Example

main()
{
struct
{
int rollno;
int attendance;
}
s1={786, 98};
}

The above example assigns 786 to the rollno and 98 to the attendance. Structure

variable can be initialized outside the function also.

Example

main()
{
struct student
{
int rollno;
int attendance;
};
struct student s1={786, 98};
struct student s2={123, 97};
}
Note:

117
Individual structure members cannot be initialized within the template. Initialization is possible only with
the declaration of structure members.

Nested Structures or Structures within Structures

Structures can also be nested. i.e A structure can be defined inside another structure.

Example

struct employee
{
int empid;
char empname[20];
int basicpay;
int da;
int hra;
int cca;
} e1;

In the above structure, salary details can be grouped together and defined as a separate structure.

Example

struct employee
{
int empid;
char empname[20];
struct
{
int basicpay;
int da;
int hra;
int cca;
} salary;
} e1;
The structure employee contains a member named salary which itself is another structure that contains
four structure members. The members inside salary structure can be referred as below:

e1.salary.basicpay
e1.salary.da;
e1.salary.hra;
e1.salary.cca;

118
However, the inner structure member cannot be accessed without the inner structure variable.

Example

e1.basicpay
e1.da e1.hra
e1.cca
are invalid statements

Moreover, when the inner structure variable is used, it must refer to its inner structure member. If it
doesn‟t refer to the inner structure member then it will be considered as an error.

Example

e1.salary (salary is not referring to any inner structure member. Hence it is wrong)

Note: C permits 15 levels of nesting and C99 permits 63 levels of nesting.

Array of Structures

A Structure variable can hold information of one particular record. For example, single record of
student or employee. Suppose, if multiple records are to be maintained, it is impractical to create multiple
structure variables. It is like the relationship between a variable and an array. Why do we go for an array?
Because we don‟t want to declare multiple variables and it is practically impossible. Assume that you
want to store 1000 values. Do you declare 1000 variables like a1, a2, a3…. Upto a1000? Is it easy to
maintain such code ? Is it a good coding? No. It is not. Therefore, we go for Arrays. With a single
name, with a single variable, we can store 1000 values. Similarly, to store 1000 records, we cannot declare
1000 structure variables. But we need “Array of Structures”.

An array of structure is a group of structure elements under the same structure variables.

struct student s1[1000];

The above code creates 1000 elements of structure type student. Each element will be structure
data type called student. The values can be stored into the array of structures as follows:

s1[0].student_age = 19;

Example

119
#include<stdio.h>
#include<conio.h>
struct book
{
int bookid;
char bookname[20];
char author[20];
};

Struct b1[5];

main()
{
int i;
clrscr();
for (i=0;i<5;i++)
{
printf("Enter the Book Id: ");
scanf("%d", &b1[i].bookid);
printf("Enter the Book Name: ");
scanf("%s", b1[i].bookname);
printf("Enter the Author Name: ");
scanf("%s", b1[i].author);
}
for (i=0;i<5;i++)
{
printf("%d \t %s \t %s \n", b1[i].bookid, b1[i].bookname, b1[i].author);
}
getch();
}

Output:

Enter the Book Id: 786


Enter the Book Name: Programming Enter
the Author Name: Dennis Ritchie Enter
the Book Id: 101
Enter the Book Name: Java Complete Reference Enter
the Author Name: Herbert Schildt Enter the
Book Id: 008
Enter the Book Name: Computer Graphics
Enter the Author Name: Hearn and Baker
120
786 Programming Dennis Ritchie
101 Java Complete Reference Herbert Schildt 008

Computer Graphics Hearn and Baker

Structure as Function Argument

Example

struct sample
{
int no;
float avg;
} a;

121
void main( )
{
a.no=75;
a.avg=90.25;
fun(a);
}

void fun(struct sample p)


{
printf(‚The no is=%d Average is %f‛,p.no , p.avg);
}

Output

The no is 75 Average is 90.25

Function that returns Structure

The members of a structure can be passed to a function. If a structure is to be passed to a called


function , we can use any one of the following method.

Method 1 :- Individual member of the structure is passed as an actual argument of the function call. The
actual arguments are treated independently. This method is not suitable if a structure is very large
structure.

Method 2:- Entire structure is passed to the called function. Since the structure declared as the
argument of the function, it is local to the function only. The members are valid for the

function only. Hence if any modification done on any member of the structure , it is not reflected in the
original structure.

Method 3 :- Pointers can be used for passing the structure to a user defined function. When the pointers
are used , the address of the structure is copied to the function. Hence if any modification done on any
member of the structure , it is reflected in the original structure.

Return data type function name ( structured variable )

Structured Data type for the structured variable;

{
Local Variable declaration;
Statement 1;

122
Statement 2;
--------------
-------------
Statement n;
}
Example :

#include <stdio.h>
struct st
{
char name[20];
int no;
int marks;
};
int main( )
{
struct st x ,y;
int res;
printf(‚\n Enter the First Record‛);
scanf(‚%s%d%d‛,x.name,&x.no,&x.marks);
printf(‚\n Enter the Second Record‛);
scanf(‚%s%d%d‛,y.name,&y.no,&y.marks); res
= compare ( x , y );
if (res == 1)
printf(‚\n First student has got the Highest Marks‛);
else

printf(‚\n Secondstudent has got the Highest Marks‛);compare ( struct st st1 , struct
st st2)
{
if (st1.marks > st2. marks )
return ( 1 );
else
return ( 0 );
}

In the above example , x and y are the structures sent from the main ( ) function as the actual
parameter to the formal parameters st1 and st2 of the function compare ( ).

Example program (1) – passing structure to function

#include<stdio.h>
#include<conio.h>
//-------------------------------------
struct Example
{

123
int num1;
int num2;
}s[3];
//-------------------------------------
void accept(struct Example *sptr)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr->num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr->num2);
}
//-------------------------------------
void print(struct Example *sptr)
{
printf("\nNum1 : %d",sptr->num1);
printf("\nNum2 : %d",sptr->num2);
}
//-------------------------------------
void main()
{
int i;
clrscr();
for(i=0;i<3;i++)
accept(&s[i]);

for(i=0;i<3;i++)
print(&s[i]);

getch();
}
Output :

Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60

Example program (2) – passing structure to function in C by value:

124
In this program, the whole structure is passed to another function by value. It means the whole
structure is passed to another function with all members and their values. So, this structure can be
accessed from called function. This concept is very useful while writing very big programs in C.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student record);

void main()
{
struct student record;

record.id=1; strcpy(record.name,
"Raju"); record.percentage =
86.5;

func(record);
getch();
}

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Output:
Id is: 1
Name is:
Raju
Percentage is: 86.500000

Example program (3) Passing structure by value

A structure variable can be passed to the function as an argument as normal variable. If structure is
passed by value, change made in structure variable in function definition does not reflect in original
structure variable in calling function.

125
Write a C program to create a structure student, containing name and roll. Ask user the name and
roll of a student in main function. Pass this structure to a function and display the information in
that function.

#include <stdio.h>
struct student
{
char name[50];
int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure declaration otherwise
compiler shows error */
int main()
{
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name); printf("Enter
roll number:");
scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 as argument return
0;
}
void Display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}

Output

Enter student's name: Kevin Amla Enter


roll number: 149
Output

Example program (4) – Passing structure to function in C by address:

In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to another
function with all members and their values. So, this structure can be accessed from called function by its
address.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

126
void func(struct student *record);

void main()
{
struct student record;

record.id=1; strcpy(record.name,
"Raju"); record.percentage =
86.5;

func(&record);
getch();
}

void func(struct student *record)


{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
Output:

Id is: 1
Name is:
Raju
Percentage is: 86.500000

Example program (5) Passing structure by reference

The address location of structure variable is passed to function while passing it by reference. If
structure is passed by reference, change made in structure variable in function definition reflects in
original structure variable in the calling function.

127
Write a C program to add two distances(feet-inch system) entered by user. To solve this program,
make a structure. Pass two structure variable (containing distance in feet and inch) to add function
by reference and display the result in main function without returning it.

#include <stdio.h>
struct distance
{
int feet;
float inch;
};
void Add(struct distance d1,struct distance d2, struct distance *d3); int main()
{
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet); printf("Enter
inch: "); scanf("%f",&dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d",&dist2.feet); printf("Enter
inch: "); scanf("%f",&dist2.inch);
Add(dist1, dist2, &dist3);

/*passing structure variables dist1 and dist2 by value whereas passing structure
variable dist3 by reference */
printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch); return 0;
}
void Add(struct distance d1,struct distance d2, struct distance *d3)
{
/* Adding distances d1 and d2 and storing it in d3 */ d3-
>feet=d1.feet+d2.feet;
d3->inch=d1.inch+d2.inch;
if (d3->inch>=12) { /* if inch is greater or equal to 12,
converting it to feet. */
d3->inch-=12;
++d3->feet;
}
}
Output

First distance
Enter feet: 12
Enter inch: 6.8

128
Second distance
Enter feet: 5
Enter inch: 7.5
Sum of distances = 18'-2.3"

Explanation

In this program, structure variables dist1 and dist2 are passed by value (because value of dist1 and dist2
does not need to be displayed in main function) and dist3 is passed by reference ,i.e, address of dist3
(&dist3) is passed as an argument. Thus, the structure pointer variable d3 points to the address of dist3. If
any change is made in d3 variable, effect of it is seed in dist3 variable in main function.

Example program(6) to declare a structure variable as global in C:

Structure variables also can be declared as global variables as we declare other variables in C.
So, When a structure variable is declared as global, then it is visible to all the functions in a program. In
this scenario, we don‟t need to pass the structure to any function separately.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure void

structure_demo();

int main()
{
record.id=1; strcpy(record.name,
"Raju"); record.percentage =
86.5;

structure_demo();
return 0;
}

void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

129
Output:
Id is: 1
Name is:
Raju
Percentage is: 86.500000

Example program(7)Passing Array of Structure to Function in C Programming

Array of Structure can be passed to function as a Parameter.function can also return Structure as return
type.Structure can be passed as follow

Example :

#include<stdio.h>
#include<conio.h>
//-------------------------------------
struct Example
{
int num1;
int num2;
}s[3];
//-------------------------------------
void accept(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr[i].num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr[i].num2);
}
}
//-------------------------------------
void print(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nNum1 : %d",sptr[i].num1);
printf("\nNum2 : %d",sptr[i].num2);
}
}
//-------------------------------------
void main()
{

130
int i;
clrscr();
accept(s,3);
print(s,3);
getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60

Explanation :

Inside main structure and size of structure array is passed. When reference (i.e ampersand) is not specified
in main , so this passing is simple pass by value. Elements can be accessed by using dot [.] operator

Union

The concept of Union is borrowed from structures and the formats are also same. The distinction
between them is in terms of storage. In structures , each member is stored in its own location but in Union
, all the members are sharing the same location. Though Union consists of more than one members , only
one member can be used at a particular time. The size of the cell allocated for an Union variable depends
upon the size of any member within Union occupying more no:- of bytes. The syntax is the same as
structures but we use the keyword union instead of struct.

Example:- the employee record is declared and processed as follows

union emp
{
char name[20];
int eno; float
salary;
} employee;

where employee is the union variable which consists of the member name,no and
salary. The compiler allocates only one cell for the union variable as

131
20 Bytes Length

Employee (only one location)

Location / Cell for name,no and salary

20 bytes cell can be shared by all the members because the member name is occupying the highest no:- of
bytes. At a particular time we can handle only one member.To access the members of an union , we have
to use the same format of structures.

Example program for C


union: #include <stdio.h>
#include <string.h>

union student
{
char name[20]; char
subject[20]; float
percentage;
};

int main()
{
union student record1;
union student record2;

// assigning values to record1 union variable


strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;

printf("Union record1 values example\n"); printf("


Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);

// assigning values to record2 union variable


printf("Union record2 values example\n");
strcpy(record2.name, "Mani");

132
printf(" Name : %s \n", record2.name);

strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);

133
record2.percentage = 99.50;

printf(" Percentage : %f \n", record2.percentage); return 0;


}

Output:

Union r
Name :
Subject
Percent
Union r
example
Subject
Percent

134
Explanation for above C union program:

There are 2 union variables declared in this program to understand the difference in accessing values
of union members.

Record1 union variable:

“Raju” is assigned to union member “record1.name” . The memory location name is


“record1.name” and the value stored in this location is “Raju”.

Then, “Maths” is assigned to union member “record1.subject”. Now, memory location name is
changed to “record1.subject” with the value “Maths” (Union can hold only one member at a
time).

Then, “86.50” is assigned to union member “record1.percentage”. Now, memory location name
is changed to “record1.percentage” with value “86.50”.

Like this, name and value of union member is replaced every time on the common storage space.

So, we can always access only one union member for which value is assigned at last.

We can‟t access other member values.

So, only “record1.percentage” value is displayed in output. “record1.name” and


“record1.percentage” are empty.

Record2 union variable:

If we want to access all member values using union, we have to access the member before
assigning values to other members as shown in record2 union variable in this program.

Each union members are accessed in record2 example immediately after assigning values to
them.

If we don‟t access them before assigning values to other member, member name and value
will be over written by other member as all members are using same memory.

We can‟t access all members in union at same time but structure can do that.

Example program – Another way of declaring C union:

In this program, union variable “record” is declared while declaring union itself as shown in the
below program.

#include <stdio.h>

135
#include <string.h>

union student
{
char name[20]; char
subject[20]; float
percentage;
}record;

int main()
{

strcpy(record.name, "Raju");
strcpy(record.subject, "Maths");
record.percentage = 86.50;

printf(" Name : %s \n", record.name); printf(" Subject : %s \n",


record.subject); printf(" Percentage : %f \n", record.percentage); return
0;
}
Output:

Name
Subjec
:
Percen

136
Note:

We can access only one member of union at a time. We can‟t access all member values at the same
time in union. But, structure can access all member values at the same time. This is because, Union
allocates one common storage space for all its members. Where as Structure allocates storage space for all
its members separately.

Difference between structure and union in C:


S.no C Structure C Union

Union allocates one common storage space for all its members.
Structure allocates storage Union finds that which of its member needs high storage space
1 space for all its members over other members and allocates that much space
separately.

Structure occupies higher


2 Union occupies lower memory space over structure.
memory space.

We can access all members of


3 We can access only one member of union at a time.
structure at a time.

4 Structure example: Union example:


struct student union student

{ {
int mark; char int mark; char
name[6]; name[6];
double average; double average;
}; };

For above structure, memory


allocation will be like below.
int mark – 2B For above union, only 8 bytes of memory will be allocated since
5 char name[6] – 6B double data type will occupy maximum space of memory over
double average – 8B other data types.
Total memory allocation = Total memory allocation = 8 Bytes
2+6+8 = 16 Bytes

137
1. Write a C program to initialize an array using functions.
#include<stdio.h> int
main()
int k, c(), d[ ]={c(),c(),c(),c(),c()};
printf(‚\nArray d[] elements are:‛);
for(k=0;k<5;k++)
printf(‚%2d‛,d[k]);
return(0);
}
c()
{
int m,n; m++;
printf(‚\nEnter number d[%d] : ‛,m);
scanf(‚%d‛,&n);
return(n);
}
Output:

Enter Number d[1] : 20


Enter Number d[2] : 30
Enter Number d[3] : 40
Enter Number d[4] : 50
Enter Number d[5] : 60
Array d[] elements are: 20 30 40 50 60

2. Write a C program to interchange array elements of two arrays using functions.


#include<stdio.h>
#include<conio.h> void
main()
{
int read();
void change(int*,int*); int
x,a[5],b[5]; clrscr();

13
8
printf(‚Enter 10 Numbers :‛);
for(x=0;x<10;x++)
{
if(x<5)
a[x]=read(); else
b[x-5]=read();
}
printf(‚\nArray A & B‛);
for(x=0;x<5;x++)
{
printf(‚\n%7d%8d‛,a[x],b[x]);
change(&a[x],&b[x]);
}
printf(‚\nNow A & B‛);
for(x=0;x<5;x++)
{
printf(‚\n%7d%8d‛,a[x],b[x]);
}
}
int read()
{
int x;
scanf(‚%d‛,&x);
return(x);
}
void change(int *a,int *b)
{
int *k;
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
Output:
Enter 10 Numbers:
13
9
0123456789
Array A & B 0
5
1 6
2 7
3 8
4 9
Now A & B 5 0
6 1
7 2
8 3
9 4

14
0
FUNCTION

A function is a self contained block of codes or sub programs with a set of statements that perform
some specific task or coherent task when it is called.

It is something like to hiring a person to do some specific task like, every six months servicing a
bike and hand over to it.

Any ‘C’ program contain at least one function i.e main(). There are basically

two types of function those are

1. Library function

2. User defined function


The user defined functions defined by the user according to its requirement

System defined function can’t be modified, it can only read and can be used. These function are
supplied with every C compiler

Source of these library function are pre complied and only object code get used by the user by linking to
the code by linker

Here in system defined function description:

Function definition : predefined, precompiled, stored in the library

Function declaration : In header file with or function prototype.

Function call : By the programmer

User defined function

Syntax:-

Return type name of function (type 1 arg 1, type2 arg2, type3 arg3) Return type

function name argument list of the above syntax

So when user gets his own function three thing he has to know, these are.

Function declaration

Function definition

Function call

14
1
These three things are represented like

int function(int, int, int); /*function declaration*/

main() /* calling function*/

function(arg1,arg2,arg3);

int function(type 1 arg 1,type2 arg2,type3, arg3) /*function definition/*

Local variable declaration;

Statement;

Return value;

}
Function declaration:-
Function declaration is also known as function prototype. It inform the compiler about three thing, those
are name of the function, number and type of argument received by the function and the type of value
returned by the function.

While declaring the name of the argument is optional and the function prototype always terminated by
the semicolon.

Function definition:-

Function definition consists of the whole description and code of the function. It tells about what

function is doing what are its inputs and what are its out put It consists of two parts function header

and function body

Syntax:-

return type function(type 1 arg1, type2 arg2, type3 arg3) /*function header*/

Local variable declaration;

Statement 1;
14
2
Statement 2;

Return value

The return type denotes the type of the value that function will return and it is optional and if it is
omitted, it is assumed to be int by default. The body of the function is the compound statements or
block which consists of local variable declaration statement and optional return statement.
The local variable declared inside a function is local to that function only. It can’t be used anywhere in
the program and its existence is only within this function.

The arguments of the function definition are known as formal arguments.

Function Call

When the function get called by the calling function then that is called, function call. The compiler
execute these functions when the semicolon is followed by the function name.

Example:-

function(arg1,arg2,arg3);

The argument that are used inside the function call are called actual argument

Ex:-

int S=sum(a, b); //actual arguments

Actual argument

The arguments which are mentioned or used inside the function call is knows as actual argument and
these are the original values and copy of these are actually sent to the called function

It can be written as constant, expression or any function call like Function (x);

Function (20, 30); Function

(a*b, c*d);

Function(2,3,sum(a, b));

Formal Arguments

The arguments which are mentioned in function definition are called formal arguments or dummy
arguments.
These arguments are used to just hold the copied of the values that are sent by the calling function
14
3
through the function call.

These arguments are like other local variables which are created when the function call starts and
destroyed when the function ends.

The basic difference between the formal argument and the actual argument are

1) The
formal argument are declared inside the parenthesis where as the local variable
declared at the beginning of the function block.

2). The formal argument are automatically initialized when the copy of actual arguments are
passed while other local variable are assigned values through the statements.

Order number and type of actual arguments in the function call should be match with the order number
and type of the formal arguments.

Return type

It is used to return value to the calling function. It can be used in two way as return

Or return(expression); Ex:-

return (a);

return (a*b);

return (a*b+c);

st
Here the 1 return statement used to terminate the function without returning any value

Ex:- /*summation of two values*/ int

sum (int a1, int a2);

main()
{

int a,b;

printf(“enter two no”);

scanf(“%d%d”,&a,&b); int

S=sum(a,b);

printf(“summation is = %d”,s);

int sum(intx1,int y1)

{
14
4
int z=x1+y1;

Return z;

Advantage of function

By using function large and difficult program can be divided in to sub programs and solved. When we
want to perform some task repeatedly or some code is to be used more than once at different place in the
program, then function avoids this repeatition or rewritten over and over.

Due to reducing size, modular function it is easy to modify and test

Notes:-

C program is a collection of one or more function.

A function is get called when function is followed by the semicolon.

A function is defined when a function name followed by a pair of curly braces


Any function can be called by another function even main() can be called by other function.

main()
{

function1()

function1()

Statement;

function2;

function 2()

So every function in a program must be called directly or indirectly by the main() function. A function
can be called any number of times.

A function can call itself again and again and this process is called recursion.
14
5
A function can be called from other function but a function can’t be defined in another function

Category of Function based on argument and return type

i) Function with no argument & no return value

14
6
Function that have no argument and no return value is written as:- void function(void);

main()

void function()

Statement;

Example:- void

me();

main()

me();

printf(“in main”);

void me()

printf(“come on”);

Output: come on

inn main

70
ii) Function with no argument but return value
Syntax:-

int fun(void);

main()

int r;

r=fun();

int fun()

reurn(exp);

Example:- int

sum();

main()

int b=sum(); printf(“entered

%d\n, b”);

int sum()

int a,b,s;

71
s=a+b;

return s;

Here called function is independent and are initialized. The values aren’t passed by the calling
function .Here the calling function and called function are communicated partly with each other.

iii ) function with argument but no return value

Here the function have argument so the calling function send data to the called function but called
function dose n’t return value.

Syntax:-

void fun (int,int);

main()

int (a,b);

void fun(int x, int y);

Statement;

72
Here the result obtained by the called function.

iv) function with argument and return value

Here the calling function has the argument to pass to the called function and the called function
returned value to the calling function.

Syntax:-

fun(int,int);

main()

int r=fun(a,b);

int fun(intx,inty)

{
return(exp);

}
Example:

main()
{

int fun(int); int

a,num;

printf(“enter value:\n”); scanf(“%d”,&a)

73
int num=fun(a);

int fun(int x)

++x;

return x;
}

Call by value and call by reference

There are two way through which we can pass the arguments to the function such as call by value and
call by reference.

1. Call by value

In the call by value copy of the actual argument is passed to the formal argument and the operation is
done on formal argument.

When the function is called by ‘call by value’ method, it doesn’t affect content of the actual argument.

Changes made to formal argument are local to block of called function so when the control back to calling
function the changes made is vanish.

Example:-

main()

int x,y;

change(int,int);

74
printf(“enter two values:\n”);

scanf(“%d%d”,&x,&y);

change(x ,y);

printf(“value of x=%d and y=%d\n”,x ,y);

change(int a,int b);

int k;

k=a;

a=b;

b=k;

Output: enter two values: 12 23

Value of x=12 and y=23

2. Call by reference

Instead of passing the value of variable, address or reference is passed and the function operate on
address of the variable rather than value.

Here formal argument is alter to the actual argument, it means formal arguments calls the actual
arguments.

Example:-

void main()

75
{

int a,b;

change(int *,int*); printf(“enter two

values:\n”); scanf(“%d%d”,&a,&b);

change(&a,&b);

printf(“after changing two value of a=%d and b=%d\n:”a,b);

change(int *a, int *b)

int k;

k=*a;

*a=*b;

*b= k;

printf(“value in this function a=%d and b=%d\n”,*a,*b);

Output: enter two values: 12 32

Value in this function a=32 and b=12

After changing two value of a=32 and b=12

So here instead of passing value of the variable, directly passing address of the variables. Formal argument
directly access the value and swapping is possible even after calling a function.

76
Recursion

When function calls itself (inside function body) again and again then it is called as recursive
function. In recursion calling function and called function are same. It is powerful technique of writing
complicated algorithm in easiest way. According to recursion problem is defined in term of itself. Here
statement with in body of the function calls the same function and same times it is called as circular
definition. In other words recursion is the process of defining something in form of itself.

Syntax:

main ()

rec(); /*function call*/ rec();

rec();

Ex:- /*calculate factorial of a no.using recursion*/ int

fact(int);

void main()

80 *Under revision
{

int num;

printf(“enter a number”);

scanf(“%d”,&num);

f=fact(num);

printf(“factorial is =%d\

n”f);

fact (int num)

If (num==0||num==1)

retu

rn

1;

else

return(num*fact(num-1));

MCQ
1.All keywords in C are in ____________
a) LowerCase letters
b) UpperCase letters
c) CamelCase letters
d) None of the mentioned
Answer: a
2. Which of the following is not a valid C variable name?
a) int number;
b) float rate; 81 *Under revision
c) int variable_count;
d) int $main;
Answer: d
3. Who invented C Language.?
A) Charles Babbage
B) Grahambel
C) Dennis Ritchie
D) Steve Jobs
ANS: A
4. C Language is a successor to which language.?
A) FORTRAN
B) D Language
C) BASIC
D) B Language
ANS :D
5. C language was invented in the year.?
A) 1999
B) 1978
C) 1972
D) 1990
ANS :C
6. A C program is a combination of.?
A) Statements
B) Functions
C) Variables
D) All of the above
ANS :D
7. Which of the following special symbol allowed in a variable name?

A.* (asterisk)
B.| (pipeline)
C.- (hyphen)
D._ (underscore)
Answer: Option D
82 *Under revision
8. How would you round off a value from 1.66 to 2.0?

A.ceil(1.66)
B.floor(1.66)
C.roundup(1.66)
D.roundto(1.66)
Answer: Option A
9. The keyword used to transfer control from a function back to the calling function is

A.switch
B.goto
C.go back
D.return
Answer: Option D
10.
In C, if you pass an array as an argument to a function, what actually gets passed?

A. Value of elements in array


B. First element of the array
C. Base address of the array
D. Address of the last element of array
Answer: Option C

83 *Under revision

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy