0% found this document useful (0 votes)
45 views75 pages

C PRG

Uploaded by

jayashrees.scs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views75 pages

C PRG

Uploaded by

jayashrees.scs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

PROGRAMMING IN C

Unit I

3 marks

1. What is an identifier?

• Identifiers are used to represent names C program, such as variables, arrays, functions,
structures, unions and labels.
• An identifier can be composed only of uppercase, lowercase letters, underscore and
digits, but should start only with an alphabet or an underscore.
• An identifier is a string of alphanumeric characters that begins with an alphabetic
character or an underscore character.

2. What is a variable?

• In programming, a variable is a memory name to store data.

• A variable in simple terms is a memory space in which data stored. Each variable in C
has a specific data type, which determines the size of memory.

• The name of a variable can be composed of letters, digits, and the underscore character. It
must begin with either a letter or an underscore. Upper and lowercase letters are distinct
because C is case-sensitive.

3. What are character set?

The C character set consists of upper and lowercase alphabets, digits, special characters and
white spaces. The alphabets and digits are altogether called as the alphanumeric
character.
Letters
In C programming, we can use both uppercase and lowercase letters of English language
Uppercase Letters: A to Z, Lowercase Letters: a to z

1
Digits
We can use decimal digits from 0 to 9.
Special Characters
comma , slash /, period .

4. aWrite the syntax of increment operator. Give example.

• Increment operators are used to increase the value of the variable by ONE.

Syntax:
Incremen toperator: ++var_name; (or) var_name++;

• Pre increment operator (++i) value of i is incremented before assigning it to the


variable i
• Post increment operator (i++) value of i is incremented after assigning it to the variable i
Example:
Increment operator : ++ i ; i ++ ;

5. What are the types of C tokens?

Each and every smallest individual units in a C program are known as C tokens. C tokens are the basic
buildings blocks in C language which are constructed together to write a C program.
Identifiers :
Identifiers in c refer to the name of the variables, functions, arrays,etc. created by the programmer,
using the combination of following characters.
◼ Alphabets : A to Z (or) a to z
◼ Digits : 0 to 9
◼ Underscore : _
Constants :
Constants define fixed values, that do not change during the execution of a program. C supports the
following constants.
• Integer constants

2
• Character constants
• Real or floating constants
• String constants

Keyword: Keywords are pre-defined or reserved words in a programming language.

For example break, for, while, do-while, do, if, int, long, char.

Variables: Variables are used to give the name and allocate memory space. For example, sum,
area, a, b, age, city.
String: String is a collection of more than one character. For example, “RAM”, “Meerut”, “Star”
Operators:
Operator is a symbol which performs particular operation. They include arithmetic operators, logical
operators, bitwise operators, etc.

6. What is a conditional operator?

A conditional operator is a ternary operator, that is, it works on 3 operands.


Syntax
Conditional_Expression? expression1: expression2;

Example

void main() {
int num;
clrscr();
printf("Enter the Number: ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd"); }
7. What is keyword?

Following list shows the reserved words in C. These reserved words may not be used as constant
or variable 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

3
continue goto sizeof volatile
default if static while
double Int struct packed

8. List out the header files in C.

C Library Functions under Different Header File


C Header Files are,
• <assert.h> Program assertion functions
• <ctype.h> Character type functions
• <locale.h> Localization functions
• <math.h> Mathematics functions
• <setjmp.h> Jump functions
• <signal.h> Signal handling functions
• <stdarg.h> Variable arguments handling functions
• <stdio.h> Standard Input/Output functions
• <stdlib.h> Standard Utility functions
• <string.h> String handling functions
• <time.h> Date time functions

9. What is an integer constant?

An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:

• decimal constant(base 10)


• octal constant(base 8)
• hexadecimal constant(base 16)

For example :-

4
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */

10. List out any 5 math functions.

Function #include What It Does


sqrt() math.h Calculates the square root of a floating-point value
pow() math.h Returns the result of a floating-point value raised to a
certain power
abs() stdlib.h Returns the absolute value (positive value) of an integer
floor() math.h Rounds up a floating-point value to the next whole number
(nonfractional) value
ceil() math.h Rounds down a floating-point value to the next whole number

For example:-

ceil(-30.89) gives output as -30

floor(-34.2) gives output as -35

abs(-12) gives output as 12

pow(3,2) gives output as 9

sqrt(16) gives output as 4

5
8 marks

1. What is an expression and explain the types of expression?


An expression represents a single data item--usually a number.
The expression may consist of a single entity, such as a constant or variable, or it may
consist of some combination of such entities, interconnected by one or
more operators.
Expressions can also represent logical conditions which are either true or false.
However, in C, the conditions true and false are represented by the integer
values 1 and 0, respectively.
Several simple expressions are given below:
2. a + b
3. x = y
4. t = u + v
5. x <= y
6. ++j
The first expression, which employs the addition operator (+), represents the sum of
the values assigned to variables a and b.
The second expression involves the assignment operator(=), and causes the
value represented by y to be assigned to x.
In the third expression, the value of the expression (u + v) is assigned to t.
The fourth expression takes the value 1 (true) if the value of x is less than or equal to
the value of y. Otherwise, the expression takes the value 0 (false). Here, <= is
a relational operator that compares the values of x and y.
The final example causes the value of j to be increased by 1. Thus, the expression is
equivalent to j = j + 1 The increment (by unity) operator ++ is called
a unary operator, because it only possesses one operand.
C – EXPRESSION EXAMPLE PROGRAM :
#include<stdio.h>
#include<conio.h>
void main()

6
{
int a=123 , b; b=a+2;
clrscr();
printf(“Value of a = %d\n”,a);
printf(“Value of b =%d”,b);
getch();
}

output:

7
Value of a = 123
Value of b = 125

7. Explain the fundamental data types?

C compiler supports five types of Dastatype, namely


• integer (int)
• character(char)
• floating point(float)
• void (void)
INTEGER TYPES
• Integers are whole numbers with a range of values -32768 to +32767 and the size is 16
bit.
• C has three classes of integer storage, namely short int , int, long int.
• These classes may be
signed int or unsigned int , signed short int or unsigned short int and
• Signed long int
orunsigned long int.

8
FLOATING POINT TYPES
Floating point types stored in 32 bitwith 6 digits of precision. The keyword float is used in C
language.
DOUBLE PRECISION FLOATING POINT
• A dpube represents the same datatypes of float.
• A double data type numbers uses 64 bit memory and the precision of 14 digits.
• We may extend the double as long double with 80 bits of memory.
VOID DATA TYPE
• This is used to specify the data type of the function.
• Void has no values.
• If one function is void , that means that function does not return any value to the
calling function.
CHARACTER TYPE
• A single character can be defind as char.
• Char usually stored in 8 bit of memory.
• The qualifier signed or unsigned may be applied.
• Unsigned char have the values of 0 to 255 and the signed char have -126 to 127

