You are on page 1of 85

CHAPTER 1: Introduction to C Language

Overview of C language
C is a structured programming language developed by Dennis Ritchie in 1973
at Bell Laboratories. It is one of the most popular computer languages today
because of its structure, high-level abstraction, machine independent feature.
C language was developed with UNIX operating system, so it is strongly
associated with UNIX, which is one of the most popular network operating
system in use today and heart of internet data superhighway.

C Character Set:

Each C Program is set of statements and each statement is set of different c


programming characters. The valid character set of C language is listed below:

Types Character Set


Lowercase Letters a-z
Uppercase Letters A to Z
Digits 0-9
,< >. _( ); $:%[ ] #?
Special Characters
' &{ }" ^!*/ |- \~+
White Spaces Tab Or New line Or Space

Variables & Identifiers


a) Identifiers

A C identifier is a name used to identify a variable, function, or any other user-


defined item. Here are some examples of acceptable identifiers

mohd zara abc move_name a_123


myname50 _temp j a23b9 retVal

b) A variable is nothing but a name given to a storage area that our


programs can manipulate. Each variable in C has a specific type, which
determines the size and layout of the variable's memory; the range of values
that can be stored within that memory; and the set of operations that can be
applied to the variable.

Built in data types

Page 1
variable declaration

A variable definition tells the compiler where and how much storage to create
for the variable. A variable definition specifies a data type and contains a list
of one or more variables of that type as follows

type variable_list;

Here, type must be a valid C data type including char, int, float, double or
any user-defined object; and variable_list may consist of one or more
identifier names separated by commas. Some valid declarations are shown
here

int i, j, k;
char c, ch;
float f, salary;
double d;

The line int i, j, k; declares and defines the variables i, j, and k; which
instruct the compiler to create variables named i, j and k of type int.

Variable Initialization

Variables can be initialized (assigned an initial value) in their declaration. The


initializer consists of an equal sign followed by a constant expression as
follows

type variable_name = value;

Some examples are

Page 2
int d = 3, f = 5; // definition and initializing d and f.
float z = 2.2; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

Note : For definition without an initializer: the initial value of all other
variables are undefined.

Keywords

The following list shows the reserved words in C. These reserved words may
not be used as constants or variables or any other identifier names.

auto else long switch


break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double

constants & literals

Constants in C refer to fixed values that program cannot change during the
time of execution. Constants are also known as literals.

A constant can be of any data type like character constant, integer


constant, string constant etc.

For Example : 'A', 1234, 123.5, "TechCrashCourse"

C Constants are like normal variables, the only difference is, their values
cannot be changed by the program once they are defined.

Operators in C

Operators are the symbol which operates on value or a variable. For example:
+ is a operator to perform addition.

C programming language has wide range of operators to perform various operations.


For better understanding of operators, these operators can be classified as:

Operators in C programming
Arithmetic Operators +, -, /, *, %
Increment and Decrement Operators ++, --
Assignment Operators =, +=, -=, *=, /=

Page 3
Relational Operators >, >= , ==, <, <=, !=
Logical Operators &&, ||, !
Conditional Operators ?:
Bitwise Operators &, |, >>, <<, ^,
Special Operators ., ,,

Evaluation of expression

An Arithmetic expression without parentheses will be evaluated from left to


right using the rules of precedence of operators. There are two different
priority levels of arithmetic operators:

High priority * / %

Low priority + -

The evaluation procedure includes two passes. In pass1 High priority


operators are evaluated & in pass2 low priority operators are evaluated.

Basic input & output statements in C

C programming provides a set of built-in functions for input & output


operations. They can be broadly divided into two categories:

i) Unformatted function: These are used to accept or print only character


or string data.

a) Input function: For character getchar(), getch(), getche()

For string gets()

b) Output function: For character putchar(), putch(), putche()

For string puts()

ii) Formatted function: These are used to accept or print any type of data.

a) Input function: scanf()


b) Output function: printf()

Page 4
5 marks questions

Q1. What is a token? Give example for each of token.

A smallest individual unit in c program is known as C Tokens. Tokens are


either keyword, identifier, constant, variable or any symbol which has some
meaning in C language. A C program can also be called as collection of various
tokens.

The various C tokens are listed below:

a) Keywords: These are reserved words which have predefined meanings &
those meanings can not be changed.

e.g. int, for, break etc

b) Identifiers: In C language identifiers are the names given to variables,


constants, functions and user-define data.

e.g. next, fact etc

c) Constants: C Constants are fixed values, their values cannot be changed


by the program once they are defined.

e.g. const pie = 3.14;

d) Strings: A string is actually one-dimensional array of characters in C


language. It is a set of characters enclosed within set of double quotes.

e.g. name = hello

e) Special Symbols: C language include special characters or symbols other


than operators.

e.g. { }, [ ] etc

f) Operators: Operators are the symbol which operates on value or a


variable. C language includes rich set of operators.

e.g. +, -. > / etc

Q2. What is a constant? Explain different types of C constants.

C Constants are fixed values, their values cannot be changed by the program
once they are defined.

Constants can be broadly divided into 2 types

Page 5
a) Numeric constants b) Character constants

a) Numeric constants include i) integer constants & ii) Real constants

i) Integer constants refers to sequence of digits. There are 3 types

Decimal constants e.g. 234, +2, -120

Octal constants - e.g. 012, 034, 0567 (Begins with 0)

Hexa decimal constants. e.g 0x12, 0x4AB, 0xFF (Begins with 0x)

ii) Real constants refers to sequence of digits followed by fractional part.

e.g 0.12, 12.45, -3.13E5, 0.56E-4

b) Character constants includes i) Single character constants & ii)


string constants

i) Single character constants refers to a single character enclosed with


in a pair of single quotes.

e.g. a, +, etc

ii) String constants refers to a set character enclosed with in a pair of


double quotes.

e.g. hello, 0987 etc

Q3. What is a variable? Write the rules & guidelines for naming
variables?

A variable is a name that may be used to store a data value. Unlike constant,
variables

are changeable, we can change value of a variable during execution of a


program.

Rules to define variable name

1. Variable name must be upto 32 characters.


2. Variable name must not start with a digit.
3. Variable name can consist of alphabets, digits and special symbols like
underscore _.
4. Blank or spaces are not allowed in variable name.
5. Keywords are not allowed as variable name.

Q4. Define the term Identifier. Give an example.

Page 6
A C identifier is a name used to identify a variable, function, or any other user-
defined item. Here are some examples of acceptable identifiers

mohd zara abc move_name a_123


myname50 _temp j a23b9 retVal

Rules for naming identifiers

1. Name of identifier includes alphabets, digit and underscore.

2. First character of any identifier must be either alphabets or underscore.

3. Name of identifier cannot be any keyword

4. Name of identifier is case sensitive i.e. num and Num are two different
variables.

5. Only first 32 characters are significant of identifier name.

6. Name of identifier can not include any blank spaces or special character
except under score

Q5. List the basic data types with byte specification.

There are five basic data types :


int - integer: a whole number.
float - floating point value: i.e. a number with a fractional part.
double - a double-precision floating point value.
char - a single character.
void - valueless special purpose type are used as function prototype

Type Storage size Value range


-32,768 to 32,767 or
int 4 bytes -2,147,483,648 to
2,147,483,647
Type Storage size Value range Precision
6 decimal
float 4 byte 1.2E-38 to 3.4E+38
places
2.3E-308 to 15 decimal
double 8 byte
1.7E+308 places
char 1 byte -128 to 127 or 0 to 255

Q6. List the hierarchy (precedence) rules of arithmetic operators.

An Arithmetic expression without parentheses will be evaluated from left to


right using the rules of precedence of operators. There are two different
priority levels of arithmetic operators:

High priority * / %

Page 7
Low priority + -

The evaluation procedure includes two passes. In pass1 High priority


operators are evaluated & in pass2 low priority operators are evaluated.

Q7 Evaluate the expression: 2 + 1 * 3 4 % 3 * 1 + 16 / 2 % 5

Q8. List the important features of C language.

Features of C language
It is a robust language with rich set of built-in functions and operators
that can be used to write any complex program.
The C compiler combines the capabilities of an assembly language with
features of a high-level language.
Programs Written in C are efficient and fast. This is due to its variety of
data type and powerful operators.
It is many time faster than BASIC.
C is highly portable this means that programs once written can be run
on another machines with little or no modification.
Another important feature of C program, is its ability to extend itself.
A C program is basically a collection of functions that are supported by
C library. We can also create our own function and add it to C library.
C language is the most widely used language in operating systems and
embedded system development today.

Q9. Give a general form of ternary operator, explain with an


example.

It is also known as conditional operator and used to evaluate conditional


expression.

Page 8
Syntax : epr1 ? expr2 : expr3;

If epr1 Condition is true ? Then value expr2 is evaluated : Otherwise value


expr3 is evaluated.

Program to display number of days in February

#include <stdio.h>
int main()
{
char feb;
int days;
printf("Enter l if the year is leap year otherwise enter 0: ");
scanf("%c",&feb);
days=(feb=='l')?29:28;
/*If test condition (feb=='l') is true, days will be equal to 29. */
/*If test condition (feb=='l') is false, days will be equal to 28. */
printf("Number of days in February = %d",days);
return 0;
}

Output

Enter l if the year is leap year otherwise enter n:


l
Number of days in February = 29

Q10. Explain simple assignments in C. Give an example.

