C PRG
C PRG
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?
• 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.
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 .
• Increment operators are used to increase the value of the variable by ONE.
Syntax:
Incremen toperator: ++var_name; (or) var_name++;
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
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.
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.
3
continue goto sizeof volatile
default if static while
double Int struct packed
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:
For example :-
4
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
For example:-
5
8 marks
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
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
#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
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 initialization data_type variable_name =
value; 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
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
▪ 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.
15 marks
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.
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:
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:
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
Constants Meaning
\a beep sound
\b backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\0 null
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.
#include <stdio.h>
18
#define PI 3.14f
int main()
{
float rad,area, perm;
area=PI*rad*rad;
perm=2*PI*rad;
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.
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
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.
21
Jump-statement:
return expression;
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
}
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.
printf("format string",argument_list);
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.
scanf("format string",argument_list);
}while(condition test);
23
10. What is the difference between break and continue?
ASIS FOR
BREAK CONTINUE
COMPARISON
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
loop. iteration.
Continuation 'break' stops the continuation of 'continue' do not stops the continuation
iteration.
Other uses 'break' can be used with 'switch', 'continue' can not be executed with
8 marks
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
}
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
}
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);
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)
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
Program
#include<stdio.h>
#include<conio.h>
void main()
int num,sum;
` clrscr();
scanf(“%d”,&num);
sum=0;
do
sum=num%10;
num=num/10;
} while(num>0);
getch|();
29
OUTPUT
WHILE DO-WHILE
while(condition) while(condition);
Variable in condition is initialized before the variable may be initialized before or within
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);
#include <stdio.h>
int main()
{
int number;
return 0;
}
31
OUTPUT
Enter an integer : 7
7 is odd
14 is even
• 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:-
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
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);
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)
➢ 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
}
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.
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.
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.
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;
}
return-type function-name(parameter-list);
41
• Example:
void display( );
• In this case, changes made to the parameter inside the function have no effect on
the argument.
8 marks
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:
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.
• Syntax
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 );
}
45
void recursion()
int main()
recursion();
❖ Number Factorial
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
if(i == 0)
{ return
0;
}
if(i == 1)
{ return
1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
47
int main() {
int 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
▪ Library Functions: functions which are declared in the C header files such
as scanf(), printf(), gets(), puts(), clrscr(), getch() etc.
❖ 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.
49
return-type function-name(parameter-list);
• Example:
void display( );
❖ Function Definition
• 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.
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:
Type1: void show()
{
}
Type2: void show(int a)
{
}
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
• In other words, not only do all variables have a data type, they also have a
‘storage class’.
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
• Storage − Memory.
• Default initial value − An unpredictable value, which is often called a
garbage value.
54
❖ Register Storage Class
• The features of a variable defined to have an register storage class are
as under:
Example:
void main( )
{
registerint i=5;
printf ( "%d\n", i)
;
}
Example:
55
void
display();
void main( )
{
display()
;
display()
;
display()
; getch();
}
void display()
{
Static int i;
printf(“%d\t”,i);
i++;
}
• 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;
❖ 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.
✓ 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:
❖ Call by reference
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:
59
100
#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.
61
TWO DIMENSIONAL ARRAY
• Array having only 2 subscript variable is called Two-dimensional array.
• Two Dimensional Array is also called as Matrix.
*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;
};
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;
};
64
Strcpy(book1.title,”PROGRAMMING IN C”);
Strcpy(book1.author,”BALAGURUSAMY”);
Book1.pages=250;
Book1.price=159.50;
8 marks
65
printf(“Array of [%d] is =%d”, i,arr[i]);
getch();
}
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.
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.
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
69
6. A terminating semi colon.
Let us discuss very familiar example of structure student , we can initialize structure variable in
different ways –
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
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():
}
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.
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
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