8. Write a C Program for calculating simple interest (si=p*n*r/100).


To calculate simple interest we need four variables, ie) si for store calculated simple interest
,
p for principle amount , for number of years n and r for rate of interest.>

#inclide<stdio.h>
#include<conio.h>
void main()
{
int si,p,n,r;
clrscr();
printf(“Enter Principle Amount”);

9
scanf(“%d”,&p);
printf(“Enter the number of years”);
scanf(“%d”,&n);
printf(“Enter the rate of interest”);
scanf(“%d”,&r);
si=(p*N*r)/100;

printf(“SIMPLE INTEREST”);
printf(“\n~~~~~~~~~~~~~~~~”);
printf(“\n\t%d”,si);
getch();
}

Output
Enter Principle Amount
2000
Enter the number of years
2
Enter the rate of interest
2
SIMPLE INTEREST
~~~~~~~~~~~~~~~~
80

9. What is an integer constant and explain the types of integer constants?


o C Constants are also like normal variables. But, only difference is, their values
cannot be modified by the program once they are defined.
o Constants refer to fixed values. They are also called as literals.
o Constants may be belonging to any of the data type.
Syntax:

10
const data_type variable_name; (or) const data_type *variable_name;

TYPES OF C CONSTANT:
i. Integer constants
ii. Real or Floating point constants iii.
Octal & Hexadecimal constants iv.
Character constants
v. String constants
vi. Backslash character constants
RULES FOR CONSTRUCTING INTEGER CONSTANTS:
i. An integer constant must have at least one digit. ii.
It must not have a decimal point.
iii. It can either be positive or negative.
iv. No commas or blanks are allowed within an integer constant.
v. If no sign precedes an integer constant, it is assumed to be positive. vi.
The allowable range for integer constants is -32768 to 32767.

10. Define variables and list out the rules for declaring it.
C variable is a named location in a memory where a program can manipulate the data.
This location is used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.
RULES FOR NAMING C VARIABLE:
i. Variable name must begin with letter or underscore. ii.
Variables are case sensitive
iii. They can be constructed with digits, letters.
iv. No special symbols are allowed other than underscore.
v. sum, height, _value are some examples for variable name
DECLARING & INITIALIZING C VARIABLE:
Variables should be declared in the C program before to use.

11
Memory space is not allocated for a variable while declaration. It happens only
on
variable definition.
Variable initialization means assigning a value to the variable.
Type Syntax

Variable declaration data_type


variable_name;

;
Variable initialization data_type variable_name =
value; Example:

int x = 50, y = 30; char flag = ‘x’,


11. ch=’l’;

12. Explain the math library functions.

Function Description Example

sqrt(4.0) is 2.0
sqrt(x) square root of x
sqrt(10.0) is 3.162278

exp(1.0) is 2.718282
exp(x) exponential (ex)
exp(4.0) is 54.598150

natural logarithm of x log(2.0) is 0.693147


log(x)
(base e) log(4.0) is 1.386294

12
Function Description Example

log10(10.0) is 1.0
log10(x) logarithm of x (base 10)
log10(100.0) is 2.0

fabs(2.0) is 2.0
fabs(x) absolute value of x
fabs(-2.0) is 2.0

rounds x to smallest ceil(9.2) is 10.0


ceil(x)
integer not less than x ceil(-9.2) is -9.0

rounds x to largest integer floor(9.2) is 9.0


floor(x)
not greater than x floor(-9.2) is -10.0

pow(x,y) x raised to power y (xy) pow(2,2) is 4.0

remainder of x/y as fmod(13.657, 2.333) is


fmod(x)
floating-point number 1.992

sin(x) sine of x (x in radian) sin(0.0) is 0.0

cos(x) cosine of x (x in radian) cos(0.0) is 1.0

tan(x) tangent of x (x in radian) tan(0.0) is 0.0

13. Explain the String library functions


STRING LIBRARY FUNCTIONS
There are some string related library functions which operate on the string and produces certain results.
Here are some of the commonly used string library functions:

▪ strlen(): This function returns the length of the string. Example: strlen(name); This will return
the length of the string stored in the variable name[].

13
▪ strcat(): This function concatenates two strings. Example: strcat(name,name1); This will
concatenate the strings stored in the variables name[] and name1[] in the order in which it is
written.
▪ strcpy(): This function copies the value of the second string to the first string.
Example: strcpy(name1,name); This will copy the string in name[] to the variable name1[].
▪ strcmp(): It compares two strings. Example: strcmp(name,name1); This compares the string
in name[] with the string in name1[]. It returns 0 if the strings are same. It returns a value less than
0 if name[]<name1[]. Otherwise, it returns a value greater than 0.
▪ strlwr(): It changes all the characters of the string to lower case. Example: strlwr(name); It shall
convert the whole string stored in the variable name[] to lowercase.
▪ strupr(): It changes all the characters of the string to upper case. Example: strupr(name); It shall
convert the whole string stored in the variable name[] to uppercase.
▪ strchr(): It returns the location or the pointer of the first occurrence of a character in a string.
Example: strchr(name,ch); It returns the location of the first occurrence of the character in ch in the
string name[]. It returns null if the character is not found.
▪ strstr(): It returns the location or the pointer of the first occurrence of one string in another.
Example: strstr(name,name1); It returns the location of the first occurrence of name1[] in name[].
It returns null if the string is not found.

These library functions are defined in the header file <string.h>.

15 marks

1. Define data types and explain with examples?

Same answer 8 mark question no.7

2. Explain constant and its types?

Constants are categorized into two basic types, and each of these types has its
subtypes/categories. These are:

1. Numeric Constants
o Integer Constants
o Real Constants
2. Character Constants
o Single Character Constants
o String Constants
o Backslash Character Constants

Integer constant

14
It's referring to a sequence of digits. Integers are of three types viz:

1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6

Real constant

The numbers containing fractional parts like 99.25 are called real or floating points constant.

Single Character Constants

It simply contains a single character enclosed within ' and ' (a pair of single quote). It is to be noted that
the character '8' is not the same as 8. Character constants have a specific set of integer values known as
ASCII values (American Standard Code for Information Interchange).

Example:

'X', '5', ';'

String Constants