The most common assignment operator is =. This operator assigns the value
in right side to the left side variable. To the right of an assignment operator
there can be a constant or variable or an arithmetic expression. But to the left
there should be only one variable. For example:

var=5 //5 is assigned to var


a=c; //value of c is assigned to a
5=c; // Error! 5 is a constant.

Operator Example Same as


= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b

Q11. List Input & Output function.

C programming provides a set of built-in functions for input & output


operations. They can be broadly divided into two categories:

Page 9
i) Unformatted function: These are used to accept or print only character
or string data.

a) Input function: For character getchar(), getch(), getche()

For string gets()

b) Output function: For character putchar(), putch(), putche()

For string puts()

ii) Formatted function: These are used to accept or print any type of data.

c) Input function: scanf()


d) Output function: printf()

Q12. Explain printf() statement with an example.

printf() is the standard output function used to display output on monitor in


the specified format. Using printf() both messages and values can be printed.

Syntax to print messages: printf( message );

e.g. printf( Welcome to programming with C );

Syntax to print values: printf( format specifier ,variable name);

e.g. printf(%d%f%c,v1,v2,v3);

Syntax to print both messages & value:

printf(message format specifier ,variable name);

e.g. . printf(The out put = %d%f%c,v1,v2,v3);

The various format specifiers generally used in c are listed below:

Data type Format Spefier(or control string)


%c
char (single character)

int (signed integer) %d (%i)

float or double (exponential format) %e (%E

float or double (signed decimal) %f

Page 10
int (unsigned octal value) %o

Char(String or array of char sequence %s


of characters)

int (unsigned decimal) %u

int (unsigned hex value) %x (%X)

Q13. Explain scanf() statement with an example.

scanf() is the standard input function used to accept input from key board in
the specified format.

Syntax: scanf(format specifier, &variable name):

e.g. scanf(%d%c%f,&v1,&v2,&v3);

Where & is called as address operator, which specify the address of the
location where data is to be stored.

Note: For format specifier refer Q12 (5 Marks)

Q14. Write a program to find sum & average of 3 numbers.

Void main()

int a,b,c,sum;

float avg;

printf(Enter 3 numbers

scanf(%d%d%d,&a,&b,&c);

sum = a + b + c;

avg = sum / 3.0;

printf(sum = %d , average = %f,sum,avg);

Page 11
}

10 Marks:

Q1. With general syntax explain formatted input & output


statements. Give example for each.

Refer Q12 & Q13 (5 marks)

Q2. Define the following with an example: i) Increment operator

ii) Decrement operator

i) Increment operator: In C, ++ is called increment operator. It is a unary


operator, i.e, used on single operand. ++ adds 1 to operand. There are two
types:

a) Prefix increment operator ( ++var) : ++var will increment the value of var
and then return it . e.g. if a=5 then ++a will return a=6;

b) Postfix increment operator (var++) : var++ operator will return the value of
operand first and then only increment it. e.g. if a=5 then a++ will return a=5;

ii) Decrement operator : : In C, -- is called decrement operator. It is a


unary operator, i.e, used on single operand. -- subtracts 1 from the operand.
There are two types:

a) Prefix decrement operator ( --var) : --var will decrement the value of var and
then return it . e.g. if a=5 then --a will return a=4;

b) Postfix decrement operator (var--) : var-- operator will return the value of
operand first and then only decrement it. e.g. if a=5 then a-- will return a=5;

. This can be demonstrated by an example:

#include <stdio.h>
int main()
{
int c=2,d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by
1 to 3.
printf("%d",++c); //this statement increments 1 to c then, only c is
displayed.
return 0;
}

Output

2
4

Page 12
Q3. Explain the basic data types of C language.

There are five basic data types :


int - integer: a whole number.
float - floating point value: ie a number with a fractional part.
double - a double-precision floating point value.
char - a single character.
void - valueless special purpose type which we will examine closely in
later sections.

Integer Types

The following table provides the details of standard integer types with their
storage sizes and value ranges

Type Storage size Value range


-32,768 to 32,767 or -2,147,483,648 to
int 4 bytes
2,147,483,647
unsigned int 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long int 8 bytes -2,147,483,648 to 2,147,483,647
unsigned long int 8 bytes 0 to 4,294,967,295

Floating-Point Types

The following table provide the details of standard floating-point types with
storage sizes and value ranges and their precision

Type Storage size Value range Precision


float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Character Types

Type Storage size Value range


char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127

Page 13
Q4. Define the following with an example: a) C Keyword b) variable
c) Constants

d) Format Specifier e) Arithmetic Expression.

a) Keywords: These are reserved words which have predefined meanings &
those meanings can not be changed.

e.g. int, for, break etc

b) Variable: A variable is a name that may be used to store a data value.


Unlike constant, variables are changeable; we can change value of a
variable during execution of a program.

e.g. sum, a, n1 etc

c) Constants: C Constants are fixed values, their values cannot be changed


by the program once they are defined.

e.g. const pie = 3.14;

d) Format Specifier: They are used to specify various data types & their
formats in printf() & scanf() functions.

e.g. for integer data types - %d, %10d

float data type - %f, %7.3f etc

e) Arithmetic Expression: It is a combination of variables, constants and


operators arranged as per the syntax of the language.

e.g. sum = a + b / (c 2) * 3 .4;

Page 14
Q5. Define the following terms. Five one example each.

a) Constant b) Keyword c) Relational Expression d) Assignment


Statement

e) Conditional Operator

a) Constants: C Constants are fixed values, their values cannot be changed


by the program once they are defined.

e.g. const pie = 3.14;

b) Keywords: These are reserved words which have predefined meanings &
those meanings can not be changed.

e.g. int, for, break etc

c) Relational Expression: It contains only one relational operator & has


the following syntax.
Exp1 relational operator exp2
Where exp1 & exp2 are constants or variables or any arithmetic expression.
e.g. a>b, a<0, (a+b) ==(b+c)

d) Assignment Statement : It contains only one assignment operator.The


most common assignment operator is =. This operator assigns the value in
right side to the left side variable. To the right of an assignment operator there
can be a constant or variable or an arithmetic expression. But to the left there
should be only one variable

e.g. a=b, sum=0, x=a+b/c etc

e) Conditional Operator: It is also known as ternary operator and used to


evaluate conditional expression.

Syntax : epr1 ? expr2 : expr3;

If epr1 Condition is true ? Then value expr2 is evaluated : Otherwise value


expr3 is

e.g. large = a?b:a:b;

Q6. WAP to swap the values of two variables without using third
variable.

#include <stdio.h>
int main()
{
int a, b;
printf("Enter value of a: ");

Page 15
scanf("%d",&a);
printf("Enter value of b: ");
scanf("%d",&b);
b=a+b; /* a=1 & b=2 then b=a+b=3*/
a=b-a; /* a=3-1 = 2, i.e. a=2 */
b=b-a; /* b = 3 2 = 1 i.e. b=1 */
printf("\nAfter swapping, value of a = %d\n", a);
printf("After swapping, value of b = %d", b);
return 0;
}

Output

Enter value of a: 1
Enter value of b: 2

After swapping, value of a = 2


After swapping, value of b = 1

Q7. Explain basic structure of C program.

1. Documentation section : The documentation section consists of a set


of comment lines giving the name of the program, the author and other
details, which the programmer would like to use later.
2. Link section : The link section provides instructions to the compiler to

Page 16
link functions from the system library.
3. Definition section : The definition section defines all symbolic
constants.
4. Global declaration section : There are some variables that are used
in more than one function. Such variables are called global variables and
are declared in the global declaration section that is outside of all the
functions. This section also declares all the user-defined functions.
5. main () function section : Every C program must have one main
function section. This section contains two parts; declaration part and
executable part
6. Declaration part : The declaration part declares all the variables used
in the executable part.
7. Executable part : There is at least one statement in the executable
part. These two parts must appear between the opening and closing
braces. The program execution begins at the opening brace and ends at
the closing brace. The closing brace of the main function is the logical
end of the program. All statements in the declaration and executable part
end with a semicolon.
8. Subprogram section : The subprogram section contains all the user-
defined functions that are called in the main () function. User-defined
functions are generally placed immediately after the main () function,
although they may appear in any order.

All section, except the main () function section may be absent when they are
not required.

Q8. WAP to find largest of three numbers using conditional


operator.

#include <stdio.h>
int main(){
int a, b, c, large;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
large = a;
large = large > b ? large : b;
large = large > c ? large : c;
printf("Largest number = %d", large);
return 0;
}

Output

Enter three numbers: 3 4 5

Largest number = 5

Q9. WAP to swap the values of two variables using third variable.

#include <stdio.h>
int main()

Page 17
{
float a, b, temp;
printf("Enter value of a: ");
scanf("%f",&a);
printf("Enter value of b: ");
scanf("%f",&b);
temp = a; /* Value of a is stored in variable temp */
a = b; /* Value of b is stored in variable a */
b = temp; /* Value of temp(which contains initial value of a) is stored in
variable b*/
printf("\nAfter swapping, value of a = %.2f\n", a);
printf("After swapping, value of b = %.2f", b);
return 0;
}

Output

Enter value of a: 1.20


Enter value of b: 2.45

After swapping, value of a = 2.45


After swapping, value of b = 1.2

Q10. WAP to find area & circumference of a circle.

