TS Programming in C Final 23-01-2022 With Preface
TS Programming in C Final 23-01-2022 With Preface
As Per C-21
Programming in C
Common to All Branches - 1st Year II Semester Diploma Students
Teaching Scheme
4:1:0 Credits 3
in Periods (L:T:P)
Total Contact
Methodology Lecture +Tutorial 75
Periods
OBJECTIVES
1.0. Programming Methodology and Introduction to C Language
1.1. State different steps involved in problem solving
1.2. Define algorithm and know its characteristics
1.3. State the steps involved in algorithm development
1.4. Develop algorithms for simple problems.
1.5. Define flowchart and know symbols used in drawing flowcharts
1.6. Draw flowchart for simple problems.
1.7. Differentiate algorithm and flowchart
1.8. Define program and differentiate between program and algorithm
1.9. Define High level language and low level language
1.10. Define Compiler, Assembler, Linker and Loader
1.11. Define source code, assembly code, object code, machine code.
1.12. state the importance of C language
1.13. Explain the structure of C program
1.14. List and Explain different stages in converting the C program source
code to executable code.
1.15. Explain the steps involved in executing the C program
Programming Methodology and Introduction to C Language 1-2
5. Pseudocode
o A pseudocode is neither an algorithm nor a program.
o It is an abstract form of a program. It consists of English like statements, which
perform the specific operations.
o It is defined for an algorithm.
o It does not use anigraphical representation.
o In a pseudocode, the program is represented in terms of words and phrases,
but the syntax of a program is not strictly followed.
o Advantages
Easy to read
Easy to understand
Easy to modify
The program can be developed easily from a pseudo code rather than a
flowchart.
Example 1: Write a pseudocode to perform the basic arithmetic operations.
Solution:
Read n1, n2
Sum = n1 + n2
Diff = n1 - n2
Mult = n1 * n2
Quot = n1/n2
Print sum, diff, mult, quot
End
6. Coding
o The complete structure of a problem to be solved by a computer is called a
program.
o The computer does not process an algorithm or a flowchart, but executes the
program.
o A program is a set of instructions to solve a particular problem by the
computer and the actual process of writing a program is called coding.
o Programs are written using programming languages and are fed to the
computer.
Rectangle Processing
Arrows Connections
Circle Continuation
Example 2: Draw a flowchart to find the area of a triangle when its three
sides are given.
Example:
The assembly language program (ALP) that is given as input to the assembler is
called source program and the output of the assembler is called object program.
There are different assembler programs available in the software market.
Example: TASM (Turbo Assembler), MASM (Macro Assembler).
1.10.2. Compiler
The process of translating high level language program into machine language
requires an intermediatory program called the translator.
The compiler and interpreter are two translator programs that are used to translate
the high level language programs into machine language.
Here, also the program written in high level language is called source program.
The corresponding program after translation (either by compiler or interpreter) is
called object program.
The high level language program to machine level conversion is shown in figure.
a) Linker vs Loader
Linker is the software that links the object The loader is the system software that
code with additional files such as header loads the executable file generated by the
files and creates an executable file with linker to the main memory.
.exe extension.
Linker Helps to link a object modules of program into a single object file.
It is executable file as output for loader.
* Programming Language *
* Applications of ‘C’ *
Because of its portability and efficiency, C is used to develop the system as well as
application software. Some of the system and application softwares are listed
below.
a) System Software
1. Operating system
2. Interpreters
3. Compliers
4. Assemblers
5. Editors
6. Loaders
7. Linkers
b) Application Software
1. Graphics Packages
2. Spread Sheets
3. Office Automation Tools
4. Word Processors
5. Scientific and Engineering Application
6. Data Base Management System (DBMS)
Part-I
Documentation section
Link (preprocessor)section
Definition section
Global Declaration section
OR Part-II
main() Function section
{
Declaration part;
Executable part;
}
Part-III
User defined functions
4. Global Declarations
There are some variables that are used in more than one function. Such variables
are called global variables whose existence is known throughout the program. This
declaration should be made before main() function.
Examples:
1. inta,b,c;
2. float x,y,z;
3. char name[20];
OBJECTIVES
2.1 Describe character set, C Tokens-Keywords, Variables, Identifiers,
Constants and Variables.
2.2 Define Data type. Classify data types and explain with examples
2.3 Explain declaration of a variable and assigning values to variables
2.4 Define operator.
2.5 Classify and Explain operators with examples
2.6 Describe precedence and associativity of operators
2.7 Define expression
2.8 Describe evaluation of Arithmetic, Relational and logical expressions
2.9 Illustrate type conversion techniques.
2.10 Define and List Pre-processor directives
2.11 Discuss #include and #define Pre-processor directives.
2.12 Define Header file and discuss stdio.h, conio.h, math.h, string.h
Header files.
2.13 Illustrate getchar(),putchar(),scanf(),printf() with programs.
Constants, variables, data types, input output functions 2-2
2.1.4. Variables
The quantity that changes during the execution of a program is called a variable.
A variable is a data name that may be used to store a data value.
A variable name can be chosen by the programmer in meaningful way so as to the
reflect its function or nature in the program.
Rules for Forming Variable Names
1. Variable names may consist of letters, digits and the underscore (_).
2. The first character of a variable name must be an alphabet or an underscore (_).
3. A variable name should not be of length more than 8 characters.
4. Both uppercase and lowercase variables are significant in C.
5. White space is not allowed.
6. Keywords should not be used as variables.
7. No commas ( , ) are allowed in a variable name.
8. Special characters are not allowed, except underscore ( _ ).
9. Writing the variable names in lowercase is a good programming practice.
2.1.5 Identifiers
Identifiers (user-defined names) are names that are given to variables, functions
and arrays.
Rules for identifiers
1. The first character must be a letter/alphabet or underscore (_).
2. It can contain characters a-z, A-Z, 0-9 or underscore (_).
3. Keywords cannot be used as identifiers.
4. No space and special symbols are allowed between the identifier.
Identifier Why it’s in valid
2.1.6 Constants
Constant is a value that does not change during the execution of the program.
C supports three types of constants. These are:
1. Numeric constants
o Integer constants
o Real (or) Floating point constants
2. Character constants
3. String constants
The kind of data that variables may hold in a programming language is called the
data type.
The data types can be broadly classified into the following types.
o Built in or primary data types
o User defined data types
o Derived data types
o Empty data type
These data types are further classified as shown in above fig.
„C‟ supports the following 4 classes of data types.
Additional information
Data Type Bytes Range Format
Specifiers
char 1 2 7 to 2 7 1 %c
unsigned char 1 0 to 2 8 1 %c
Examples:
int code;
char sex;
float price;
char name[10];
Here the variables, code is type of integer, sex is type of character, price is type
of float and name[10] is defined an array of character.
*Note:
1. When the variables are declared in single line, then the variables must be
separated by commas.
2. A declaration statement must end with a semicolon (;).
b) Initializing variables (or Assigning values to variables)
Variables initializaiton means assigning a value to the variable.
Initializaiton of variable can be done using the assignment operator (=).
Variables should be declared in the C program before to use.
The syntax for declaring a initializing variables is as follows,
Additional information
The logical AND operator is used to perform ANDing operation on two logical
operands. It performs the multiplication operation. The result of a logical ANDing
is true, when both the operands are true. Otherwise the answer is false. The
following table show logical operators.
Operand 1 Operand 2 Operand 1&& Operand 2
False False False
False True False
True False False
True True True
The logical OR operator is used to perform logical addition operation. The result
of a logical addition is false only when both the operands are false; otherwise the
answer is always true. The following truth table illustrates this.
Operand 1 Operand 2 Operand 1¦¦Operand 2
False False False
False True True
True False True
True True True
Declarations: int i 3 , j 7
double f 5.5 , g 4.5
char ch ' T'
Expression Interpretation Value
i 5 & &ch ' T' True 1
f g 10.0|| i 2 True 1
f 6 || i * j 15 False 0
Examples:
a 10 20* 3 ;
a 70 ;
b) Declaration Assignment Statement:
The initialization of variables is possible at the time of declaration itself.
In this case, the declaration must consist of a data type followed by a variable name,
an equal sign and a number appropriate to the data type and finally a “semicolon
(;)”.
Examples:
int x 1 ;
float sum 0.0 ;
char ch ' Y' ;
c) Multiple Assignment Statement:
According to this statement, more than one variable can be assigned a single value
or an expression using the following syntax:
Example: a b c 10;
d) Increment/Decrement statement
With assignment we can use either increment/decrement operator.
Example 1: a b
Let us take the value of b 5
Then the above statement increments the value of b by one, then value is assigned
to a.
Hence, a 6 , b 6
Example 2: a b
Let us take the value of b 5
First a takes the value of b; then value of b is incremented it by one.
Hence, a 5 , b 6
2.5.5. Explain the increment and decrement operators
In certain cases the value of a variable to be incremented or decremented by one.
C uses two very useful operators not generally found in other languages. These are
increment (++) and decrement (--) operators.
The „++‟ adds one to the variable and „--‟ substracts one from the variable.
Operator Meaning
++a Prefix increment
--a Prefix decrement
a++ Postfix increment
a-- Postfix decrement
*Note:
1. ++a is equivalent to a a 1; or a 1;
2. --a is equivalent to a a 1; or a 1;
Explanation:
i) Increment Operator
This operator is used to increment (or increase) the value of an integer quantity by
one. This is represented by „++‟ (double plus) symbol. This symbol can be placed
either before or after an integer variable.
These are further subdivided into two categories:
1. Prefix increment
2. Postfix increment
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-18
Where,
variable An int or char data element
shift operator Left shift or right shift operator
nob Number of bits to be shifted
Examples: The left shift and right shift operations are illustrated pictorially below.
Consider the binary number 10000100. It is equivalent to 132 in decimal.
a) Bitwise Right shifting b) Bitwise Right shifting
Before shifting one bit right Before shifting one bit right
1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0
After one bit shifted to right After one bit shifted to right
0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0
4ac 4 * a * c /2 * a
2a
2x 2 2 * x * x / b c
c
b
Where data_type is one of the standard C data types. The expression may be a
constant, variale or an expression.
Example:
double d = 6.5;
double b = 6.5;
int result = (int)(a) + (int)(b);
Result would be equal to 12 instead of 13.
Some other examples of casts and their actions are shown in Table.
Example Action
Additional information
Formatted Input/Output refers to input and output, that has been arranged in a
particular format.
Additional information
2. Output Function:
C provides the printf( ) function to display the data on the standard output
device(monitor). The printf( ) function is included in the header file
<stdio.h>.
The general form of printf( ) function is
……………….………..Simple C Programs…………….…………
Program 1: C program to find the area of triangle having base ‘b’ and
height ‘h’.
1./*to find the area of a triangle*/
2.#include<stdio.h>
3.void main()
4.{
5. float area,base,height;
6. printf(“Enter base,height\n”);
7. scanf(“%f %f”,&base,&height);
8. area=0.5*base*height;
9. printf(“Area= %f “,area);
10. }
Output:
Enter base,height
15.0,10.0
Area =75.000000
Explanation:
The program lines have been indicated for explanation purposes only and they do
not from part of the program.
Line 1: Comment line to explain the purpose of the program.
Line 2: Header file inclusion.
Line 3: The main function starts with the keyword void which indicates the main
fuction does not return a value.
Line 4: {
Line 5: Declaration of floating variables area, base, height.
Line 6: printf is used to print the message “Enter base, height”, so as to interact
with the user.
Line 7: scanf is used to accept values for base, height from user.
Line 8: To compute area.
Line 9: To display the result
Line 10: }
*Note: The braces (Line number 4 and 10) are used to indicate the beginning and end
of the faction main ().
OBJECTIVES
3.1 Discuss decision making in programming.
3.2 Explain decision making statements- if , if-else, nested if, else-if l
adder - with syntax and programs
3.3 Discuss break and continue statements.
3.4 Explain decision making statement- switch statement - with syntax
and programs
3.5 Define looping and list loop statements
3.6 Explain the loop statements – while, do- while, for statement- with
syntax and programs
3.7 Define nesting of loops and implement it
3.8 Compare different loop statements
3.9 Know about Infinite loop and steps to avoid it
Decision making, Looping statements and Pre-Processor directives 3-2
3.2.1. if statement
When if statement is executed, the computer first evaluates the value of the test
condition.
If the value is true, statement block and next statement are executed sequentially.
If the value is false, statement block is skipped and execution starts from next
statement.
The fig. was the operation of if statement using flowchart.
*Note: The „statement-block‟ may be a single statement or a group of statements.
When this statement is executed, the computer evaluates the value of the test
condition.
If the value is true, statement block1 is executed and the control is transferred
to next statement.
If the value is false, statement block2 is executed and the control is transferred
to next statement.
Explanation:
This program tests the mark of the student. If it is greater than or equal to 40 it
prints pass. If it is less than 40 it prints fail.
When we take multipath decisions at that moment we use the else if ladder
statement.
It is like a chain of if statements, in which the statement associated with each else is
known as a if.
Syntax:
if (condition-l)
statement-l;
else if (condition-2)
statement-2;
else if (condition-31
statement-3;
else if (condition-n)
statement-n;
else
default statement;
Maanya’s M.G.B Publications Programming in C
Decision making, Looping statements and Pre-Processor directives 3-9
Working Process
o In the else.. if ladder the conditions are evaluated from top to downwards.
o When the controller of the program found a true condition, the statement
associated with the condition will be executed and the controller skips other
conditions and transfer to the statement-x.
o When all conditions becomes false at that moment the final else (i.e., default
else) statement will be executed i.e., default statement.
o The working process of else.. .if ladder is represented on the Fig. shown above
When the statement continues is encountered inside any „C‟ loop control
automatically passes to the beginning of the loop.
The continue statement tells the compiler. “SKIP THE FOLLOWING
STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”. The format of
the continue statement is simply Continue;
The continue statement can be used in for, while, do ..while loops. It cannot be used
in switch statement
The use of the continue statement in loops is illustrated in fig.
In while and do loops, continue causes the control to go directly to the test-
condition and then to continue the iteration process. In the case of for loop, the
increment section of the loop is executed before the test-condition is evaluated.
3.3.3. Differentiate break and continue statements
S. No Break Continue
1. Control exit from the loop Control will be within the loop only.
2. Can be used in while, do-while, for Used in for, while, do-while
and switch statement
3. Use of break statement causes to Use of continue statement is to skip
escape from a loop, or skip the the execution of some statements in
remainder of switch statement the loop, and performs next iteration
of the loop
Maanya’s M.G.B Publications Programming in C
Decision making, Looping statements and Pre-Processor directives 3-11
The below fig. in next page shows the operation of switch statement using
flowchart.
int main()
{
char ch;
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
return 0;
}
Output 1:
Input a character: A
A is a vowel.
Output 2:
Input a character: x
x is not a vowel.
Program 6: C program to perform arithmetic operations using switch
statement
Option Operation
1 Addition
2 Subtraction
3 Multiplication
4 Division
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b ,c, option;
clrscr( );
printf(“\n Enter the values of a and b:”);
scanf(“%d %d”, &a, &b);
printf(“\n Enter your option:”);
scanf(“%d”, &option);
Where,
while is a keyword
test condition logical expression that results in either true or false
body of the loop may be a simple or compound statement
The while loop is an entry controlled loop statement, means the condition is
evaluated first and it is true, then the body of the loop is executed.
After executing the body of the loop, the condition is once again evaluated and if it
is true, the body is executed once again, the process of repeated execution of the
body of the loop until the condition finally becomes false and the control is
transferred out of the loop.
The fig. shows the operation of while loop using flowchart.
When this statement is executed the body of the loop is executed first.
Then the test condition is evaluated.
Fig.
Program 9: C Program for addition of numbers using do…..while loop
#include<stdio.h>
main()
{
int i=1, sum=0;
do
{
sum = sum + i;
i++;
}
while(i<=10);
printf(“Sum of the numbers upto 10 is…%d”, sum);
}
Here are two for statements. The first one is called the outer loop and the second
as the inner loop.
Program 11: C Program to demonstrate nesting of for loops
#include<stdio.h>
main()
{
int i, j;
for(i=1; i<=3; i++)
{
printf(“\n”);
for(j=1; j<=3; j++)
printf(“%d\t”, j);
}
}
Output:
1 2 3
1 2 3
1 2 3
Explanation:
Here for each value of „i' the inner loop is executed completely, with in the inner
loop „j‟ taking from 1 to 3.
The inner loop terminates when the value of „j‟ is greater than 3. Where „\n‟ causes
the control to the next line for each entry of the „i' loop and prints the output.
OBJECTIVES
4.1 Define Array. Describe declaration and initialization of One
Dimensional Array with syntax and program
4.2 Explain about ‘accessing array out of bounds’ problem
4.3 Explain reading elements of an array, accessing the elements and
display them with program
4.4 Explain sorting elements in an array in ascending order
4.5 Explain finding the average of elements in an array and finding the
largest element in an array
4.6 Explain declaration and initialization of two Dimensional Arrays
4.7 Illustrate the concept of two dimensional arrays with sample
programs on matrix addition, subtraction, matrix multiplication and
transpose of a matrix
4.8 Define String and know about declaration and initialization of a String
variable.
4.9 Know about reading & writing of strings with programs
4.10 Explain about various String handling functions with sample
programs.
Arrays and Strings 4-2
4.0. Introduction
So far, you have seen different types of variables which hold only one value.
There are many applications which require to process a group of data items that are
of same type such as int, float, char or double.
For example, we can define an array of a list of marks obtained in an examination
by a group of students.
In such a situation, it is necessary to have a unique variable which holds a group of
elements.
Such a construct of programming language which stores and organises a set of data
items is called a data structure.
There are different types of data structure such as array, stack, queue, linked lists,
structures, tree and file etc.
In this chapter the data structure array is discussed with the following objective.
1. Definition
2. Classification of arrays
3. Declaration of an array
4. One-dimensional array
5. Two-dimensional array
Where,
1, 2, 3, 4 and 5 are subscripts
even [1] : indicates the first element in an array even.
even [2] : indicates the second element in an array.
even [3] : indicates the third element in an array.
even [4] : indicates the fourth element in an array.
even [5] : indicates the fifth element in an array.
In general, even [i] indicates the i th element of an even array.
4.1.2. Classification of Arrays
Generally, arrays are classified into one-dimensional array and multi-dimensional
arrays.
Further, the multi-dimensional arrays are classified into two-dimensional, three-
dimensional and so on n-dimensional arrays.
The dimensionality is determined by the number of subscripts in an array.
If there is one subscript, then it is called one-dimensional.
If there are two subscripts then it is two dimensional and so on.
4.1.3. Declaration of One dimensional arrays
Arrays must be declared before it is used like other variables.
The general form is,
Where
data_type int, float, char etc
drray_name valid C variable name
size number of contiguous location in the memory to be
reserved
Fig. shows three different array declarations: one for integers, one for floating-point
numbers and one for characters.
Where
data type type of data found in the array such as int, float, char etc
array-name valid C variable name
size number of contiguous locations in the memory to be
reserved
list of values initial values to be given to the array. This should be
separated by commas.
Example 1: int age[3]={10, 20, 30}:
This declares age as an integer array having three locations and assign initial
values as given below.
age[0] age[1] age[2]
10 20 30
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
m g b m a a n y a \0
Even though the character string has 9 characters, we have defined the array with
10 elements. This is to store \0 (null character) as the string terminator.
2. Run Time Initialization:
An array can be explicitly initiated at run time. This approach is usually applied for
initializing large arrays.
Example 5: while{i<=10}
{
if{i<5}
sum[i]=0;
else
sum[i]=sum[i]+i;
}
Explanation:
The while loop checks the condition i<=10.
If condition is true then if statement checks condition i<5, if condition is true
then sum[i] the assigned to zero else sum[i] assigned as sum[i]+i.
This would cause the array value to store the values as shown below.
Output:
Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
1 2
3 4
Enter the elements of second matrix
5 6
2 1
Sum of entered matrices:-
6 8
5 5
Program 12: C Program to multiply two matrices.
#include<stdio.h>
#include<conio.h>
void main()
{
int mat1[3][3], mat2[3][3], mat3[3][3], sum=0, i, j, k;
printf("Enter first matrix element (3*3) : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
1 2
2 4 1 2 1 2 2 4 2 8 10
2 4
3 5
1 2
2 4 1 2 2 1 4 2 2 8 10
2 4
3 5
The very first character occupies 0 th subscript, second character, the 1tst subscript
and so on the last character the ( n 1)th subscript; in an n-character array.
Where,
ch_var is a character type variable to which an accepted character is assigned.
Example:
main()
{
char 1etter;
letter = gethcer();
:
}
Where,
string a sequence of characters.
Example
#include<stdio.h>
Main()
{
char messg[20];
puts(messg);
}
Example
strcat(“PROGRAM”,“MING”);
It will append string “MING” to the end of the string “PROGRAM”. The
resultant string is “PROGRAMMING”.
Program char st1[30]=” C programming”;
char st2[20]=”tutorial”;
char *st3;
st3=strcat(st1, st2);
printf(“%s\n”, st3);
Output: C programming tutorial
2. strchr() function
Purpose This function searches for a specified character in a given string. It returns
NULL if the desired character is not found in the string.
Syntax
4. strncmp() function
Purpose This compares the first n characters of two input strings.
Syntax
Example strncmp(“devi”,”dev”,3);
This compares the first 3 characters in strings “devi” and “dev” respectively.
It returns one of the 3 values {-1, 0, 1} .
5. strcpy() functions
Purpose This function is used to copy the contents of one string to another and it
almost works like string assignment operator
Syntax
Where,
string = One – dimensional array of characters.
Example 1: strlen(“programming”);
The length of the string programming is 11 as there are 11 characters in
it.
2: strlen(“India is great”);
Here, the string length is 14. It includes two white spaces apart from all
other alphabets.
Program 16: C program to copy the content of one string to another by
using strcpy()
#include<stdio.h>
#include<string.h>
void main()
{
char ori[20], dup[20];
printf(“Enter Your Name:”);
gets(ori);
strcpy(dup.ori);
printf(“Original String: %s”, ori);
printf(“\n Duplicate String: %s”, dup);
}
After iteration 4 4 a
After iteration 5 5 i
After iteration 7 6 Loop Terminated
Program 20: C program to compare two strings using strcmp()
#include<stdio.h>
#include<string.h>
int main()
{
char a[100], b[100];
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b);
if{ strcmp(a,b) == 0 )
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");
return 0;
}
Output:
Enter first string: MGB Maanya.com
Enter second string: MGB Maanya.com
Both strings are equal
Program 21: C program is used to copy the string by using the library
function strcpy()
#include<stdio.h>
#include<string.h>
int main()
{
char str1[100];
char str2[100];
printf("\nEnter the String 1 : ");
gets(str1);
strcpy(str2, str1);
printf("\nCopied String : %s", str2);
return (0);
}
OBJECTIVES
5.1 Define function, state the need for user defined functions, advantages
of functions
5.2 Know the elements of function and return values.
5.3 Define and discuss function prototype, function call, and function
definition with syntax and program.
5.4 Discuss the scope, visibility and lifetime of variables in functions
5.5 Differentiate Local and Global variables
5.6 Illustrate functions with no arguments and no return values with
programs
5.7 Illustrate functions with no arguments and with return values with
programs
5.8 Illustrate functions with arguments and with no return values with
programs
5.9 Illustrate functions with arguments and with return values with
programs
5.10 Illustrate passing arrays to functions with programs
5.11 Define recursion and Illustrate recursion with programs
User defined funtions 5-2
Example:
int sum (int a, int b, int c)
{
printf(“sum = %d” , a+b+c);
return ;
}
Maanya’s M.G.B Publications Programming in C
User defined funtions 5-4
5.2.2. Use of return statement
A function may or may not send back any value to the calling function. If it does, it
is done through the return statement.
The return statement serves the following two purposes:
1. Transferring control from the function back to the calling program.
2. It returns the values to the calling function.
The return statement can take one of the following forms.
or
The first form of return statement does not returns any value to the calling
function.
The second form of return with an expression returns the value of the expression.
Example 1:
mul(x,y)
int x,y;
{
int p;
= x*y;
return(p);
}
Returns the value of p which is the product of the values of x and y. The last two
statements can be combined into one statement as follows:
return (x*y);
Example 2:
float add(float x, float y)
{
return(x+y);
}
Returns the value of the addition of x and y.
Example:
int sum(int a, int b); // prototype
The prototype indicates the name of the function, what type of the value returned
the function and what the parameter lists are.
When we place the declaration above all the function(in the global declaration
section),the prototype is referred to as a global prototype. Such declarations are
available for all the functions in the program.
When we place it in a function definition (in the local declaration section), the
prototype is called a local prototype. Such declarations are primarily used by the
functions containing them.
Program 1: C function that performs the sum of two predefined numbers.
#include<stdio.h>
float total()
{
float x,y;
x=20.0;
y=10.0;
return(x+y);
}
void main()
{
float sum;
float total();
sum=total();
printf(“sum=%f\n”,sum);
}
Output:
sum = 30.000000
Program 2: C program to find the product of two numbers.
#include<stdio.h>
int product(int a,int b)
{
int res;
res=a*b;
Additional information
Variables in C differ in behavior from other languages.
To fully define a variable, one needs to mention not only its ‘type’ but also its
storage class.
A variable’s storage class tells us:
1. Where the variable would be stored.
2. What the initial value of the variable will be.
3. What the scope of the variable is.
4. What life of the variable is i.e. how long would the variable exist.
Basically the area or block of the C program from where the variable can be
accessed is known as the scope of the variable.
1. These are also known as automatic These are also known as Global
variables. variables.
4. Same variables can be used in different External Variable has constant value
functions. The values differ from throughout the program.
function to function.
5. Local variables exist while the block of An external variable exists as long as
code in which they are declared is program is executing.
executing. That is a Local variable is
created upon entry into its block and
destroyed upon exit.
Additional information
* ARRAYS TO FUNCTIONS *
To process array in a large program, we have to be able to pass them to functions.
We can do this in two ways: Pass individual elements or pass the entire array.
In some situations we may want to pass individual elements of the array, and in
other situations we may want to pass the entire array to a function.
Additional information
It is a variable that communicate between calling function to called function. There
are two types:
1. Actual argument
2. Formal argument
Actual argument: The arguments which are defined in calling function are known
as actual argument.
Formal argument: The arguments which are defined in called function are known
as formal argument.
The actual and formal argument should match in number, type, and order.
The values of actual arguments are assigned to the formal arguments on a one to
one basis, starting with the first argument as shown in fig .
Output:
The average is 20.80
Comment:
The address of array, arr is passed as an actual parameter. The function accesses the
same array with different name x.
5!=(5)(4!)
But 4! Is equal to 4(3!), so 5! Is equal to
(5)(4)(3!)
But 3! Is equal to 3(2!), so
5!=(5)(4)(3)(2!)
But 2!= 2(1!)=(2)(1), so
5!=(5)(4)(3)(2)(1)=120
The above entire process to evaluate 5! Is shown in fig. .
Figure shows how the succession of recursive calls proceeds until 1! Is evaluated to
be 1, which terminates the recursion.
Figure shows the values returned from each recursive call to its caller until the final
value is calculated and returned.
#include <stdio.h>
long int fact(int n);
void main( )
{ int n;
printf(“\nEnter n value:”);
scanf(“%d”,&n);
printf(“\n%d Factorial=%1d”,n,fact(n));
}
long int fact(int n)
{ if (n==1)
return 1;
else
return (n*fact(n-1));
}
Input-Output:
Enter N value:5
Factorial=120
For better visualization of recursion in this example:
Fact(5)
5 fact(4)
5 4 fact(3)
5 4 3 fact(2)
5 4 3 2 fact(1)
5 4 3 2 1
5 4 3 2`
5 24
120
OBJECTIVES
Structures and Unions
6.1 Define structure
6.2 Illustrate creating a structure tag and declaring structure variables,
6.3 Explain accessing structure members and structure assignment
6.4 Know size of a structure.
6.5 Discuss nested structure concept.
6.6 Illustrate array of structures, structures containing arrays, arrays of
structures containing arrays.
6.7 Illustrate structure as function arguments and returning of structure
variables as function values.
6.8 Define Union and illustrate usage of a union.
6.9 Know the differences between Structure and Union
Files management
6.10 Define file
6.11 Know how to declare file pointer to a file
6.12 Illustrate the concept of file opening in various modes
6.13 Illustrate the concept of closing of a file
6.14 Illustrate the concept of Input / Output operations on a file
6.15 Illustrate the concept of random access to files
Structures, unions and file management 6-2
6.0. Introduction
We known a variable can stores a single value of a data type. Array can store more
than one value of same type.
But our objective is to store more than one value to a variable of different type. So,
C provides a special feature to handle this things i.e., structure.
An array is employed to store and process a group of homogeneous elements. For
example, marks of students, names of employees, etc. but, most of the real-world
applications need a group of heterogeneous elements.
For example, in processing student information, it is necessary to process the
information like his roll number., name, branch and percentage is of type float. In
processing such information, the knowledge of the structure is required.
Structure is a collection of one or more variables of different data types, grouped
together a single name. In other words we can say structure is a heterogeneous data
type.
Let us use an example to illustrate the process of structure definition and the
creation of structure variables. Consider a book database consisting of book name,
author, number of pages, and price. We can define a structure to hold this
information as follows:
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of four fields, namely
title, author, pages, and price. These fields are called structure elements
or members. Each member may belong to a different type of data, book_bank is
the name of the structure and is called the structure tag. The tag name may be used
subsequently to declare variables that have the tag’s structure.
*Note: The structure is musty ended with a semicolon (;).
6.2.3. Declaration of structure variables
After declaration of the structure format, we can declare variable of the type. The
structure variable may be defined in the following ways.
a) In the structure Declaration
The structure variables can be specified after the closing brace and before
semicolon.
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-4
struct book_bank
{
char title[20];
char author[15];
int pages ;
float prices;
}b1;
Here, in the above example ‘b1’ is the variable of structure book_bank. We can
also declare more than one variable, list of variable names separated by commas.
Example:
struct book_bank
{
char title[20];
char author[15];
int pages;
float prices;
}b1, b2, b3;
Here b1, b2 and b3 are three variable of structure book_bank.
b) Using the structure Tag
The variable of a structure may also be declared separately by using the structure
Tag.
Example:
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
struct book_bank b1,b2,b3;
Here b1, b2 and b3 are three structure variables declared by the help of structure
tag i.e., struct book_bank.
*Note: Remember that the members of a structure themselves are not variables, They
do not occupy any memory until they are associated with the structure variables.
Where,
Structurevariable : Name of the structure variable
member : Name of a member within the structure
The student’s roll_no of the structure “student” can be accessed by writing,
std1.roll.
Similarly the student’s name of the structure “student” can be accessed by
writing, std1.name.
6.2.2. Structure Assignment
The one structure information can be assigned to another structure of the same type
using single assignment statement. We do not require to assign the value of each
member separatly.
The syntax for structure assignment is,
where, var1 and var2 are the the structure variables of same structure.
The concept of structure assignment is clearly illustrated in the fig.
Fig.
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-6
Example: Consider the following statement.
library book1, book2;
book1=book2;
Here, the value contained in book2 will be assigned in book1.
Internal assignments related to the above statement will be performed accordingly.
The following program initializes the variable book1 with some values. This
variable is also assigned to another variable book2.
Program 2: C program to demonstrate initialization and assignment
of a structure.
#include<stdio.h>
#include<conio.h>
main()
{
struct library
{
char name[30];
int price;
int pages;
};
struct library book1={“Harrypotter”, 560, 1015};
struct library book2;
book2=book1;
printf(“\n Name”, book2.name);
printf(“\n Price”, book2. price);
printf(“\n Pages”, book2.pages);
getch();
}
Output:
Name: Harrypotter
Price: 200
Pages: 1015
(or)
The ‘sizeof’ operator returns the size in bytes of its operand or structure
variable. Its returned value is determined at compile time.
The usage of ‘sizeof’ operator on structures is illustrated in the program-2.
Program 1: Write a C program to find the memory occupied by the
structure variable.
#include<stdio.h>
#include<conio.h>
void main()
{
struct mphone
{
char name[15];
char model[10];
float price;
}p;
printf(“\nThe size of structure variable is %d”,sizeof(p));
getch();
}
Output:
The size of structure variable is 29
Fig.
6.3.2. Declaring Nested structures
The declaration of nested structures may take one of the two forms mentioned
below.
Method 1:
In this method, a structure may completely be defined within the other structure.
We show the declaration of the structure ‘REMINDER’ and a variable that uses in
the following example.
struct REMINDER
{
struct DATE
{
int month;
int day;
int year;
}date;
struct TIME
{
int hour;
int min;
int sec;
}time;
}reminder;
This method of declaring nested structures is not recommended because it is very
difficult to follow the structure if large number of sub-structures are involved.
This shortcoming of this method can be overcome in the next method.
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-9
Method 2:
In this method, all the sub-structures are declared separately and then grouped
together in the high-level structure.
The ‘REMINDER’ structure declared in this method is shown in the following C
code snippet.
//structure decalrations
struct DATE
{
int month;
int day;
int year;
}
struct TIME
{
int hour;
int min;
int sec;
}
struct REMINDER
{
struct DATE date;
struct TIME time;
}
//variable declaration
struct REMINDER reminder;
Concept 2:
Array is a collection of similar data types. In the same way we can also define array
of structure. In such type of array every element is of structure type. Array of
structure can be defined as follows:
struct book
{
char name [30];
int page;
float price;
}b[5];
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-11
In the above example the variable b[5] is an array of five elements. In other words
five variables are created of structure book type. i.e., book[O], book[l], book[2],
book[3], book[4]. Here, each variable has three members i.e., name, page, and price.
return std;
}
Student #1 Detail:
Firstname: Bruce
Lastname: Wayne
ID: dc-01
Score: 8
Student #2 Detail:
Firstname: Peter
Lastname: Parker
ID: mc-01
Score: 9
Student #3 Detail:
Firstname: Tony
Lastname: Stark
ID: mc-02
Score: 7
Example 2:
union item
{
int m;
float x;
char c ;
}code;
declares a variable code of type union item. The union contains three members,
each with a different data type.
To access a union member, we can use the same syntax that we use for structure
members. That is,
code.m
code.x
code.c
Are all valid member variables. During accessing, we should make sure that we are
accessing the member whose value is currently stored. For example, the statements
such as
code.m = 379;
code.x = 7859.36;
printf(“%d”,code.m);
would produce erroneous output(which is machine dependent).
All members can be accessed at a time. Only one member of a union and
4. thus one data type can be accessed
at any one time.
5. The memory size of the structure The memory size of the union
variable is the sum of the size of its variable is the largest size of its
members. members.
6. Occupies more memory when compare Occupies less memory when
to union. compared with structure.
7. It may be initialized with all its Only its first members may be
members. initialized.
8. Structure definition Union definition
struct stu union stu
{ {
char name [7]; char name [7];
int age; int age;
}x; }x;
9. Storage in case of Structures: Storage in case of Structures:
Additional information
The preprocessor can be thought as a smart editor. Like a smart editor, it inserts,
includes, excludes, and replaces text based on commands supplied by the
programmer. These commands are known as Pre-processor Commands or Pre-
processor directives.
The following points about the preprocessor commands are very important and
must be noted carefully.
o All the pre-processor commands start with a pound sign (#).
o Pre-processor directives are placed in the source program before the main line.
o They do not require a semicolon (;) at the end.
The preprocessor directives are broadly divided into two categories:
o Unconditional Preprocessor directives
o Conditional Preprocessor directives
b) Binary Modes
1. wb (write) : This mode opens a binary file in write mode.
Syntax:
fp=fopen("p.dat", "wb");
Here p.dat file is opend in binary mode for writing
2. rb (write) : This mode opens a binary file in read mode.
Syntax:
fp=fopen("p.dat","wb");
Here p.dat file is opened in binary mode for reading.
1. Character I/O
fgetc()
It is used to read a single character from a given file. And increment the file
pointer position.
Syntax:
fgetc (FILE * fp) ;
getc()
It is used to read a single character from the file.
Syntax:
getc (FILE *fp);
fputc()
It is used to write a single character in a file at current position and then
increment the file pointer position.
Syntax:
fputc( char c, FILE *fp);
2. String I/O
fputs()
It is used to write a line of text in a file. It doesn't write null character in a file.
Syntax:
fputs(constant char *str,FILE *fp);
fgets()
It is used to read character from a file and these characters are stored in the
string [pointed to by str. It read at most n-l and appends '\0' character in replace
or '\n'. It returns NULL when reached in EOF.
3. Integer I/O
putw()
It is used to write an integer data in a file.
Syntax:
int putw(int , FILE *fp);
getw()
It is used to read an integer data from file.
Syntax:
int getw (FILE * fp) ;
4. Formatted I/O
fprintf()
It is same as printf() but it writes formatted data into the file. In other words we
can say, this function is used for writing characters, strings, integer's floats etc., to
the file. It contains one more parameter that is the file pointer, which points the
opened file.
fscanf()
This function reads character, strings, integers, float etc., from the file pointed
by file pointer.
5. Structure read and writes
fwrite()
This function is used for writing a structure variable in a file.
Syntax:
fwtite(const void *ptr , sizeof(data),no-of-data, FILE *fp);
ptr is a pointer which points to the block of memory that contains the
information to be written to the file.
sizeof(data): Denotes the length of each item in bytes.
no-of-data: Denotes the number of items to be written to the file.
*fp: Denotes the file where the data are written.
fread()
It is used to read an entire block from a given file.
Syntax:
fread(void *ptr, sizeof(data) , no-of-data, FILE *fp);
sizeof(data): Denotes the length of data (byte )in read.
*fp: Denotes the file where the data is read.
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-22
PART – B
Note: Answer any two questions. Each question carries three marks
2x3=6M
5. a) Write any three differences between break and continue statements.
(OR)
b) Write any three differences between while and do-while statements.
6. a) Write a C program to find largest number in array.
(OR)
b) Explain any three String handling functions.
PART – C
Note: Answer two questions. Each question carries ten marks
2 x 5 = 10 M
7. a) Explain do-while statement with syntax and sample program
(OR)
b) Explain switch statement with syntax and sample program .
8. a) Write a C program to find the multiplication of two matrices.
(OR)
b) Write a C program to find the addition of two matrices.