These are a sequence of characters enclosed in double quotes, and they may include letters, digits,
special characters, and blank spaces. It is again to be noted that "G" and 'G' are different - because "G"
represents a string as it is enclosed within a pair of double quotes whereas 'G' represents a single
character.

Example:

"Hello!", "2015", "2+1"

Backslash character constant

C supports some character constants having a backslash in front of it. The lists of backslash characters
have a specific meaning which is known to the compiler. They are also termed as "Escape Sequence".

For Example:

15
\t is used to give a tab

\n is used to give a new line

Constants Meaning

\a beep sound

\b backspace

\f form feed

\n new line

\r carriage return

\t horizontal tab

\v vertical tab

\' single quote

\" double quote

\\ backslash

\0 null

3.Explain in detail about different types of operators.

16
Operators are the foundation of any programming language. Thus the functionality of C language is
incomplete without the use of operators. Operators allow us to perform different kinds of operations on
operands. In C, operators in Can be categorized in following categories:
• Arithmetic Operators (+, -, *, /, %, post-increment, pre-increment, post-decrement, pre-
decrement)
• Relational Operators (==, !=, >, <, >= & <=)
• Logical Operators (&&, || and !)
• Bitwise Operators (&, |, ^, ~, >> and <<)
• Assignment Operators (=, +=, -=, *=, etc)
• Other Operators (conditional, comma, sizeof, address, redirecton)
❖ Arithmetic Operators: These are used to perform arithmetic/mathematical operations on operands.
The binary operators falling in this category are:
• Addition: The ‘+’ operator adds two operands. For example, x+y.
• Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
• Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
• Division: The ‘/’ operator divides the first operand by the second. For example, x/y.
• Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second.
For example, x%y.
• Increment: The ‘++’ operator is used to increment the value of an integer. When placed before
the variable name (also called pre-increment operator), its value is incremented instantly. For
example, ++x.
And when it is placed after the variable name (also called post-increment operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the execution
of the next statement. For example, x++.
• Decrement: The ‘ – – ‘ operator is used to decrement the value of an integer. When placed before
the variable name (also called pre-decrement operator), its value is decremented instantly. For
example, – – x.
And when it is placed after the variable name (also called post-decrement operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the execution
of the next statement. For example, x – –.

❖ Relational Operators:
Relational operators are used for comparison of two values. Let’s see them one by one:
• ‘==’ operator checks whether the two given operands are equal or not. If so, it returns true.
Otherwise it returns false. For example, 5==5 will return true.
• ‘!=’ operator checks whether the two given operands are equal or not. If not, it returns true.
Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For
example, 5!=5 will return false.
• ‘>’ operator checks whether the first operand is greater than the second operand. If so, it returns
true. Otherwise it returns false. For example, 6>5 will return true.
• ‘<‘ operator checks whether the first operand is lesser than the second operand. If so, it returns
true. Otherwise it returns false. For example, 6<5 will return false.
• ‘>=’ operator checks whether the first operand is greater than or equal to the second operand. If
so, it returns true. Otherwise it returns false. For example, 5>=5 will return true.
• ‘<=’ operator checks whether the first operand is lesser than or equal to the second operand. If
so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true.

17

❖ Logical Operators:
They are used to combine two or more conditions/constraints or to complement the evaluation of
the original condition in consideration. They are described below:
• Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are
satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true
(i.e. non-zero).
• Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration
is satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b is true (i.e.
non-zero). Of course, it returns true when both a and b are true.
• Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied.
Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0.
❖ Bitwise Operators
• & (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers.
The result of AND is 1 only if both bits are 1.
• | (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The
result of OR is 1 if any of the two bits is 1.
• ^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers.
The result of XOR is 1 if the two bits are different.
• << (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand
decides the number of places to shift.
• >> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand
decides the number of places to shift.
• ~ (bitwise NOT) Takes one number and inverts all bits of it
❖ Assignment operators
Assignment operators are used to assigning value to a variable. The left side operand of the assignment
operator is a variable and right side operand of the assignment operator is a value. The value on the right
side must be of the same data-type of the variable on the left side otherwise the compiler will raise an
error.
Different types of assignment operators are shown below:
• “=”: This is the simplest assignment operator. This operator is used to assign the value on the
right to the variable on the left.

4. Explain the various library functions in detail.

(write some math and string functios)

5. Write a program to calculate the area and perimeter of a circle.

*C program to find area and perimeter of circle.*/

#include <stdio.h>

18
#define PI 3.14f

int main()
{
float rad,area, perm;

printf("Enter radius of circle: ");


scanf("%f",&rad);

area=PI*rad*rad;
perm=2*PI*rad;

printf("Area of circle: %f \nPerimeter of circle: %f\n",area,perm);


return 0;
}
Write explanation in your own words

19
UNIT II

3 marks

1. Define Looping.

In programming, loops are used to repeat a block of code until a specified condition is
met.

C programming has three types of loops:

1. for loop
2. while loop
3. do...while loop
We will learn about for loop in this tutorial. In the next tutorial, we will learn
about while and do...while loop.
2. What is if-else? Give syntax.

An if statement can be followed by an optional else statement, which executes when the
expression is false.

Syntax

The syntax of an if...else statement in C programming language is −


if(expression) {
/* statement(s) will execute if the expression is true */
}
else
{
/* statement(s) will execute if the expression is false */
}

3. Write the syntax of for loop with an example.

A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is −
for ( init; condition; increment ) {
statement(s);

20
}
Here is the flow of control in a 'for' loop −
• The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and the flow of control jumps to the next
statement just after the 'for' loop.
• After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the condition.
4. Name the unconditional control statement.

(1) The “break” Statement :


A break statement terminates the execution of the loop and the control is transferred to the statement.
Syntax :
Jump-statement;
break;
The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.
(2) The “continue” Statement :
The continue statement is used to bypass the remainder of the current pass through a loop.
The loop does not terminate when a continue statement is encountered. Instead, the remaining loop
statements are skipped and the computation proceeds directly to the next pass through the loop.
Syntax :
Jump-statement;
Continue;
The jump statement can be while, do while and for loop.
(3) The “goto” Statement :
C supports the “goto” statement to branch unconditionally from one point to another in the program.
Syntax :
goto label;
.............
.............
label:
statement;
4) Return Statement :
The return statement terminates the execution of a function and returns control to the calling function.
Execution resumes in the calling function at the point immediately following the call.
A return statement can also return a value to the calling function.
Syntax :

21
Jump-statement:
return expression;

5. Give the syntax of switch case statement.

The switch statement allows us to execute one code block among many alternatives.

You can do the same thing with the if...else..if ladder. However, the syntax of
the switch statement is much easier to read and write.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;

case constant2:
// statements
break;
.
.
.
default:
// default statements
}

6. Write the syntax of printf()with example.

The printf() and scanf() functions are used for input and output in C language. Both functions are
inbuilt library functions, defined in stdio.h (header file).

printf() function

The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

printf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

22
7. Write the syntax of scanf() with example.

The printf() and scanf() functions are used for input and output in C language. Both functions are
inbuilt library functions, defined in stdio.h (header file).

scanf() function

The scanf() function is used for input. It reads the input data from the console.

The syntax of scanf() function is given below:

scanf("format string",argument_list);

8. Give the syntax of do while statement.


• A do while loop is similar to while loop with one exception that it executes the
statements inside the body of do-while before checking the condition.
• So you can say that if a condition is false at the first place then the do while would run
once, however the while loop would not run at all.
do..while loop
Syntax of do-while loop
do
{
//Statements

}while(condition test);

9. Write the syntax of getchar() and putchar().

• putchar() function is used to write a character on standard output/screen. In a C program,


we can use putchar function as below.
putchar(char);
• where, char is a character variable/value.

• getchar() function is used to get/read a character from keyboard input. In a C program,


we can use getchar function as below.
getchar(char);
• where, char is a character variable/value.

23
10. What is the difference between break and continue?

ASIS FOR
BREAK CONTINUE
COMPARISON

Task It terminates the execution of It terminates only the current iteration

remaining iteration of the loop. of the loop.

Control after 'break' resumes the control of the 'continue' resumes the control of the

break/continue program to the end of loop program to the next iteration of that

enclosing that 'break'. loop enclosing 'continue'.

Causes It causes early termination of It causes early execution of the next

loop. iteration.

Continuation 'break' stops the continuation of 'continue' do not stops the continuation

loop. of loop, it only stops the current

iteration.

Other uses 'break' can be used with 'switch', 'continue' can not be executed with

'label'. 'switch' and 'labels'.

8 marks

1. Explain conditional control structure with example?

24
Conditional statements help you to make a decision based on certain conditions. These conditions are
specified by a set of conditional statements having boolean expressions which are evaluated to a boolean
value true or false. There are following types of conditional statements in C.
1. If statement
2. If-Else statement
3. Nested If-else statement
4. If-Else If ladder
5. Switch statement

➢ If statement
The single if statement in C language is used to execute the code if a condition is true. It is also called
one-way selection statement.

Syntax
if(expression)
{
//code to be executed
}

➢ If-else statement
The if-else statement in C language is used to execute the code if condition is true or false. It is also
called two-way selection statement.

Syntax
if(expression)
{
//Statements
}
else
{
//Statements
}

➢ Nested If-else statement


The nested if...else statement is used when a program requires more than one test expression. It is also
called a multi-way selection statement. When a series of the decision are involved in a statement, we use
if else statement in nested form.

Syntax
if( expression )
{

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

➢ If..else If ladder
The if-else-if statement is used to execute one code from multiple conditions. It is also called multipath
decision statement. It is a chain of if..else statements in which each if statement is associated with else if
statement and last would be an else statement.

Syntax
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if(condition3)
{
//statements
}
else
{

26
//statements
}

➢ Switch Statement
switch statement acts as a substitute for a long if-else-if ladder that is used to test a list of cases. A
switch statement contains one or more case labels which are tested against the switch expression. When
the expression match to a case then the associated statements with that case would be executed.

Syntax
Switch (expression)
{
case value1:
//Statements
break;
case value 2:
//Statements
break;
case value 3:
//Statements
case value n:
//Statements
break;
Default:
//Statements
}

2. Discuss about formatted I/O functions.

Formatted Input

The function scanf() is used for formatted input from standard input and provides many of
the conversion facilities of the function printf().

Syntax

scanf(format,num1,num2,……);

27
The function scnaf() reads and converts characters from the standards input depending
on the format specification string and stores the input in memory locations represented
by the other arguments (num1, num2,….).

For Example:
scanf(“ %c %d”,&Name, &Roll No);

Formatted Output

The function printf() is used for formatted output to standard output based on a format
specification. Syntax:
printf (format, data1, data2,……..);
In this syntax format is the format specification string. This string contains, for each
variable to be output, a specification beginning with the symbol % followed by a
character called the conversion character.
Example:
printf (“%c”, data1);

See the following table conversion character and their meanings.

Conversion
Meaning
Character
d The data is converted to decimal (integer)
c The data is taken as a character.
The data is a string and character from the string , are printed until a NULL,
s
character is reached.
f The data is output as float or double with a default Precision 6.

Symbols Meaning
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)

3. Write a program to add the digits of a given number using do-while

28
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at
least one time.

Syntax

The syntax of a do...while loop in C programming language is −


do {
statement(s);
} while( condition );

Program

#include<stdio.h>

#include<conio.h>

void main()

int num,sum;

` clrscr();

printf(|”Enter any integer”);

scanf(“%d”,&num);

sum=0;

do

sum=num%10;

num=num/10;

} while(num>0);

Printf(“The sum of digits is%d=”,sum);

getch|();

29
OUTPUT

Enter any integer 123

The sum of digits is=6

(write explanation about program in your own words)

4. Differentiate between while and do-while?

WHILE DO-WHILE

Condition is checked first then statement(s) Statement(s) is executed atleast once,

is executed. thereafter condition is checked.

It might occur statement(s) is executed zero

times, If condition is false. At least once the statement(s) is executed.

No semicolon at the end of while. Semicolon at the end of while.

while(condition) while(condition);

If there is a single statement, brackets are not

required. Brackets are always required.

Variable in condition is initialized before the variable may be initialized before or within

execution of loop. the loop.

30
WHILE DO-WHILE

while loop is entry controlled loop. do-while loop is exit controlled loop.

while(condition) do { statement(s); }

{ statement(s); } while(condition);

5. Write a program to find whether the given number is even or not.

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

printf("Enter an integer: ");


scanf("%d", &number);

// True if the number is perfectly divisible by 2


if(number % 2 == 0)
printf("%d is even.", number);
else
printf("%d is odd.", number);

return 0;
}

31
OUTPUT

Enter an integer : 7

7 is odd

Enter an integer :14

14 is even

write explanation about program in your own words)

6. Write in detail about GOTO statement with explain.

• The goto statement is a jump statement which is sometimes also referred to as


unconditional jump statement.
• The goto statement can be used to jump from anywhere to anywhere within a
function.
Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
label: | goto label;

• In the above syntax, the first line tells the compiler to go to or jump to the statement
marked as a label. Here label is a user-defined identifier which indicates the target
statement.
• The statement immediately followed after ‘label:’ is the destination statement. The
‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.
Example:-

// C program to check if a number is


// even or not using goto statement
#include <stdio.h>

void checkEvenOrNot(int num)


{

32
if (num % 2 == 0)

goto even;
else

goto odd;

even:
printf("%d is even", num);

return;
odd:
printf("%d is odd", num);
}

int main() {
int num = 26;
checkEvenOrNot(num);
return 0;
}

OUTPUT
26 is even

7. Explain about for statement with example.

A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
Syntax

33
The syntax of a for loop in C programming language is −
for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a 'for' loop −
• The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and the flow of control jumps to the next
statement just after the 'for' loop.
• After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the condition.
Example :-
#include<stdio.h>
int main()
{
int i;
for (i=1; i<=3; i++)
{
printf("%d\n", i);
}
return 0;
}

OUTPUT

15 marks

34
1. Explain I/O functions.

scanf() function

The function scanf() is used for formatted input from standard input and provides many of
the conversion facilities of the function printf().

Syntax

scanf(format,num1,num2,……);
The function scnaf() reads and converts characters from the standards input depending on
the format specification string and stores the input in memory locations represented by
the other arguments (num1, num2,….).

For Example:
scanf(“ %c %d”,&Name, &Roll No);

printf() function

The function printf() is used for formatted output to standard output based on a format
specification. Syntax:
printf (format, data1, data2,……..);
In this syntax format is the format specification string. This string contains, for each
variable to be output, a specification beginning with the symbol % followed by a
character called the conversion character.
Example:
printf (“%c”, data1);

See the following table conversion character and their meanings.

Conversion
Meaning
Character
d The data is converted to decimal (integer)
c The data is taken as a character.
The data is a string and character from the string , are printed until a NULL,
s
character is reached.
f The data is output as float or double with a default Precision 6.
2.
Symbols Meaning

35
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)

getchar() & putchar() functions


• The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time.
• The putchar() function displays the character passed to it on the screen and returns the same
character. In case you want to display more than one characters, use putchar() method in a loop.

gets() & puts() functions


• The gets() function reads a line from stdin(standard input) into the buffer pointed to
by str pointer, until either a terminating newline or EOF (end of file) occurs.
• The puts() function writes the string str and a trailing newline to stdout.

3. Explain in detail about if statements with examples?

➢ If statement
The single if statement in C language is used to execute the code if a condition is true. It is also called
one-way selection statement.

Syntax
if(expression)
{
//code to be executed
}
How "if" statement works..
• If the expression is evaluated to nonzero (true) then if block statement(s) are executed.
• If the expression is evaluated to zero (false) then Control passes to the next statement following
it.

➢ If-else statement
The if-else statement in C language is used to execute the code if condition is true or false. It is also
called two-way selection statement.

36
Syntax
if(expression)
{
//Statements
}
else
{
//Statements
}

How "if..else" statement works..


• If the expression is evaluated to nonzero (true) then if block statement(s) are executed.
• If the expression is evaluated to zero (false) then else block statement(s) are executed.

➢ Nested If-else statement


The nested if...else statement is used when a program requires more than one test expression. It is also
called a multi-way selection statement. When a series of the decision are involved in a statement, we use
if else statement in nested form.

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

37
➢ If..else If ladder
The if-else-if statement is used to execute one code from multiple conditions. It is also called multipath
decision statement. It is a chain of if..else statements in which each if statement is associated with else if
statement and last would be an else statement.

Syntax
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if(condition3)
{
//statements
}
else
{
//statements
}

4. Write a C program to count the number of vowels, consonants and spaces using switch case.

refer record program

5. Explain about while and do while statements in detail?

write the same answer fron 8 mark question 3

38
UNIT-III
FUNCTIONS AND STORAGE CLASSES

3 marks

1. Define functions?
A function is a group of statements that together perform a task. Every C
program has at least one function, which is main(), and all the most trivial programs can
define additional functions.

2. Define: Actual parameters.


A parameter or argument is data which is taken as input or considered as
additional information by the function for further processing. The parameters which are
passed in the function call are known as actual parameters or actual arguments.

3. What are static variables?


Static variables have a property of preserving their value even after they are out
of their scope. Hence, static variables preserve their previous value in their previous
scope and are not initialized again in the new scope.
4. What is recursion?
Recursion is the process of repeating items in a self-similar way. In programming
languages, if a program allows you to call a function inside the same function, then it is
called a recursive call of the function.

void recursion()
{
recursion(); /* function calls itself */
}

39
int main()
{
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But
while using recursion, programmers need to be careful to define an exit condition from
the function; otherwise it will go into an infinite loop.

5. What is local variable?


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.

40
Example:
#include
<stdio.h> int
main ()
{
/* local variable declaration */
int a, b;
int c;

/* actual initialization
*/ a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b,
c); return 0;
}

6. What are automatic variables?


The features of a variable defined to have an automatic storage class are as given below:
o Storage − Memory.
o Default initial value − An unpredictable value, which is often called a
garbage value.
o Scope − Local to the block in which the variable is defined.
o Life − Till the control remains within the block in which the variable is defined.

7. Define function header?


• Function header is also called as function prototype
• This informs compiler about the function name, function parameters and
return value’s data type.

• The general syntax of function prototype/header :

return-type function-name(parameter-list);

41
• Example:
void display( );

8. Define function Prototype.


REFER THE SAME ANSWER GIVEN FOR QUESTION NO. 7

9. List out the types of storage classes.


In C, there are only two storage places namely memory and CPU registers. To
completely declare a variable, we need to mention the data type and storage class of the
variable. In other words, not only do all variables have a data type, they also have a
‘storage classes.
There are four storage classes in C:
(a) Automatic storage class
(b) Register storage class
(c) Static storage class
(d) External storage class

10. What is call by value?


• The call by value method of passing arguments to a function 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.

• By default, C programming 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.

8 marks

1. Write a c program to find a factorial of a number using function.


#include<stdio.h
>

42
#include<math.h
> void main()
{
//clrscr();
printf("Enter a Number to Find Factorial: ");
fact();
getch();
}
int fact()
{
int i,fact=1,n;
scanf("%d",&n);
for(i=1; i<=n; i++)
{
fact=fact*i;
}
printf("\nFactorial of a Given Number is: %d ",fact);
return fact;
}
OUTPUT:

Enter a Number to Find Factorial: 5


Factorial of a Given Number is: 120

2. Explain the general format for defining a function.


• C functions are basic building blocks in a program. All C programs are written
using functions to improve re-usability, understandability and to keep track on
them. You can learn below concepts of C functions in this section in detail.
• A large C program is divided into basic building blocks called C function. C
function contains set of instructions enclosed by “{ }” which performs specific
operation in a C program. Actually, Collection of these functions creates a C
program.
• C functions are used to avoid rewriting same logic/code again and again in a

43
program.
• There is no limit in calling C functions to make use of same functionality
wherever required.
• We can call functions any number of times in a program and from any place in a
program.
• A large C program can easily be tracked when it is divided into functions.
• The core concept of C functions are, re-usability, dividing a big task into small
pieces to achieve the functionality and to improve understandability of very large
C programs.

• The general format for defining a function:

❖ Function declaration or prototype – This informs compiler about the


function name, function parameters and return value’s data type.
❖ Function call – This calls the actual function.
❖ Function definition – This contains all the statements to be executed.

• Syntax

• SIMPLE EXAMPLE PROGRAM FOR C FUNCTION:


❖ As you know, functions should be declared and defined before calling in a C
program.
❖ In the below program, function “square” is called from main function.
❖ The value of “m” is passed as argument to the function “square”. This value is
multiplied by itself in this function and multiplied value “p” is returned to
main function from function “square”.

44
• Example Program:
#include<stdio.h>
float square ( float x
); int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square
\n"); scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}

float square ( float x ) // function definition


{
float p ;
p=x*x;
return ( p )
;
}
• Output:
Enter some number for finding square
2
Square of the given number 2.000000 is 4.000000

3. How functions are defined in C? Explain with an example.


REFER THE SAME ANSWER GIVEN FOR PREVIOUS QUESTION

4. What is recursion? Explain with example.


• Recursion is the process of repeating items in a self-similar way. In programming
languages, if a program allows you to call a function inside the same function,
then it is called a recursive call of the function.

45
void recursion()

recursion(); /* function calls itself */

int main()

recursion();

• The C programming language supports recursion, i.e., a function to call itself.


But while using recursion, programmers need to be careful to define an exit
condition from the function; otherwise it will go into an infinite loop.
• Recursive functions are very useful to solve many mathematical problems, such
as calculating the factorial of a number, generating Fibonacci series, etc.
• Example Program:

❖ Number Factorial

The following example calculates the factorial of a given number using a


recursive function −
#include <stdio.h>
unsigned long long int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);

46
}

int main()
{
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;

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

Factorial of 12 is 479001600

❖ Fibonacci Series

The following example generates the Fibonacci series for a given


number using a recursive function −
#include <stdio.h>
int fibonacci(int i)
{

if(i == 0)
{ return
0;
}

if(i == 1)
{ return
1;
}
return fibonacci(i-1) + fibonacci(i-2);
}

47
int main() {

int i;

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


printf("%d\t\n", fibonacci(i));
}

return 0;
}
❖ When the above code is compiled and executed, it produces the following
result −

0
1
1
2
3
5
8
13
21
34

48
15 marks

1. Explain functions and its prototypes.


▪ A function is a group of statements that together perform a task.
▪ Every C program has at least one function, which is main().
▪ You can divide up your code into separate functions.
▪ There are two types of functions in C

▪ Library Functions: functions which are declared in the C header files such
as scanf(), printf(), gets(), puts(), clrscr(), getch() etc.

▪ User-defined functions: functions which are created by the C programmer, so


that he/she can use it many times. It reduces complexity of a big program and
optimizes the code.

▪ There are three important features to be considered when we define a function


• Function prototype/ header
• Function definition
• Function call

❖ Function prototype/header
• Function header is also called as function prototype
• This informs compiler about the function name, function parameters and
return value’s data type.

• The general syntax of function prototype/header :

49
return-type function-name(parameter-list);

• Example:

void display( );

❖ Function Definition

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


as follows

return_typefunction_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
called, 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; i.e.,
a function may contain no parameters.

• Function Body − the function body contains a collection of statements


that define what the function does.
• Example:

50
❖ Function call
void display()
{
//body
}

51
• The function call is nothing but calling the function
• Function can be called either with parameters or no parameters
• The general syntax for calling a function is given below:

Function_name(parameter – list);

Example: display(); // calling display() function with no parameters

❖ In C, we can define functions in 4 different ways as given below:


➢ Type 1: no return value function name no parameters
➢ Type 2: no return value function name with parameters
➢ Type 3: with return value function name no parameters
➢ Type 4: with return value function name with parameters

Example:
Type1: void show()
{
}
Type2: void show(int a)
{
}

Type3: int show()


{
return;
}
Type4: Int void show(inta,int b)
{
return;
}

52
Program:
TO ADD TWO NUMBERS USING FUNCTION WITH ARGUMENTS
#include <stdio.h>
void sum(int,int); //function prototype
void main ()

{
clrscr();
sum(7,3); //function
call getch();

}
void sum(inta,int b) //function definition
{
int c;
c=a+b;
printf("sum=%d\n",c);
}
output:
sum=10

2. Explain about various storage classes in C with examples.


• In C, there are only two storage places namely memory and CPU registers
• To completely declare a variable, we need to mention the data type and storage
class of the variable

• In other words, not only do all variables have a data type, they also have a
‘storage class’.

• Moreover, a variable’s storage class tells us:


(a) Where the variable would be stored.
(b) What will be the initial value of the variable, if initial value is not
specifically assigned.(i.e. the default initial value).

53
(c) What is the scope of the variable; i.e. in which functions the value of the
variable would be available.
(d) What is the life of the variable; i.e. how long would the variable exist

• There are four storage classes in C:


(a) Automatic storage class
(b) Register storage class
(c) Static storage class
(d) External storage class

❖ Automatic Storage Class


• The features of a variable defined to have an automatic storage class are
as under:

• Storage − Memory.
• Default initial value − An unpredictable value, which is often called a
garbage value.

• Scope − Local to the block in which the variable is defined.


• Life − Till the control remains within the block in which the variable is
defined.
Example:
void main( )
{
autoint i=5;
printf ( "%d\n", i) ;
}
The output of the above program could be...
5

54
❖ Register Storage Class
• The features of a variable defined to have an register storage class are
as under:

• Storage – CPU registers if registers are available otherwise it will be in


stored in memory.

• Default initial value − An unpredictable value, which is often called a


garbage value.

• Scope − Local to the block in which the variable is defined.


• Life − Till the control remains within the block in which the variable is
defined.

Example:
void main( )
{
registerint i=5;
printf ( "%d\n", i)
;
}

The output of the above program could be...


5

❖ Static Storage Class


• The features of a variable defined to have an static storage class are as under:
• Storage – memory
• Default initial value − zero. Static variables cannot be re-initialized.
• Scope − Local to the block in which the variable is defined.
• Life – value will persist between different function calls.

Example:

55
void
display();
void main( )
{
display()
;
display()
;
display()
; getch();
}
void display()
{
Static int i;
printf(“%d\t”,i);
i++;
}

The output of the above program could


be... 0 1 2

❖ External Storage Class


• The features of a variable defined to have an external storage class are
as under:

• Storage – memory.
• Default initial value −zero.
• Scope – Global.
• Life − As long as the program’s execution doesn’t come to an end.

Example:
void main()

56
{
int x = 21 ;
externint y ;
printf ( "\n%d %d", x, y ) ;
}
int y = 31;

consider the following two statements:


externint y ;
int y = 31 ;
• Here the first statement is a declaration, whereas the second is the
definition. When we declare a variable no space is reserved for it, whereas,
when we define it space gets reserved for it in memory.

• We had to declare y since it is being used in printf( ) before it’s definition is


encountered. There was no need to declare x since its definition is done
before its usage.

3. Describe call by value and call by reference with example.

❖ Call by Value
• The call by value method of passing arguments to a function 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.

• By default, C programming 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.

✓ Example:

57
#include<stdio.h>
#include<conio.h>
void swap(int x, int y); //calling function by value
void main()
{
int a=100;
int b=200;
printf("Before swap, values of a,b : %d %d\n", a,b
); swap(a,b); // calling a function to swap the values
printf("After swap, values of a,b : %d %d\n", a,b );
getch();
}
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x
*/ x = y; /* put y into x */
y = temp; /* put temp into y */
printf("After swap, values of x,y : %d %d\n", x,y );
}

output:

Before swap, values of a,b :100 200


After swap, values of x,y : 200 100
After swap, values of a,b :100 200

❖ Call by reference

• The call by reference method of passing arguments to a function copies


the address of an argument into the formal parameter.
• Inside the function, the address is used to access the actual argument used in

58
the call. It means the changes made to the parameter affect the passed
argument.
• To pass a value by reference, argument pointers are passed to the functions
just like any other value.

✓ Example:

#include<stdio.h>
#include<conio.h>
void swap(int*, int*); //calling function by reference
void main()
{
int a=100;
int b=200;
printf("Before swap, values of a,b : %d %d\n", a,b );
swap(&a,&b); // calling a function to swap the values
printf("After swap, values of a,b : %d %d\n", a,b );
getch();
}
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value of x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
}

Output:

Before swap, values of a,b :100


200 After swap, values of a,b :200

59
100

4. Write a C program to sort a given number in ascending order.

#include<stdio.h>
#include<conio.h
> void main()
{
intarr[10],n,i,j;
clrscr();
printf("SORTING ELEMENTS IN AN ARRAY USING BUBBLE SORT\n");
printf("*******************************************************\n")
; printf("enter n:");
scanf("%d",&n);
printf("\nenter elements in array:");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("Elements before sorting
are:\n"); for(i=0;i<n;i++)
printf("%d\n",arr[i])
; for(i=0;i<=n-
2;i++)
{
for(j=i+1;j<=n-1;j++)
{
if(arr[i]>arr[j])
{
int temp;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}

60
printf("Elements after sorting
are:\n"); for(i=0;i<n;i++)
printf("%d\n",arr[i])
; getch();
}
Output :

Unit IV
3 marks
1. Define an array?
• An array is a collection of data items, all of the same type, accessed using a common
name.
• A one-dimensional array is like a list; A two dimensional array is like a table;
• The C language places no limits on the number of dimensions in an array.
Example:- a[10]---one dimensional array.
a[10][10]--- two dimensional array,
a[10][10][10]--- multi dimensional array.

2. Give an example to initialize an array.


We can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
balance[4] = 50.0; //assigns the 5th element in the array with a value of 50.0.
*int mark[5]; for(int i=0;i<5;i++) scanf(“%d”,&mark[i]);
3. List the types of array.
There are three types of arrays, One dimensional array, Two dimensional array and Multi
dimensional array,
ONE DIMENSIONAL ARRAY
• Single or One Dimensional array is used to represent and store data in a linear form.
• Array having only one subscript variable is called One-Dimensional array
• It is also called as Single Dimensional Array or Linear Array

61
TWO DIMENSIONAL ARRAY
• Array having only 2 subscript variable is called Two-dimensional array.
• Two Dimensional Array is also called as Matrix.

MULTI DIMENSIONAL ARRAY


• Array having more than one subscript variable is called Multi-dimensional array.
• Multi Dimensional Array is also called as Matrix.

4. Define user defined function?


• A function is a block is a code that performs a specific task.
• These are those functions which are defined by the user at the time of writing program.
• These functions are made for code reusability and for saving time and space.
An user-defined has 3 important steps to be followed

*Function declaration:
Syntax:
return data_type function_name(arguments list);

*Function Definition:
Syntax:
return data_typefunction_name(argument list)
{
Body of the function;
}
*FunctionCalling:
Syntax:
Function_name(param_list);
5. What is structure variable?
• A structure creates a data type that can be used to group items of possibly
different types into a single type.
• Structure is a collection of variables (can be of different types) under a single
name.
• It allocates storage space for all its members separately. ‘struct’ keyword is used
to create a structure.
Syntax of structure

62
struc tstructure_name
{
data_type member1;
data_type member2;
.
.
data_typememeber;
};

A structure variable declaration is is similar to declaration of normal variable. But it


includes the following elements,
1. The key word struct
2. The structure tag name
3. List of variable names separated by commas
4. A terminating semicolon.
Example:-
struct emp
{
char name[40];
int age;
float salary;
};

6. Define structure.
A structure is a user defined data type in C. A structure creates a data type that can be used
to group items of possibly different types into a single type.
A structure is a convenient tool for handling a group of logically related data.
General syntax is
struct structure_name
{
data_type member1;
data_type member2;
.

63
.
data_typememeber;
};

7. Define union.

• A union is a special data type available in C that allows 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.
Syntax :-
union union_tag
{
data_type member1;
data_type member2;
.
.
data_typememeber;
};

8. How do you access a structure member?


In structure ,the member themselves are not variables.
In order to make meaningful member , we should link the member to structures using (.) dot
operator.
Here title.book3 is gives the meaning of title of the book3.
Example:-
Struct book_bank
{
char title[40];
char author[40];
int page;
float price;
}book1,book2,book3;
Accessing the above structure is follows,

64
Strcpy(book1.title,”PROGRAMMING IN C”);
Strcpy(book1.author,”BALAGURUSAMY”);
Book1.pages=250;
Book1.price=159.50;

8 marks

1. Write a program to find the transpose of a given matrix.


Refer record
2. Explain briefly about arrays and give examples.
• An array is a collection of data items, all of the same type, accessed using a common name.
int arr[5] is a array variable. Here arr is the variable name. It shares the same name for five
elements. That is, arr[0],arr[1],arr[2],arr[3]and arr[4];

• A one-dimensional array is like a list; A two dimensional array is like a table;


• The C language places no limits on the number of dimensions in an array.
▪ Example:- a[10]---one dimensional array.
▪ a[10][10]--- two dimensional array,
▪ a[10][10][10]--- multi dimensional array.
• We can initialize an array in C either one by one or using a single statement as follows.
o double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
o double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
o balance[4] = 50.0; //assigns the 5th element in the array with a value of 50.0.
o int mark[5]; for(int i=0;i<5;i++) scanf(“%d”,&mark[i]);
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
int i,arr[30], i, n=5;
printf(“Enter any five numbers”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
for(i=0;i<n;i++)

65
printf(“Array of [%d] is =%d”, i,arr[i]);
getch();
}

3. Write a program to find the sum and average using arrays.


#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,arr[20],average,sum=0;
clrscr();
printf(“Enter number of element”);
scanf(“%d”,&n);
printf(“Enter array element”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nArray is ”);
for(i=0;i<n;i++)
printf(“%d\n”,arr[i]);
for(i=0;i<n; i++)
{
sum=sum+arr[i];
}
printf(“The sum of array is =%d”,sum);
paverage=sum/n;
printf(“The average is %d”,average);
getch():
}

4. Explain union with example.


A union is a user-defined type similar to structs in C programming.

66
We use the union keyword to define unions. Here's: an example
union car
{
char name[50];
int price;
};
Creation of union variables
union car
{
char name[50];
int price;
};

int main()
{
union car car1, car2, *car3;
return 0;
}
Access members of a union
We use the . operator to access members of a union. To access pointer variables, we use also use the -
> operator.

In the above example,


• To access price for car1, car1.price is used.
• To access price using car3, either (*car3).price or car3->price can be used.

5. Explain structure with example.


A structure is a user defined data type in C/C++. A structure creates a data type that can be
used to group items of possibly different types into a single type.
A structure is a convenient tool for handling a group of logically related data
General syntax is
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_typememeber;
};

To initialize structure at compile time we have to follow the following rules,

67
1. The keyword struct
2. The structure tag name
3. The name of the variable to be declared
4. The assignment operator =
5. Set of values for the members of the structure variables ,separated by commas and
enclosed in brace.
6. A terminating semi colon.
Way of Declare and Initialize

struct student
{
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };

In the above code snippet, we have seen that structure is declared and as soon as after declaration we
have initialized the structure variable.

6. Differentiate structure with union.

Difference between unions and structures

Let's take an example to demonstrate the difference between unions and structures:
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;

struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;

int main()

68
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
Output

size of union = 32
size of structure = 40

7. How to initialize a structure explain in detail with example.

To initialize structure at compile time we have to follow the following rules,


1. The keyword struct
2. The structure tag name
3. The name of the variable to be declared
4. The assignment operator =
5. Set of values for the members of the structure variables ,separated by commas and
enclosed in brace.

69
6. A terminating semi colon.

When we declare a structure, memory is not allocated for un-initialized variable.

Let us discuss very familiar example of structure student , we can initialize structure variable in

different ways –

Way of Declare and Initialize


struct student
{
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };

In the above code snippet, we have seen that structure is declared and as soon as after declaration we
have initialized the structure variable.

15 marks

1. Explain in detail about arrays and its types with examples.


• An array is a collection of data items, all of the same type, accessed using a common
name.
• A one-dimensional array is like a list; A two dimensional array is like a table;
• The C language places no limits on the number of dimensions in an array.
Example:- a[10]---one dimensional array.
a[10][10]--- two dimensional array,
a[10][10][10]--- multi dimensional array.
There are three types of arrays, One dimensional array, Two dimensional array and
Multi dimensional array,
ONE DIMENSIONAL ARRAY
• Single or One Dimensional array is used to represent and store data in a linear form.
• Array having only one subscript variable is called One-Dimensional array
• It is also called as Single Dimensional Array or Linear Array
TWO DIMENSIONAL ARRAY
• Array having only 2 subscript variable is called Two-dimensional array.
• Two Dimensional Array is also called as Matrix.

70
MULTI DIMENSIONAL ARRAY
• Array having more than one subscript variable is called Multi-dimensional array.
• Multi Dimensional Array is also called as Matrix.
Example program for arrays
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,arr[20],average,sum=0;
clrscr();
printf(“Enter number of element”);
scanf(“%d”,&n);
printf(“Enter array element”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nArray is ”);
for(i=0;i<n;i++)
printf(“%d\n”,arr[i]);
for(i=0;i<n; i++)
{
sum=sum+arr[i];
}
printf(“The sum of array is =%d”,sum);
paverage=sum/n;
printf(“The average is %d”,average);
getch():
}

2. Write a program for matrix addition.


Refer record

71
3. Explain the string manipulation functions with examples.

• C supports a large number of string handling functions in the standard library. Strings
handling functions are defined under "string.h" header file.

• Few commonly used string handling functions are discussed below:

Function Work of Function

strlen() Calculates the length of string

strcpy() Copies a string to another string

strcat() Concatenates(joins) two strings

strcmp() Compares two string

strlwr() Converts string to lowercase

strupr() Converts string to uppercase

Example program :- palindrome checking using string functions.


#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
char s1[40],s2[40];
clrscr():
printf(“Enter any string”);
scanf(“%s”,s1);

72
srtcpy(s2,s1);
strrev(s2);
if(srtcmp(s2,s1)==0)
printf(“GIVEN STRING IS PALINDROME”);
else
printf(“GIVENSTRING NOT PALINDROME”);
getch();
}
OUTPUT
Enter any string
Selvi
GIVEN STRING IS NOT PALINDTROME
Enter any string
madam
GIVEN STRING IS PALINDROME

4. Explain the structure and union.


A structure is a user defined data type in C. A structure creates a data type that can be used to
group items of possibly different types into a single type.
A structure is a convenient tool for handling a group of logically related data.
General syntax is
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_typememeber;
};
• A union is a special data type available in C that allows 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.

73
Syntax :-
union union_tag
{
data_type member1;
data_type member2;
.
.
data_typememeber;
};
Example program for structure and union
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;

struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;

int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
Output

size of union = 32
size of structure = 40

74
75

You might also like