#include <stdio.h>
int main()
{
float r,area,circum;
printf("Enter value of radius: ");
scanf("%f",&r);
area = 2*3.14 * r;
circum = 3.14 * r * r;
printf("\nArea of a circle = %.2f\n", area);
printf("Circumference of circle = %.2f", circum);
return 0;
}

Output

Enter value of a radius: 3

Area of a circle = 18.84

Circumference of circle = 28.26

Page 18
CHAPTER 2:
DECISION MAKING, BRANCHING & LOOPING
Logical operators are used to combine expressions containing relation operators. In C,
there are 3 logical operators:

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

Relational operators checks relationship between two operands. If the relation is true,
it returns value 1 and if the relation is false, it returns value 0.
Operator Meaning
== Equal to
> Greater than
< Less than
!= Not equal to
>= Greater than or equal to
<= Less than or equal to

Decision making with if statement

The if statement may be implemented in different forms depending on the


complexity of conditions to be tested. The different forms are,

1. Simple if statement
2. If....else statement
3. Nested if....else statement
4. else if statement

Loops in C Lanugage

In any programming language, loops are used to execute a set of statements


repeatedly until a particular condition is satisfied.

There are 3 type of Loops in C language

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

5 Marks:

Page 19
Q1. Explain different logical operators with examples.

Logical operators are used to combine expressions containing relation operators. In C,


there are 3 logical operators:

Meaning of
Operator Example
Operator
If c=5 and d=2 then,((c==5) && (d>5)) returns
&& Logical AND
false.
|| Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) returns true.
! Logical NOT If c=5 then, !(c==5) returns false.

Q2. Explain different logical operators with examples.

Relational operators checks relationship between two operands. If the relation


is true, it returns value 1 and if the relation is false, it returns value 0. For
example:

a>b

Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then,
it returns 0.

Relational operators are used in decision making and loops in C programming.

Operator Meaning of Operator Example


== Equal to 5==3 returns false (0)
> Greater than 5>3 returns true (1)
< Less than 5<3 returns false (0)
!= Not equal to 5!=3 returns true(1)
>= Greater than or equal to 5>=3 returns true (1)
<= Less than or equal to 5<=3 return false (0)

Q3. Write the general syntax of if & if else statement.

if statement

The general form of a simple if statement is,

if( expression )
{
statement-inside;
}
statement-outside;

Page 20
If the expression is true, then 'statement-inside' it will be executed, otherwise
'statement-inside' is skipped and only 'statement-outside' is executed.

if...else statement

The general form of a simple if...else statement is,

if( expression )
{
statement-block1;
}
else
{
statement-block2;
}

If the 'expression' is true, the 'statement-block1' is executed, else 'statement-


block1' is skipped and 'statement-block2' is executed.

Q4. Compare while & do while statement.

Sl no While Do_while
1 Entry controlled loop Exit controlled loop
2 The while statement The do-while statement
verifies the condition executes the first
before entering into the iteration without
loop to see whether the checking the condition, it
next loop iteration should verifies the condition
occur or not. after finishing each
iteration.
3 The while statement will The do-while statement
not execute not even once will always execute the
if the condition is false at body of a loop at least
the beginning. once.
4 The test condition is The test condition is
placed at the begging of placed at the end of the
the loop loop

Q5. Compare if & if else statement.

Sl no if If - else
1 The body of if statement The body of if - else
includes only true part statement includes both
true part & false part
2 The body of if statement In if else statement, if
is executed, if the the condition is true the if
condition is true. part is executed or if the
Otherwise program condition is false the else
control comes out of the part is executed. then the
if statement program control comes

Page 21
out of the if statement

Q6. Illustrate & explain nested if else statement.

The general form of a nested if...else statement is,

if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{
statement-block 3;
}

if 'expression' is false the 'statement-block3' will be executed, otherwise it


continues to perform the test for 'expression 1' . If the 'expression 1' is true the
'statement-block1' is executed otherwise 'statement-block2' is executed.

Example :

#include <stdio.h>
#include <conio.h>
void main( )
{
int a,b,c;
clrscr();
printf("enter 3 number");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if( a > c)
{
printf("a is greatest");
}
else
{
printf("c is greatest");
}
}
else

Page 22
{
if( b> c)
{
printf("b is greatest");
}
else
{
printf("c is greatest");
}
}
getch();
}

Q7. Illustrate & explain else - if ladder.

The general form of else-if ladder is,

if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;

The expression is tested from the top(of the ladder) downwards. As soon as
the true condition is found, the statement associated with it is executed.

Example :

#include <stdio.h>
#include <conio.h>
void main( )
{
int a;
printf("enter a number");
scanf("%d",&a);
if( a%5==0 && a%8==0)
{
printf("divisible by both 5 and 8");
}
else if( a%8==0 )
{

Page 23
printf("divisible by 8");
}
else if(a%5==0)
{
printf("divisible by 5");
}
else
{
printf("divisible by none");
}
getch();
}

Q8. WAP to find largest of three numbers.

/* C program to find largest number using if...else statement */

#include <stdio.h>
int main(){
float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if (a>=b)
{
if(a>=c)
printf("Largest number = %.2f",a);
else
printf("Largest number = %.2f",c);
}
else
{
if(b>=c)
printf("Largest number = %.2f",b);
else
printf("Largest number = %.2f",c);
}
return 0;
}

Q9. With general syntax, explain the significance of break &


continue statements in loops.

Jumping Out of Loops

Sometimes, while executing a loop, it becomes necessary to skip a part of the


loop or to leave the loop as soon as certain condition becomes true, that is
called jumping out of loop. C language allows jumping from one statement to
another within a loop as well as jumping out of the loop.

1) break statement

Page 24
When break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following
the loop.

2) continue statement

It causes the control to go directly to the test-condition and then continue the
loop process. On encountering continue, cursor leave the current cycle of loop,
and starts with the next cycle.

Q10. Define the following: a) break b) goto & label c) continue.

a) 1) break statement: Refer Q9

Page 25
b) goto & label statement: In C programming, goto statement is used for
altering the normal sequence of program execution by transferring control to
some other part of the program with out checking for any condition.

Syntax of goto statement


goto label;
.............
.............
.............
label:
statement;

In this syntax, label is an identifier. When, the control of program reaches to


goto statement, the control of the program will jump to the label: and executes
the code below it.

c) continue statement: Refer Q9

Q11. List & explain any two unconditional statements / jumping


statement.

Refer Q9 & Q10

Q12. Explain Relational & logical operators.

Refer Q1 & Q2

Q13. With general syntax explain the need of break statement in


switch.

Switch statement

Switch statement is used to solve multiple option type problems for menu like
program, where one value is associated with each option. The expression in
switch case evaluates to return an integral value, which is then compared to
the values in different cases, where it matches that block of code is executed, if
there is no match, then default block is executed. The general form of switch
statement is,

switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;

Page 26
case value-4:
block-4;
break;
default:
default-block;
break;
}
1. It isn't necessary to use break after each block, but if you do not use it,
all the consecutive block of codes will get executed after the matching
block.
2. int i = 1;
3. switch(i)
4. {
5. case 1:
6. printf("A"); // No break
7. case 2:
8. printf("B"); // No break
9. case 3:
10. printf("C");
11. break;
12. }

Output : A B C

Q14. Give general syntax & an example of do while loop


statement. Why it is called as exit controlled loop?

do while loop

In some situations it is necessary to execute body of the loop before testing the
condition. Such situations can be handled with the help of do-while loop. do
statement evaluates the body of the loop first and at the end, the condition is
checked using while statement. General format of do-while loop is,

do
{
....
.....
}
while(condition);

Example : Program to print first ten multiple of 5.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,i;
a=5;
i=1;

Page 27
do
{
printf("%d\t",a*i);
i++;
}
while(i <= 10);
getch();
}
output

5 10 15 20 25 30 35 40 45 50

Do while loop is called exit controlled loop because

Q15. Differentiate between break & continue statements.

Sl break continue
no
1 A break can appear in both A continue can appear only in loop (for,
switch and loop (for, while, do) while, do) statements.
statements.

2 A break causes the switch or loop A continue doesn't terminate the loop, it
statements to terminate the causes the loop to go to the next
moment it is executed. Loop or iteration. All iterations of the loop are
switch ends abruptly when executed even if continue is
break is encountered. encountered. The continue statement is
used to skip statements in the loop
that appear after the continue.

3 The break statement can be The continue statement can appear only
used in both switch and loop in loops. You will get an error if this
statements. appears in switch statement.

4 When a break statement is When a continue statement is


encountered, it terminates the encountered, it gets the control to the
block and gets the control out next iteration of the loop.
of the switch or loop.

5 A break causes the innermost A continue inside a loop nested within a


enclosing loop or switch to be switch causes the next loop iteration.
exited immediately.

Page 28
Q16. WAP to check whether the given number is odd or even.

Write a C program to check whether a number entered by user is


even or odd

#include <stdio.h>
int main()
{
int num;
printf("Enter a number you want to check.\n");
scanf("%d",&num);
if((num % 2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
return 0;
}

Output 1

Enter a number you want to check.


25
25 is odd.

Output 2

Enter a number you want to check.


2
2 is even.

Q17. Explain logical operators with example.

Refer Q1

Q18. Explain relational operators with example.

Refer Q2.

Q19. Explain for statement with example.

for loop

for loop is used to execute a set of statements repeatedly until a particular


condition is satisfied. we can say it an open ended loop. General format is,

for(initialization; condition ; increment/decrement)


{
statement-block;
}

Page 29
In for loop we have exactly two semicolons, one after initialization and second
after condition. In this loop we can have more than one initialization or
increment/decrement, separated using comma operator. for loop can have
only one condition.

Program to print natural number from 1 to 10

#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
for(x=1; x<=10; x++)
{
printf("%d\t",x);
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10

10 marks

Q1. Explain if else statement with an example.


For syntax refer Q3

Example to print largest of two numbers

#include <stdio.h>
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
Output:
y is greater than x

Q2. Explain nested for loop with the general syntax.

Nested for loop

Page 30
one for loop inside another for loop. Basic syntax is,

for(initialization; condition; increment/decrement)


{
for(initialization; condition; increment/decrement)
{
statement ;
}
}

Q3. Write a program to find roots of quadratic equation using


switch statement.

/* C Program to find roots of a quadratic equation when coefficients are


entered by user. */
/* Library function sqrt() computes the square root. */

#include <stdio.h>
#include <math.h> /* This is needed to use sqrt() function.*/
int main()
{
Int n;
float a, b, c, determinant, r1,r2, real, imag;
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
determinant=b*b-4*a*c;

if (determinant>0)
{
N= 1;
}
else if (determinant==0)
{
N = 2;
}
else
{
N= 3;
}

Switch(n)
{
Case 1: r1= (-b+sqrt(determinant))/(2*a);
r2= (-b-sqrt(determinant))/(2*a);
printf("Roots are: %.2f and %.2f",r1 , r2);
break;
case 2: r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f", r1, r2);
break;
case 3: real= -b/(2*a);
imag = sqrt(-determinant)/(2*a);

Page 31
printf("Roots are: %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag);
}
return 0;
}

Output 1

Enter coefficients a, b and c:


2.3
4
5.6
Roots are: -0.87+1.30i and -0.87-1.30i

Output 2

Enter coefficients a, b and c:


4
1
0
Roots are: 0.00 and -0.25

Q4. Explain the switch statement with syntax, with an example


Refer Q13 (5 marks)

Q5. Explain entry controlled & exit controlled loop with an


example.

while loop can be addressed as an entry control loop. It is completed in 3


steps.

Variable initialization.( e.g int x=0; )


condition( e.g while( x<=10) )
Variable increment or decrement ( x++ or x-- or x=x+2 )

Syntax :

variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}

Example : Program to print first 10 natural numbers

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

Page 32
int x;
x=1;
while(x<=10)
{
printf("%d\t", x);
x++;
}
getch();
}
output
1 2 3 4 5 6 7 8 9 10

For exit controlled loop refer Q14 ( 5 marks)

Q6. WAP to find the number & sum of all numbers greater than 150
& less than 250 which are divisible by 8.

#include <stdio.h>
int main()
{
int i,sum=0,
for(i=150; i<=250; i++)
{
if(i%8 == 0)
sum = sum+I;
}
printf( sum = %d,sum);
return 0;
}

Q7. WAP to find largest of 3 numbers using if else statement.


/* C program to find largest number using if...else statement */

#include <stdio.h>
int main(){
float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if (a>=b)
{
if(a>=c)
printf("Largest number = %.2f",a);
else
printf("Largest number = %.2f",c);
}
else
{
if(b>=c)
printf("Largest number = %.2f",b);
else

Page 33
printf("Largest number = %.2f",c);
}
return 0;
}

Enter three numbers: 12.2


13.452
10.193
Largest number = 13.45

Q8. WAP to find smallest of 3 numbers using nested if else


statement.

/* C Program to find smallest number using nested if...else statement */

#include <stdio.h>
int main(){
float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if(a<=b && a<=c)
printf("Smallest number = %.2f", a);
else if(b<=a && b<=c)
printf("Smallest number = %.2f", b);
else
printf("Smallest number = %.2f", c);
return 0;
}

Enter three numbers: 12.2


13.452
10.193
Largest number = 13.45

Q9. WAP to check whether the given number is prime or not.

/* 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;
}

Page 34
}
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.

Q10. WAP to generate Fibonacci series.

/* Displaying Fibonacci sequence up to nth term where n is entered by user. */


#include <stdio.h>
int main()
{
int count, n, t1=0, t2=1, display=0;
printf("Enter number of terms: ");
scanf("%d",&n);
printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */
count=2; /* count=2 because first two terms are already displayed. */
while (count<n)
{
display=t1+t2;
t1=t2;
t2=display;
++count;
printf("%d+",display);
}
return 0;
}

Output

Enter number of terms: 10


Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+

Q11. WAP to find the sum of n natutal numbers.

#include <stdio.h>
int main(){
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */

Page 35
}
printf("Sum=%d",sum);
return 0;
}

Output

Enter the value of n.


19
Sum=190

Q12. WAP to find reverse of a given number.

#include <stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
printf("Reversed Number = %d",reverse);
return 0;
}

Output

Enter an integer: 2345


Reversed Number = 5432

Q13. WAP to count even & odd from n natural numbers.

#include <stdio.h>
int main()
{
int num,i,ocount,ecount,n;
printf("Enter a number \n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
if((i%2)==0) //checking whether remainder is 0 or not.
Ecount = ecount + 1;
Else
Ocount = ocount + 1;

Page 36
}
Printf(Number of even numbers = %d,ecount);
Printf(number of odd numbers = %d,ocount);

return 0;
}

Page 37
CHAPTER 3: FUNCTIONS
Define function.

In programming, a function is a segment that groups code to perform a


specific task.

Types of C functions

There are two types of functions in C programming:

Library function : Library functions are the in-built function in C


User defined function : C allows programmer to define their own
function according to their requirement.

Defining a Function

The general form of a function definition in C programming language is as


follows

return_type function_name( parameter list )


{
body of the function
}

Types of parameters

There are 2 types of parameters

1. actual parameter
2. Formal parameter

Passing arguments to a function

There are two ways of passing arguments to function

1. call by value
2. call by reference

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 it cannot be accessed.
There are three places where variables can be declared in C programming
language

Inside a function or a block which is called local variables.


Outside of all functions which is called global variables.

Page 38
5 MARKS:

Q1. Define function. List different types of functions.

In programming, a function is a segment that groups code to perform a


specific task.

A C program has at least one function main(). Without main() function, there is
technically no C program.

Types of C functions

There are two types of functions in C programming:

Library function
User defined function

Library function

Library functions are the in-built function in C programming system. For


example:

main()

- The execution of every C program starts from this main() function.

printf()

- prinf() is used for displaying output in C.

scanf()

- scanf() is used for taking input in C.

User defined function

C allows programmer to define their own function according to their


requirement. These types of functions are known as user-defined functions.
Suppose, a programmer wants to find factorial of a number and check whether
it is prime or not in same program. Then, he/she can create two separate user-
defined functions in that program: one for finding factorial and other for
checking whether it is prime or not, which are called in the main() function.

Q2. What are the advantages of functions.

Advantages of user defined functions


1. User defined functions helps to decompose the large program into
small segments which makes programmer easy to understand,
maintain and debug.

Page 39
2. If repeated code occurs in a program. Function can be used to include
those codes and execute when needed by calling that function.
3. Programmer working on large project can divide the workload by
making different functions.

Q3. List the difference between actual parameters & formal


parameters.

Sl Actual parameters Formal parameters


no
1 The parameters that are passed The formal parameters are the
in a function call are called parameters in a function declaration.
actual arguments.
2 These parameters are defined The scope of formal parameters is local
in the calling function. to the function definition in which they
are used.

3 These are actual parameters Formal parameters are a copy of the


actual parameters.
4 A change in actual parameters A change in formal parameters would
would be reflected in the not be reflected in the actual
formal parameters. parameters.

Q4. Explain scope & life time of a variable in a function.

A scope in any programming is a region of the program where a defined


variable can have its existence and beyond that variable it cannot be accessed.
There are three places where variables can be declared in C programming
language

Inside a function or a block which is called local variables.


Outside of all functions which is called global variables.

Local Variables

Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of
code. Local variables are not known to functions outside their own. The
following example shows how local variables are used. Here all the variables a,
b, and c are local to main() function.

#include <stdio.h>

int main () {

/* local variable declaration */


int a =10, b =5;
int c;

Page 40
c = a + b;

printf ("value of a = %d, b = %d and c = %d\n", a, b, c);

return 0;
}

Global Variables

Global variables are defined outside a function, usually on top of the program.
Global variables hold their values throughout the lifetime of your program and
they can be accessed inside any of the functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. The
following program show how global variables are used in a program.

#include <stdio.h>

/* global variable declaration */


int g = 10;

int main () {

/* local variable declaration */


int a, b = 5;

a = g + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

return 0;
}

Q5. What do you mean by user defined function explain.

C allows programmer to define their own function according to their


requirement. These types of functions are known as user-defined functions.
Suppose, a programmer wants to find factorial of a number and check whether
it is prime or not in same program. Then, he/she can create two separate user-
defined functions in that program: one for finding factorial and other for
checking whether it is prime or not, which are called in the main() function.

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

Page 41
...........
...........
function_name();
...........
...........
}
Every C program begins from main() and program starts executing the codes
inside main() function. When the control of program reaches to function_name()
inside main() function. The control of program jumps to void function_name() and
executes the codes inside it. When all the codes inside that user-defined
function are executed, control of the program jumps to the statement just after
function_name() from where it is called.

Q6. Write a short note on C library function.

C Standard library functions or simply C Library functions are inbuilt


functions in C programming. Function prototype and data definitions of these
functions are written in their respective header file. For example: If you want
to use printf() function, the header file <stdio.h> should be included.

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

/* If you write printf() statement without including header file, this program
will show error. */
printf("Catch me if you can.");
}

There is at least one function in any C program, i.e., the main() function (which
is also a library function). This program is called at program starts.

There are many library functions available in C programming to help the


programmer to write a good efficient program.

Page 42
Suppose, you want to find the square root of a number. You can write your
own piece of code to find square root but, this process is time consuming and
the code you have written may not be the most efficient process to find square
root. But, in C programming you can find the square root by just using sqrt()
function which is defined under header file "math.h"

List of Standard Library Functions Under Different Header Files in


C Programming
C Header Files
<ctype.h>
<math.h>
<stdio.h>
<stdlib.h>
<string.h>
<time.h>

Q7. Write a user defined function great() that computes greatest of


two number & return the largest number to function main().

#include <stdio.h>

/* function declaration */
int great(int num1, int num2);

int main () {

/* local variable definition */


int a = 100;
int b = 200;
int ret;

/* calling a function to get max value */


ret = great(a, b);

printf( "Max value is : %d\n", ret );

return 0;
}

/* function returning the max between two numbers */


int great(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

Page 43
return result;
}

Q8. Write the block structure of a function.

Defining a Function

The general form of a function definition in C programming language is as


follows

return_type function_name( parameter list )


{
body of the function
}

A function definition in C programming consists of a function header and a


function body. Here are all the parts of a function

Return Type A function may return a value. The return_type is


the data type of the value the function returns. Some functions perform
the desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name This is the actual name of the function. The
function name and the parameter list together constitute the function
signature.

Parameters A parameter is like a placeholder. When a function is


invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.

Function Body The function body contains a collection of


statements that define what the function does.

Example

Given below is the source code for a function called great(). This function
takes two parameters num1 and num2 and returns the maximum value
between the two

/* function returning the max between two numbers */


int great(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

Page 44
return result;
}

Q9. Define the following: a) Formal parameter b) Actual parameter


c) Return type d) Function call

a) Formal parameter : If a function is to use arguments, it must declare


variables that accept the values of the arguments. These variables are called
the formal parameters of the function. E.g. int great(int num1, int num2). In
this num1 & num2 are formal parameters

b) Actual parameter: The variables used in function call are called actual
parameters. E.g. ret = max(a, b); In this a,b are actual parameters.

c) Return type : A function may return a value. The return_type is the


data type of the value the function returns. e.g. int great(),

d) Function call : While creating a C function, you give a definition of what


the function has to do. To use a function, you will have to call that function to
perform the defined task. To call a function, pass the required parameters
along with the function name, and if the function returns a value, then you can
store the returned value. E.g. ret = great(a, b);

Q10. What is a function prototype give an example.

Function prototype (declaration):

Every function in C programming should be declared before they are used.


These type of declaration are also called function prototype. Function
prototype gives compiler information about function name, type of arguments
to be passed and return type.

Syntax of function prototype


return_type function_name(type(1) argument(1),....,type(n) argument(n));

In the above example,int add(int a, int b); is a function prototype which provides
following information to the compiler:

1. name of the function is add()


2. return type of the function is int.

two arguments of type int are passed to function.

10 MARKS:

Q1. WAP to find the factorial of a given number using function.

Page 45
#include<stdio.h>
int factorial(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;
}
int factorial(int n)
{
Int I, f = 1;
For(i=1;i<=n;i++)
F = f * I;
Return(f);
}

Output

Enter an positive integer: 6


Factorial of 6 = 720

Q2. WAP to find GCD of a given number using function.

#include<stdio.h>
int GCD(int n);
int main()
{
int num1,num2,g=0;
printf("Enter two integers: ");
scanf("%d %d",&num1,&num2);
printf("HCF of %d and %d is ",num1 , num2);
g= GCD(num1,num2)
printf(GCD = %d,g);
return 0;
}

int GCD(int n1,int n2)


{
while(n1!=n2)
{
if(n1>n2)
n1-=n2;
else
n2-=n1;
}
return(n1);
}

Page 46
Output

Enter two integers: 14


35
HCF of 14 and 35 is 7

Q3. Explain call by value with an example.


This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter inside
the function have no effect on the argument.

For example refer Q2(10 marks)

As shown in the example the initial value of variable g = 0. After the execution
of the GCD() function the g value is g= 7

Q4. Explain the following: a) Passing arguments to a function

b) Returning value from a function.

a) Passing arguments to a function

While calling a function, there are two ways in which arguments can be passed to a
function

S.N. Call Type & Description


Call by value

1 This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.
Call by reference

This method copies the address of an argument into the formal


2
parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.

By default, C uses call by value to pass arguments. In general, it means the


code within a function cannot alter the arguments used to call the function.

b) Returning value from a function: Returning value from function


can be of two types

i) A function may return a value. The return_type is the data type of the
value the function returns.e.g int

#include<stdio.h>
float calculate_area(int);

Page 47
int main()
{
int radius;
float area;
printf("\nEnter the radius of the circle : ");
scanf("%d",&radius);
area = calculate_area(radius);
printf("\nArea of Circle : %f ",area);
return(0);
}
float calculate_area(int radius)
{
float areaOfCircle;
areaOfCircle = 3.14 * radius * radius;
return(areaOfCircle);
}

Output :
Enter the radius of the circle : 2
Area of Circle : 12.56
In the above program we can see that inside main function we are calling a
user defined calculate_area() function.

We are passing integer argument to the function which after area


calculation returns floating point area value.

ii) Some functions perform the desired operations without returning a


value. In this case, the return_type is the keyword void. Illustrated in the
below example

#include<stdio.h>

void area(); // Prototype Declaration


void main()
{
area();
}

void area()
{
float area_circle;
float rad;

printf("\nEnter the radius : ");


scanf("%f",&rad);

area_circle = 3.14 * rad * rad ;

printf("Area of Circle = %f",area_circle);


}

Page 48
Output :
Enter the radius : 3
Area of Circle = 28.260000

Consider main function

void main()
{
area();
}

We have just called a function , we can see that there is no variable or anything
specified between the pair of round brackets.

void area();

Now in the prototype definition (line No 3) of the function we can see the
return value as Void. Void means it does not return anything to the calling
function.

CHAPTER 4: ARRAYS

Array: An array is defined as finite ordered collection of homogenous data,


stored in contiguous memory locations.

Page 49
Arrays are of two types:

1. One-dimensional arrays

2. Multidimensional arrays

5 MARKS:

Q1. What is an array? Explain how to declare & initialize a single


dimensional array?

An array is defined as finite ordered collection of homogenous data, stored in


contiguous memory locations.

Declaring an Array

Like any other variable, arrays must be declared before they are used. General
form of array declaration is,

data-type variable-name[size];

for example :
int arr[10];

Here int is the data type, arr is the name of the array and 10 is the size of
array. It means array arr can only contain 10 elements of int type. Index of
an array starts from 0 to size-1 i.e first element of arr array will be stored at
arr[0] address and last element will occupy arr[9].

Initialization of an Array

After an array is declared it must be initialized. Otherwise, it will contain


garbage value(any random value).

Compile time initialization of array elements is same as ordinary variable


initialization. The general form of initialization of array is,

type array-name[size] = { list of values };

int M[4]={ 67, 87, 56, 77 }; //integer array initialization

Page 50
67 87 56 77
M[0] M[1] M[2] M[3]

float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization

It is not necessary to define the size of arrays during initialization.

int age[]={2,4,34,3,4};

Q2. With an example, explain declaration & initialization of two


dimensional array.

C language supports multidimensional arrays. The simplest form of the


multidimensional array is the two-dimensional array.

Two-dimensional array is declared as follows,

type array-name[row-size][column-size]

Example :
int a[3][3];

The above array can also be declared and initialized together. Such as,

int A[2][3] = {
{0,0,0},
{1,1,1}
};

0 0 0 0
A[0][0] A[0][1] A[0][2] A[0][3]

1 1 1 1
A[1][0] A[1][1] A[1][2] A[1][3]

int c[2][3]={{1,3,0}, {-1,5,9}};


OR
int c[][3]={{1,3,0}, {-1,5,9}};
OR

Page 51
int c[2][3]={1,3,0,-1,5,9};

Q3. Compare one dimensional array with two dimensional arrays.

Sl no One dimensional Two dimensional


Single or One Dimensional Two dimensional array is used
array is used to represent and to represent and store data in a
1
store data in a linear form. matrix form.

Array having only one Array having more than one subscript
subscript variable is called variable is called Multi-Dimensional
2
One-Dimensional array array.

It is also called as Single Multi Dimensional Array is also called


Dimensional Array or Linear as Matrix.
3
Array

Q4. Explain multi dimensional array with example.

Refer Q2 (5 marks)

Q5 WAP to search a given key in the array of elements.

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

void main()
{
int array[10];
int i, N, keynum, found=0;

clrscr();

printf("Enter the value of N\n");


scanf("%d",&N);

printf("Enter the elements one by one\n");


for(i=0; i<N ; i++)
{
scanf("%d",&array[i]);
}
printf("Input array is\n");
for(i=0; i<N ; i++)
{
printf("%d\n",array[i]);
}
printf("Enter the element to be searched\n");
scanf("%d", &keynum);

/* Linear search begins */


for ( i=0; i < N ; i++)
{
if( keynum == array[i] )
{

Page 52
found = 1;
break;
}
}
if ( found == 1)
printf("SUCCESSFUL SEARCH\n");
else
printf("Search is FAILED\n");

} /* End of main */

Q6. Discuss one dimensional array with an example.

Refer Q1 ( 5 marks)

Q7. Explain different operations on arrays.

Following operations can be performed on arrays:

1. Traversing
2. Searching
3. Insertion
4. Deletion
5. Sorting
6. Merging

1. Traversing: It is used to access each data item exactly once so that it can
be processed.
E.g.
We have linear array A as below:

1 2 3 4 5
10 20 30 40 50

Here we will start from beginning and will go till last element and during this
process we will access value of each element exactly once as below:

A [1] = 10
A [2] = 20
A [3] = 30
A [4] = 40
A [5] = 50

2. Searching: It is used to find out the location of the data item if it exists in
the given collection of data items.
E.g.
We have linear array A as below:

Page 53
1 2 3 4 5
15 50 35 20 25

Suppose item to be searched is 20. We will start from beginning and will
compare 20 with each element. This process will continue until element is
found or array is finished. Here:

1) Compare 20 with 15
20 # 15, go to next element.

2) Compare 20 with 50
20 # 50, go to next element.

3) Compare 20 with 35
20 #35, go to next element.

4) Compare 20 with 20
20 = 20, so 20 is found and its location is 4.

3. Insertion: It is used to add a new data item in the given collection of data
items.
E.g.
We have linear array A as below:

1 2 3 4 5
10 20 50 30 15

New element to be inserted is 100 and location for insertion is 3. So shift the
elements from 5th location to 3rd location downwards by 1 place. And then
insert 100 at 3rd location. It is shown below:

Page 54
4. Deletion: It is used to delete an existing data item from the given
collection of data items.
E.g.
We have linear array A as below:

1 2 3 4 5
10 20 50 40 25 60

The element to be deleted is 50 which is at 3rd location. So shift the elements


from 4th to 6th location upwards by 1 place. It is shown below:

After deletion the array will be:


1 2 3 4 5 6
10 20 40 25 60

Page 55
5. Sorting: It is used to arrange the data items in some order i.e. in
ascending or descending order in case of numerical data and in dictionary
order in case of alphanumeric data.
E.g.
We have linear array A as below:

1 2 3 4 5
10 50 40 20 30

After arranging the elements in increasing order by using a sorting technique, the
array will be:

1 2 3 4 5
10 20 30 40 50

6. Merging: It is used to combine the data items of two sorted files into
single file in the sorted form
We have sorted linear array A as below:

1 2 3 4 5 6
10 40 50 80 95 100

And sorted linear array B as below:

1 2 3 4
20 35 45 90

After merging merged array C is as below:

1 2 3 4 5 6 7 8 9 10
10 20 35 40 45 50 80 90 95 100

Q8. WAP to store 25 elements (integers) in two dimensional array


called temp in 5 rows & 5 columns. The program should display
these numbers in a matrix format.

#include <stdio.h>

int main()
{

Page 56
int temp[5][5];

printf("Enter the elements of matrix\n");

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


for(d = 0; d <5n; d++)
scanf("%d",&matrix[c][d]);

printf("The entered matrix :-\n");

for (c = 0; c < 5; c++) {


for (d = 0; d < 5; d++)
printf("%d\t",temp[c][d]);
printf("\n");
}

return 0;
}

Output

Enter the elements of the matrix


1111122222333334444455555

The entered matrix :-


11111
22222
33333
44444
55555

Q9. WAP to transpose given matrix.

#include <stdio.h>

int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);

printf("Enter the elements of matrix\n");

for (c = 0; c < m; c++)


for(d = 0; d < n; d++)
scanf("%d",&matrix[c][d]);

for (c = 0; c < m; c++)


for( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];

Page 57
printf("Transpose of entered matrix :-\n");

for (c = 0; c < n; c++) {


for (d = 0; d < m; d++)
printf("%d\t",transpose[c][d]);
printf("\n");
}

return 0;
}

Q10. List the advantages & disadvantages of an array.

Advantages:

1. It is used to represent multiple data items of same type by using only single
name.
2. It can be used to implement other data structures like linked lists, stacks,
queues, trees, graphs etc.
3. 2D arrays are used to represent matrices.

Disadvantages:

1. We must know in advance that how many elements are to be stored in array.
2. Array is static structure. It means that array is of fixed size. The memory
which is allocated to array can not be increased or reduced.
3. Since array is of fixed size, if we allocate more memory than requirement
then the memory space will be wasted. And if we allocate less memory than
requirement, then it will create problem.
4. The elements of array are stored in consecutive memory locations. So
insertions and deletions are very difficult and time consuming.

Q11. WAP to find the sum of principle diagonal elements of a


matrix.

#include<stdio.h>

Page 58
int main()
{
int m[4][4]; //Declare 2 Dimensional Array
int i, j, sum = 0;
// Input Matrix
printf("Enter matrix order 4*4 \n");
for (i = 0; i < 4; i++)
{
printf("Enter elements of %d row \n", i);
for (j = 0; j < 4; j++)
{
scanf("%d", &m[i][j]);

}
}
// Compute Sum of main diagonal elements in sum1
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (i == j)

sum = sum + m[i][j];

}
}

printf("Sum of Diagonal Elements is %d \n", sum);

return 0;
}

10 MARKS:

Q1. Write a program to search an element in an array.

Refer Q 5 ( 5 marks)

Q2. WAP to find the sum and number of positive & negative
numbers in an array.

# include <stdio.h>

# include <conio.h>

void main()

Page 59
int a[20], i, n, psum = 0, nsum = 0 ;

clrscr() ;

printf("Enter the limit : ") ;

scanf("%d", &n) ;

printf("\nEnter the elements :\n\n") ;

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

scanf("%d", &a[i]) ;

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

if(a[i] > 0)

psum = psum + a[i] ;

if(a[i] < 0)

nsum = nsum + a[i] ;

printf("\nSum of positive elements is : %d", psum) ;

printf("\n\nSum of negative elements is : %d", nsum) ;

getch() ;

Output

Enter the limit : 5

Enter the elements :

-10 30 50 -20 40

Sum of positive elements is : 120

Sum of negative elements is : -30

Page 60
Q3. WAP to sort N elements of an array using simple sort.

/*
C program to accept N numbers and arrange them in an ascending order
*/
#include <stdio.h>

void main()
{
int i, j, a, n, number[30];

printf("Enter the value of N \n");


scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);
}

Output:

Enter the value of N


6
Enter the numbers
3
78
90
456
780
200
The numbers arranged in ascending order are given below
3
78
90
200
456
780

Page 61
Q4. Define the following: a) Array b) Searching c) Sorting

a) Array: An array is defined as finite ordered collection of homogenous


data, stored in contiguous memory locations.
int a[5], float m[4]

b) Searching: searching is a process of searching for an element in the data


structure based on some technique.
e.g. searching on array using linear search technique.

c) Sorting: sorting is the method of rearranging data in the data structure


using some technique.
e.g. sorting array elements in ascending order using bubble sort technique.

Q5. WAP to find sum of two matrices.

#include <stdio.h>

int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);

printf("Enter the elements of second matrix\n");

for (c = 0; c < m; c++)


for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);

printf("Sum of entered matrices:-\n");

for (c = 0; c < m; c++) {


for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}

return 0;
}

Page 62
Output

Q6. WAP to find the transpose of a matrix.

Refer Q9 ( 5 marks)

CHAPTER 5: STRINGS & PREPROCESSOR

Page 63
Strings: In C programming, array of character are called strings. A string is
terminated by null character /0. e.g. hello. Like other variables strings also
must be declared & can be initialized. Strings must be declared using char
data type only.

Strings are often needed to be manipulated by programmer according to the


need of a problem. All string manipulation can be done manually by the
programmer but, this makes programming complex and large. To solve this,
the C supports a large number of string handling functions.

There are numerous functions defined in "string.h" header file. Few commonly
used string handling functions are discussed below:

Method Description
strcat() It is used to concatenate(combine) two string
strlen() It is used to show length of a string
strrev() It is used to show reverse of a string
strcpy() Copies one string into another
strcmp() It is used to compare two string

Macros: Macros are known as symbolic constants.Preprocessing directive


#define can be used to write macro definitions with parameters as well in the
form below:

#define identifier(identifier 1,.....identifier n) token_string

Again, the token string is optional but, are used in almost every case. Let us
consider an example of macro definition with argument.

#define area(r) (3.1415*(r)*(r))

Here, the argument passed is r. Every time the program encounters


area(argument), it will be replace by (3.1415*(argument)*(argument)).
Suppose, we passed (r1+5) as argument then, it expands as below:

area(r1+5) expands to (3.1415*(r1+5)*(r1+5))

5 MARKS:

Page 64
Q1. Define string. Explain how to declare & initialize string
variables with an example.

In C programming, array of character are called strings. A string is terminated


by null character /0. For example:

"c string tutorial"

Here, "c string tutorial" is a string. When, compiler encounters strings, it


appends null character at the end of string.

Declaration of strings

Strings are declared in C in similar manner as arrays. Only difference is that,


strings are of char type.

char s[5];

Initialization of strings

In C, string can be initialized in different number of ways.

char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};

Q2. WAP to concatenate two strings using in built string functions.

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

int main ()
{

char str1[12] = "Hello";


char str2[12] = "World";
/* concatenates str1 and str2 */

Page 65
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

return 0;
}

When the above code is compiled and executed, it produces the following
result

strcat( str1, str2): HelloWorld

Q3. Explain how to read the string from the terminal & write a
string to the terminal with an example.

Functions gets() and puts() are two string functions to take string input from
user and display string respectively as mentioned in previous chapter.

#include<stdio.h>
int main(){
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}

Or

Write a C program to illustrate how to read string from terminal.

#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}

Output

Enter name: Dennis Ritchie


Your name is Dennis.

Page 66
Q4. Explain with an example the null terminated strings as Array
of Characters.

string is a sequence of characters that is treated as a single data item and


terminated by null character '\0'. For example : The string "hello world"
contains 12 characters including '\0' character which is automatically added by
the compiler at the end of the string.

char c[5]={'a','b','c','d','\0'};

Q5. WAP to check whether the given string is a palindrome or not.

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

int main () {

char str1[12], str2[12];


printf("Enter string ");
scanf("%s",str1);

/* copy str1 into str2 */


strcpy(str2, str1);
printf("string 2 : %s\n", str2 );

/* reverse str2 */
strrev(str2);
printf("Reverse string 2 : %s\n", str2 );

/* compare original string with reversed string */


If(strcmp(str1,str2) == 0)
Printf( The given string is a palindrome );
Else
Printf( The given string is not a palindrome);

return 0;
}

When the above code is compiled and executed, it produces the following
result

Output 1:

Enter string: Hello

Page 67
String 2 : Hello
Reverse string 2: olleh
The given string is not a palindrome

Output 1:

Enter string: amma

String 2 : amma
Reverse string 2: amma
The given string is a palindrome

Q6. List string handling functions.

Strings are often needed to be manipulated by programmer according to the


need of a problem. All string manipulation can be done manually by the
programmer but, this makes programming complex and large. To solve this,
the C supports a large number of string handling functions.

There are numerous functions defined in "string.h" header file. Few commonly
used string handling functions are discussed below:

S.N. Function & Purpose


strcpy(s1, s2);
1
Copies string s2 into string s1.
strcat(s1, s2);
2
Concatenates string s2 onto the end of string s1.
strlen(s1);
3
Returns the length of string s1.
strcmp(s1, s2);
4
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
strchr(s1, ch);
5
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
6
Returns a pointer to the first occurrence of string s2 in string s1.

Q7. WAP to compare any two strings using string functions.

The following example uses some of the above-mentioned functions

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

int main () {

char str1[12],str2[12];
printf("Enter string1 ");
scanf("%s",str1);

printf("Enter string2 ");


scanf("%s",str2);

/* compare two strings */


If(strcmp(str1,str2) == 0)
Printf( The given strings are same);
Else
Printf( The given strings are not same);

return 0;
}

When the above code is compiled and executed, it produces the following
result

Output1:
Enter string 1: hello
Enter string 2: hello
The given strings are same

Output2:
Enter string 1: hello
Enter string 2: hell
The given strings are not same

Q8. List the advantages of preprocessor directives.

Q9. Explain briefly how to use #define directive.

Given below is the form to use #define preprocessor to define a constant

#define identifier value

The following example explains it in detail

#define MAX_ARRAY_LENGTH 20

This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH


with 20.

Page 69
The directive must be included after defining header files as shown below:

#include <stdio.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

Q10. Write short note on file inclusion.


1. File inclusive Directories are used to include user define header file
inside C Program.
2. File inclusive directory checks included header file inside same
directory (if path is not mentioned).
3. File inclusive directives begins with #include
4. If Path is mentioned then it will include that header file into current
scope.
5. Instead of using triangular brackets we use Double Quote for
inclusion of user defined header file.
6. It instructs the compiler to include all specified files.

There are two ways of including header file:

1 : Including Standard Header Files

#include<filename>
Search File in Standard Library

way 2 :User Defined Header Files are written in this way

#include"FILENAME"
Search File in Current Library
If not found , Search File in Standard Library
User defined header files are written in this format

Example :
#include<stdio.h> // Standard Header File
#include<conio.h> // Standard Header File
#include"myfunc.h" // User Defined Header File

Explanation:

1. In order to include user defined header file inside C Program , we must


have to create one user defined header file.
2. Using double quotes include user defined header file inside Current C
Program.
3. myfunc.h is user defined header file .
4. We can combine all our user defined functions inside header file and
can include header file whenever require.

Page 70
Q11. Explain with example the #include directive.

Refer Q10 ( 5 marks)

Q12. How do you define symbolic constants? Illustrate with an


example.
In c symbolic constants can be defined in two typtes
I) Refer Q9

ii) The const Keyword

const can be to declare constants with a specific type as follows

const type variable = value;

The following example explains it in detail

#include <stdio.h>

int main() {

const int LENGTH = 10;


const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}

When the above code is compiled and executed, it produces the following
result

value of area : 50

Q13. Define a macro. Explain macro substitution with an example.

One of the powerful functions of the CPP is the ability to simulate functions
using parameterized macros. For example, we might have some code to square
a number as follows

int square(int x)
{
return x * x;
}

Page 71
We can rewrite above the code using a macro as follows

#define square(x) ((x) * (x))

Macros with arguments must be defined using the #define directive before
they can be used. The argument list is enclosed in parentheses and must
immediately follow the macro name. Spaces are not allowed between the
macro name and open parenthesis. For example

#include <stdio.h>

#define MAX(x,y) ((x) > (y) ? (x) : (y))

int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}

When the above code is compiled and executed, it produces the following
result

Max between 20 and 10 is 20

10 MARKS:

Q1. Explain the following function with an example: a) getchar()


b) strrev()
c) strcmp() d) strcat() e) strcpy()

a) getchar() : getchar(s); this function accepts only one character from


key
board & stores in the variable s.
e.g. getchar(s); s=w

b) strrev() : strrev(s); reverses the string s & saves in string s


e.g s = hello
after strrev(s); s=olleh

c) strcmp() : strcmp(s1, s2); Returns 0 if s1 and s2 are the same;


less than 0 if s1<s2; greater than 0 if s1>s2.

e.g s1 = hello s2 = hai

after strcmp(s1,s2); return > 0 value

e.g s1 = hello s2 = hello

after strcmp(s1,s2); return = 0 value

e.g s1 = hai s2 = hello

Page 72
after strcmp(s1,s2); return < 0 value

d) strcat() : strcat(s1, s2); Concatenates string s2 onto the end of string


s1.

e.g s1 = hello s2 = hai

after strcat(s1,s2); s1= hellohai s2 = hai

e) strcpy() : strcpy(s1, s2); Copies string s2 into string s1.

e.g s1 = hello s2 = hai

after strcpy(s1,s2); s1= hai s2 = hai

Q2. Define string. Give an example. Explain various string handling


functions with an example.
Refer Q1 & Q6 of 5 marks , Q1 of 10 marks

Q3. WAP to verify that the given string is palindrome or not using
iterative method.

#include <stdio.h>

#include <conio.h>

void main() {

char *a;

int i,len,flag=0;

clrscr();

printf("\nENTER A STRING: ");

gets(a);

len=strlen(a);

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

if(a[i]==a[len-i-1])

flag=flag+1;

Page 73
if(flag==len)

printf("\nTHE STRING IS PALINDROM"); else

printf("\nTHE STRING IS NOT PALINDROM");

getch();

Result
ENTER A STRING:Ankit
THE STRING IS NOT PALINDROM

Q4. WAP to find area of a circle using macros.

#include <stdio.h>

#define AREA(r) ((3.14) * (r) * (r))

int main(void) {
printf("The area of a circle %f\n", AREA(10));
return 0;
}

OUTPUT:

The are of a circle 314

OR

C Program to find area of a circle, passing arguments to macros.


[Area of circle=r2]

#include <stdio.h>
#define PI 3.1415
#define area(r) (PI*(r)*(r))
int main()
{
int radius;
float a;
printf("Enter the radius: ");
scanf("%d",&radius);
a=area(radius);
printf("Area=%.2f",a);
return 0;
}

Page 74
Output:
Enter the radius: 3
Area = 28.27

Q5. Write a note on the following: a) Pre processor directive


b) Macro substitution.
a) Pre processor directive: Refer Q9 & Q11 of 5 marks

c) Macro substitution:The other major use of the preprocessor is to define


macros. The advantage of a macro is that it can be type-neutral, and it's in
lined directly into the code, so there isn't any function call overhead.

A macro definition is usually of the following form:

#define MACRO_NAME(arg1, arg2, ...) [code to expand to]

For instance, a simple increment macro might look like this:

#define INCREMENT(x) x++

They look a lot like function calls, but they're not so simple. when it comes to
working with macros. First, remember that the exact text of the macro
argument is "pasted in" to the macro. For instance, if you wrote something
like this:

#define MULT(x, y) x * y

and then wrote

int z = MULT(3 + 2, 4 + 2);

what value do you expect z to end up with? The obvious answer, 30, is wrong!
That's because what happens when the macro MULT expands is that it looks
like this:
int z = 3 + 2 * 4 + 2; // 2 * 4 will be evaluated first!

So z would end up with the value 13! This is almost certainly not what you
want to happen. The way to avoid it is to force the arguments themselves to be
evaluated before the rest of the macro body. You can do this by surrounding
them by parentheses in the macro definition:

#define MULT(x, y) (x) * (y)

// now MULT(3 + 2, 4 + 2) will expand to (3 + 2) * (4 + 2)

It is also generally a good idea to surround the macro's code in parentheses if


you expect it to return a value.

Page 75
CHAPTER 6: STRUCTURES & UNION

Structure: Structure is a user-defined data type in C which allows user to


combine different data types to store a particular type of record.

A union is a special data type available in C that allows user to store different
data types in the same memory location.

5 MARKS:

Page 76
Q1. Define a structure. Explain with an example, the general syntax
of a structure.
Structure is a user-defined data type in C which allows user to combine
different data types to store a particular type of record. Structure helps to
construct a complex data type in more meaningful way.

Defining a structure

struct keyword is used to define a structure. struct define a new data type
which is a collection of different type of data.

Syntax :

struct structure_name
{
//Statements
};

Example of Structure

struct Book
{
char name[15];
int price;
int pages;
};

Here the struct Book declares a structure to hold the details of book which
consists of three data fields, namely name, price and pages. These fields are
called structure elements or members. Each member can have different
data type,like in this case, name is of char type and price is of int type etc.
Book is the name of the structure and is called structure tag.

Q2. What are structure variables? Explain how to declare &


initialize a structure variable.

It is possible to declare variables of a structure, after the structure is defined.


Structure variable declaration is similar to the declaration of variables of any
other data types. Structure variables can be declared in following two ways.

1) Declaring Structure variables separately

struct Student
{
char[20] name;
int age;
int rollno;
};

Page 77
struct Student S1 , S2; //declaring variables of Student

2) Declaring Structure Variables with Structure definition

struct Student
{
char[20] name;
int age;
int rollno;
} S1, S2 ;
Here S1 and S2 are variables of structure Student. However this approach is
not much recommended.

Structure Initialization

Like any other data type, structure variable can also be initialized at compile
time.

struct Patient
{
float height;
int weight;
int age;
};

struct Patient p1 = { 180.75 , 73, 23 }; //initialization

or,

struct patient p1;


p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;

Q3. Define a union. Explain with an example, the general syntax of


a union.

A union is a special data type available in C that allows user to store different
data types in the same memory location. You can define a union with many
members, but only one member can contain a value at any given time. Unions
provide an efficient way of using the same memory location for multiple-
purpose.

Defining a Union

To define a union, you must use the union statement in the same way as you
did while defining a structure. The union statement defines a new data type

Page 78
with more than one member for your program. The format of the union
statement is as follows

union [union tag]


{
member definition;
member definition;
...
member definition;
} [one or more union variables];

The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the
end of the union's definition, before the final semicolon, you can specify one
or more union variables but it is optional. Here is the way you would define a
union type named Data having three members i, f, and str

union Data
{
int i;
float f;
char str[20];
} data;

Now, a variable of Data type can store an integer, a floating-point number, or


a string of characters. It means a single variable, i.e., same memory location,
can be used to store multiple types of data. You can use any built-in or user
defined data types inside a union based on your requirement.

The memory occupied by a union will be large enough to hold the largest
member of the union. For example, in the above example, Data type will
occupy 20 bytes of memory space because this is the maximum space which
can be occupied by a character string.

Q4. List the difference between union & structure.

Slno Structures Unions


1 The amount of memory The memory required to store a
required to store a structure union variable is the memory
variables is the sum of memory required for largest element of an
size of all members. union.

2 All members of structure can be Only one member of union can be


accessed at any time. accessed at a time in case of union
and other members will contain
garbage value.

3 It is defined with struct It is defined with union keyword

Page 79
keyword

Q5. Compare array versus structure.

Sl Array structure
no
1 An array is a collection of related . Structure can have elements of
data elements of same type. different types
2 Static memory allocation. Dynamic memory allocation.
3 It uses the subscript to access the It uses the dot(.)operator to access the
array elements .e.g. a[2] structure members. E.g. s.name
4 Memory (array size) is fixed Memory (structure size) can be
changed dynamically
5 An array is derived data type A structure is a
programmer defined one.

Q6. Define array of structures. Give example.

We can also declare an array of structure. Each element of the array


representing a structure variable. Example : struct employee emp[5];

The above code define an array emp of size 5 elements. Each element of array
emp is of type employee

#include<stdio.h>
#include<conio.h>
struct employee
{
char ename[10];
int sal;
};

struct employee emp[5];


int i,j;
void ask()
{
for(i=0;i<3;i++)
{
printf("\nEnter %dst employee record\n",i+1);
printf("\nEmployee name\t");
scanf("%s",emp[i].ename);
printf("\nEnter employee salary\t");
scanf("%d",&emp[i].sal);
}
printf("\nDisplaying Employee record\n");
for(i=0;i<3;i++)
{
printf("\nEmployee name is %s",emp[i].ename);

Page 80
printf("\nSlary is %d",emp[i].sal);
}
}
void main()
{
clrscr();
ask();
getch();
}

Q7. Explain array variables as a structure member with an


example.
1. Structure may contain the Array of integer as its Member.
2. We can store name,roll,percent as structure members , but sometimes
we need to store the marks of three subjects then we embed integer
array of marks as structure member

e.g. consider a program to read one student name & 3 test marks, then an
array marks[3] is included in side the structure as shown below. Then we can
access individual array element from structure using structure variable

#include <stdio.h>

struct student
{
char sname[20];
int marks[3]; //Note Carefully
}s1;

int main()
{

printf("\nEnter the Name of Student : ");


gets(s1.sname)

printf("\nEnter the Marks in Subject 1 : ");


scanf("%d",&s1.marks[0]);
printf("\nEnter the Marks in Subject 2 : ");
scanf("%d",&s1.marks[1]);
printf("\nEnter the Marks in Subject 3 : ");
scanf("%d",&s1.marks[2]);

printf("\n ---- Student Details -------- ");


printf("\n Name of Student : %s",s1.sname);
printf("\n Marks in Subject 1 : %d",s1.marks[0]);
printf("\n Marks in Subject 2 : %d",s1.marks[1]);
printf("\n Marks in Subject 3 : %d",s1.marks[2]);

return 0;
}

Page 81
Output:
Enter the Name of Student : xyz
Enter the Marks in Subject 1 : 67
Enter the Marks in Subject 2 : 77
Enter the Marks in Subject 3 : 76

n ---- Student Details --------


Name of Student : xyz
Marks in Subject 1 : 67
Marks in Subject 2 : 77
Marks in Subject 3 : 76

10 MARKS:

Q1. Explain array of structures with an example.


Refer Q6 of 5 marks

Q2. Explain the need of structure with in a structure ( nested


structure) with an example.

Structures can be nested within other structures in C programming.

struct complex
{
int imag_value;
float real_value;
};

struct number{
struct complex c1;
int real;
}n1,n2;

Suppose you want to access imag_value for n1 structure variable then,


structure member n1.c1.imag_value is used.

#include <stdio.h>

struct date
{
int date;
int month;
int year;
};

struct Employee
{
char ename[20];
int ssn;
float salary;

Page 82
struct date doj;

}emp = {"Pritesh",1000,1000.50,{22,6,1990}};

int main(int argc, char *argv[])


{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee SSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", \
emp.doj.date,emp.doj.month,emp.doj.year);

return 0;
}

Output :
Employee Name : Pritesh
Employee SSN : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990

Q3. WAP to read N students information & display it.

#include<stdio.h>
#include<conio.h>
struct student
{
char sname[10];
int regno;
};

struct student s[5];


int i,j;
void ask()
{
for(i=0;i<3;i++)
{
printf("\nEnter %dst student record\n",i+1);
printf("\nstudent name\t");
scanf("%s",s[i].sname);
printf("\nEnter student regno \t");
scanf("%d",&s[i].regno);
}
printf("\nDisplaying student record\n");
for(i=0;i<3;i++)
{
printf("\nstudent name is %s",student[i].sname);
printf("\nSlary is %d",student[i].regno);
}
}

Page 83
void main()
{
clrscr();
ask();
getch();
}

Output

Enter 1 student record


student name abc
Enter student regno 111

Enter 2 student record


student name lmn
Enter student regno 222

Enter 3 student record


student name xyz
Enter student regno 333

Displaying student record

Enter 1 student record


student name abc
Enter student regno 111

Enter 2 student record


student name lmn
Enter student regno 222

Enter 3 student record


student name xyz
Enter student regno 333

Q4. WAP to create structure with an employee details & display the
same.

#include<stdio.h>
#include<conio.h>
struct employee
{
char ename[10];
int sal;
}emp;

Void main()
{

Page 84
printf("\nEnter employee record\n",i+1);
printf("\nEmployee name\t");
scanf("%s",emp.ename);
printf("\nEnter employee salary\t");
scanf("%d",&emp.sal);

printf("\nDisplaying Employee record\n");


printf("\nEmployee name is %s",emp.ename);
printf("\nSlary is %d",emp.sal);
getch();
}

Output
Enter employee record
Employee name ddd
Enter employee salary 10000

Displaying Employee record


Employee name ddd
Enter employee salary 10000

Page 85

You might also like