C.3
C.3
Mandal
Generation of Programming Language
First Generation
In first generation language, all the instructions were given in the binary form and is referred to as
machine language or Low Level Language (LLL). It is very difficult for us to write or read instructions
written in binaries. Consider the following instruction written in binaries:
Second Generation
In second generation language, instructions are written with mnemonics to simplify the program.
The symbolic instruction language is known as Assembly Language. In order to execute these
instructions, all mnemonics are converted into binaries with the help of a translator known as
Assembler. The program written using mnemonics is called source program and the binary form is
called object program.
Source Program
Assembler
Object Program
Assembly Language programs are commonly used to write programs for electronics controls using
microprocessor, e.g. computerised copier machine, computerised telephone billing etc.
Third Generation
In third generation languages, instructions are written using English language with symbols and digits. Third
generation languages are also known as High Level Language (HLL). The commonly used high level languages
are FORTRAN, BASIC, COBOL etc.
In order to execute the instructions, the source program is translated into binary form by compiler or
interpreter.
Source Program
Compiler/
Interpreter
Object Program
Prepared by A. Mandal
Fourth Generation
Fourth generation languages refer to software packages which are mostly written in one of the languages
(FORTRAN, C etc.) for any specific application. It is very useful or users to perform a task without writing
programs. The user has to enter the command to call the program which is readily available in the package.
This language is also called command line language. Some commonly used 4 GL packages are dBase, FoxPro,
Oracle etc.
Computer Programming
A program has a set of instructions written in correct order to get the desired result. The method of writing
the instruction to solve the given problem is called programming.
Programming Techniques
There are two types of Programming techniques commonly used:
i) Procedural Programming
ii) Object Oriented programming (OOP)
Procedural Programming
In procedural programming, for a given problem, variables are identified and instructions are written using
the variables in correct sequence to get the required result. Sometimes the program required unconditional
transfer of control from one part of the program to another. The procedural programming method is
commonly used to solve scientific and engineering problems involving variables.
Abstract Algorithm
1. START
2. Read n numbers
3. Add these n numbers
4. Divide the addition result by n to get the average
5. Print the average
6. STOP
Detailed Algorithm
1. START
2. Read the value of n
3. Assign 0 to sum
4. Repeat n times
5. Read number
6. Add number to sum
7. End repeat
8. Divide sum by n to get the average
9. Print average
10. STOP
Pseudo Code
It is a formal representation than algorithm. In pseudo code, each of the steps will be written via operators
and statements equivalent to some programming language instruction. An algorithm can be written in the
form of pseudo code as follows:
1. START
2. Read n
3. sum← 0
4. for i← 1 to n do
5. Read numberi
6. sum←sum+numberi
7. End for
8. average←sum/n
9. Print average
10. STOP
Flow Chart
A flow chart is a symbolic or diagrammatic representation of an algorithm. The various symbols used in
flowchart are:
Prepared by A. Mandal
Symbol Meaning
START/STOP
Input/Output
Processing
Checking/Decision making
Example:
Draw a flowchart to find the sum and product of given two numbers.
START
Read a, b
sum←a+b
product←a×b
Print sum,
product
STOP
Prepared by A. Mandal
Introduction to C
History of C:
‘C’ seems a strange name for a programming language. But this strange sounding language is one of
the most popular computer languages today because it is a structured, high-level, machine
independent language. It allows software developers to develop programs without worrying about
the hardware platforms where they will be implemented.
The history and development of C is illustrated below:-
Features of C language:
General applications
Database systems
Spread sheets
Graphic packages
CAD applications
Word processors etc.
Advantages of C:
Data structures: There are several ways to store data in C, which allows easy access to data
in C.
Operator richness: C supports a wide range of operators to handle arithmetic and logical
calculations.
Disadvantage of C:
Difficult to debug: C gives a lot of freedom to the developer, but it appears a bit complex for
a new comer to find what is wrong with a program.
Loosely syntaxed: C allows a lot of freedom in coding. We can put the symbol (;) at the end
of a statement. We can also put blank lines, white spaces anywhere we want in the
program. There is no fixed place to start or end a line. This can give rise to codes that are
difficult to understand by reading.
Prepared by A. Mandal
Basic Structure of C Program:
Documentation Section
Link Section
Definition Section
Subprogram Section
Function 1
(User-defined functions)
Function 2
-------
--------
Function n
-
The documentation section consists of a set of comment lines giving the name of the program, the
author and other details, which the programmer would like to use later.
The link section provides instructions to the compiler to link functions from the system library.
There are some variables that are used in more than one function. Such variables are called global
variables and are declared in the global declaration section that is outside of all the functions. This
section also declares all user-defined functions.
Every C program must have one main() function section. This section contains two parts,
declaration and executable part. The declaration part declares all the variables used in the
executable part. There is at least one statement in the executable part. The program execution
begins at the opening brace and ends at the closing brace.
The subprogram section contains all the user-defined functions that are called in the main function.
Prepared by A. Mandal
Constants, Variables and Data Types
A programming language is designed to help process certain kinds of data consisting of
numbers, characters and strings and to provide useful output known as information. Like any other
language, C has its own vocabulary and grammar. Now we will discuss the concept of constants and
variables and their types as they relate to C programming language.
Character Set:
White Spaces:
Blank space, Horizontal tab, Carriage return, New line, Form feed.
Prepared by A. Mandal
C Tokens:
In a passage of text, individual words and punctuation marks are called tokens. Similarly, in a C
program the smallest individual units are known as C tokens. C has six types of tokens as shown
below.
C Tokens
main []
amoun {}
t
Keywords:
Keywords are some special words which have fixed meaning and cannot be changed. Keywords
serve as basic building blocks for program statements. ANSI C supports 32 keywords.
Identifiers:
Identifiers refer to the names of variables, functions and arrays. These are user defined names and
consist of a sequence of letters and digits with a letter as first character.
Constants:
Constants in C refer to fixed values that do not change during the execution of a program. C
supports several types of constants.
Prepared by A. Mandal
Constants
Constant Meaning
\a Audible alert(bell)
\b Back space
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quote
\” Double quote
\? Question mark
\\ Backslash
\0 null
Variables:
A variable is a data name that may be used to store a data value. Unlike constants that remain
unchanged during the execution of a program, a variable may take different values at different
times during execution.
1. They must begin with a letter. Some system permits underscore as the first character.
2. ANSI standard recognize a length of 31 characters. However length should not be normally
more than eight characters. Since only first eight characters are treated as significant by
many compilers.
3. Uppercase and lower case are significant. That is the variable Total is not same as total.
4. White spaces are not allowed.
5. Except underscore (_) all other special characters are not allowed.
Prepared by A. Mandal
Data Types:
C is reach in its data type. Data type indicates what kind of data should be stored in a variable.
Types of data may be integer, floating point, character etc. There are 3 types of data type in C.
1) Primary of fundamental data type (Ex: int, char, float etc.)
2) Derived data type (Ex: array, pointer)
3) User defined data type (Ex: structure, union)
Operators
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulation. C operators are:
1.Arithmetic Operators
These operators are used for arithmetical calculation. Arithmetic operators are:
Operators Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division
2. Relational Operators
Comparisons can be done with the help of these operators. Relational operators are:
Operators Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
3. Logical Operators
These operators are used when we want to test more than one condition and make decisions.
Logical operators are:
Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT
When all the conditions are true then AND operator returns the value true otherwise it returns
false.
If any one the condition is true then OR operator returns the value true otherwise it returns false.
If the condition is true then NOT operator returns false otherwise it returns true.
4. Assignment Operators
This operator is used to assign the result of an expression to a variable. ‘=’ is the assignment
operator.
Shorthand Assignment Operators
Statement with simple assignment operator Shorthand notation
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a%b a%=b
Prepared by A. Mandal
6. Conditional Operator
A ternary operator pair “?:” is called conditional operator. It uses to construct conditional
expression of the form:
Exp1? Exp2 : Exp3
Exp1 is evaluated first. If it is true then the Exp2 is evaluated and it becomes the value of the
expression. Otherwise Exp3 is evaluated and it becomes the value of the expression.
Ex:
int a=10, b=15;
x=(a>b)? a : b;
The value of x will be the value of b.
7. Bitwise Operators
These operators are used for testing bits or shifting them right or left. Bitwise operator may not be
applied to float or double. These operators are:
Operators Meaning
~ Bitwise 1’s complement
| Bitwise OR
& Bitwise AND
^ Bitwise Exclusive OR
<< Bitwise left shift
>> Bitwise right shift
8. Special Operators
C supports some special operators such as comma operator, sizeof operator, pointer operators (&
and *) and member selection operators (. and ->).
Ex:
int a=10,b=20;
float c=2.5,d;
d=a+b+c;
The value of d is converted into float because in the expression a+b+c, a and b are integer but c is
float. So the result is converted to float.
long double
Conversion
double
Hierarchy
float
long int
unsigned int
int
Short char
Syntax:
(type)variable/Expression;
So the above example can be written as
int a=5,b=2;
float c;
c=(float)a/b;
Prepared by A. Mandal
1. Simple if statement
2. if-else statement
3. Nested if statement
4. else-if statement
5. switch statement
6. Conditional operator statement
7. goto statemets
Simple if statement
An if statement consists of a boolean expression followed by one or more statements. If the
condition is true the statement will be executed.
The general form of simple if statement is:
if(Test condition)
{
Statements;
}
The statements may be a single statement or a group of statements. If the condition is true then
the statements will be run; otherwise it will be skipped.
if-else statement
if(Test condition)
{
Statements;
}
else
{
Statements;
}
The statements may be a single statement or a group of statements. If the condition is true then
the if block statements will be run; otherwise else block statements will be run.
Prepared by A. Mandal
Nested if-else statement
if(Test condition)
{
if(Test condition)
{
Statements;
}
else
{
Statements;
}
}
else
{
if(Test condition)
{
Statements;
}
else
{
Statements;
}
}
else-if statement
if(Test condition)
{
Statements;
}
else if(Test condition)
{
Statements;
}
else if(Test condition)
{
Statements;
}
.
.
.
.
.
else
{
Statements;
}
Prepared by A. Mandal
Character functions :
SL FUNCTIONS DESCRIPTION
NO.
1 isalnum(c) If c is an alphanumeric character then it returns true otherwise
false
2 isalpha(c) Returns true if c is an alphabate
3 isdigit(c) Returns true if c is digit
4 islower(c) Returns true if c is lower case
5 isupper(c) Returns true if c is upper case
6 isprint(c) Returns true if c is a printable character
7 ispunct(c) Returns true if c is a puntution mark
8 isspace(c) Returns true if c is a white space character
Note :
The expression is an integer or character expression. Value1,value2 are constant or constant
expression are known as case label.
Syntax:
goto label; label:
--------------- Statement;
--------------- ------------------------
--------------- ------------------------
--------------- ------------------------
Label: goto label;
Statement;
LOOPING:
In looping, sequences of statements are executed until some conditions for termination of
the loop are satisfied. A program loop therefore consists of two segments, one known as the body
of the loop and other known as control statement. The control statement tests certain condition
and then directs the repeated execution of the statements contain in the body of the loop.
Example:
while(condition) //control statement
{
Statements; //body of the loop
}
In the case of an exit controlled loop, the test is performed at the end of the body of the
loop and therefore the body is executed unconditionally for the first time.
Entry and exit controlled loop are known as pre-test and post-test loop respectively.
Prepared by A. Mandal
Entry Entry
Body of the
Test False
Loop
Condition
?
True
True Test False
Body of the Condition
?
Loop
Category of loops:
There are three types of loop available in C. These are:
1. while loop
2. do-while loop
3. for loop
While Loop
It is an entry controlled loop. The condition is evaluated and if the condition is true then body of the
loop is executed. After execution of the body the condition is once again evaluated and if it is true
then body of the loop executed once again. This process continues until the condition become
false.
Syntax:
while(condition)
{
Statements;
}
Prepared by A. Mandal
do-While Loop
It is an exit controlled loop. At first body of the loop is executed then condition is tested. If the
condition is true then body of the loop is executed again. This process continues until the condition
become false.
Syntax:
do
{
Statements;
} while(condition);
for Loop
It is an entry controlled loop. Initialization of control variable done at first. Then the condition is
evaluated. If the condition is true then body of the loop is executed. Then control variable is
incremented or decremented and condition is evaluated again. If the condition is true then body of
the loop is executed once again. This process continues until the condition become false.
Syntax:
for(initialization; condition; increment/decrement)
{
Statements;
}
1) The initialization section contains more than one initialization statements separated by “,”.
2) Like initialization section the increment/decrement section contain more than one part
separated by comma.
Ex.-
for(i=0,j=0;i<=10;i++,j--)
{
…………….
…………….
…………….
}
3) The test condition may have any compound relation and the testing need not be limited
only to the loop control variable.
Ex.-
for(i=1;i<20&&sum<100;i++)
{
……………..
……………..
}
4) It is also permissible to use expression in the assignment statements of initialization and
increment section.
Ex.-
for(x=(m+n)/2;x>0x=x/2)
{
…………..
…………..
…………..
}
5) Another unique aspect of for loop is that one or more sections can omitted, if necessary.
Prepared by A. Mandal
Ex.-
n=123;
for(;n>0;)
{
…………….
…………….
…………….
}
6) We can setup time delay loops using the null statement as follows:
for(i=0;i<=1000;i++)
;
Jumping from loops
‘break’ statement:-
When a break statement is encountered inside a loop,the loop is immediately exited
and the program continues with the statement immediately following the loop. When the loops are
nested,the break would only exit from the loop containing it.
Ex.-
while(conditon)
{
…………….
…………….
…………….
break;
…………….
…………….
}
continue statement:-
C support another jumping statement called continue. This statement causes the loop
to be continued with next iteration after skipping any statements in between. The continue
statement tells the compiler “skip the following statements and continue with the next iteration”.
while(condition)
{
………………
……………..
continue;
…………….
…………….
}
Prepared by A. Mandal
Array
An array as a collection of variables of the same type which are stored in contiguous memory
locations.
Ex: int a[10];
Type of Array
1. Single dimensional array
2. Two dimensional array
3. Multi dimensional array
Declaration
Data_type array_name[size];
Ex:
int a[5];
Initialization
Data_type array_name[size]={list of values};
Ex:
int a[3]={7,10,15};
Here
a[0]=7
a[1]=10 and
a[2]=15
Another method
int a[3];
a[0]=7;
a[1]=10;
a[2]=15;
If only one element is initialized then remaining elements of the array will be set to zero.
Ex:
int a[3]={3};
Here
a[0]=3
a[1]=0 and
a[2]=0
Prepared by A. Mandal
Two dimensional array
When an array has two dimension, row and column; it is called two dimensional array.
Declaration
Data_type array_name[row_size][col_size];
Ex:
int a[2][3];
Initialization
Int a[2][3]={ {4,7,9},{3,9,5} };
Here
a[0][0]=4
a[0][1]=7
a[0][2]=9
a[1][0]=3
a[1][1]=9
a[1][2]=5
Prepared by A. Mandal
Strings
A string is a sequence of characters that is treated as a single data item. Any group of characters
defined between double quotation marks is a string constant.
Example – “Man obviously made to think.”
Declaration of String
char string_name[size];
Ex:
char str[20];
Initialization of String
char string_name[size]=”value”
Ex:
char str[5]=”GOOD”
or
char string_name[]=”value”
Ex:
char str[]=”GOOD”
G O O D \0
strcat(string1,string2);
string1 & string2 are two strings. When the function is executed, string2 is appended to string1 and
string2 remain unchanged.
Example:
Assume that
string1=”Good” and string2=”Morning”
strcat(string1,string2) will result
string1=”GoodMorning” and string2=”Morning”
Prepared by A. Mandal
strcpy(): It is used to assign the content of a string variable into another string variable. It takes the
following form:
strcpy(string1,string2);
The above function assigns the content of string2 to string1. string2 remain unchanged.
Example:
Assume that
string1=”Good” and string2=”Morning”
strcpy(string1,string2) will result
string1=”Morning” and string2=”Morning”
strupr(): It converts entire string content into upper case. It takes the following form:
strupr(string1);
Example:
Assume that
string1=”Good”
strupr(string1) will result
string1=”GOOD”
strlwr(): It converts entire string content into lower case. It takes the following form:
strlwr(string1);
Example:
Assume that
string1=”GooD”
strlwr(string1) will result
string1=”good”
strrev(string1);
Example:
Assume that
string1=”Good”
strrev(string1) will result
string1=”dooG”
strlen(): It returns the number of characters present in a string. It takes the following form:
n=strlen(string1);
Here string1 is a string variable and n is an integer variable.
Example:
Assume that
string1=”Good”
n=strlen(string1);
The value of n will be 4.
strcmp(): It compares two strings. If the strings are equal it returns 0 or if first string is largest it
returns +ve value or if second string is largest it returns –ve value. Actually it returns the ASCII value
differences of first non matching character from first string to second string. It takes the following
form:
n=strcmp(string1,string2);
Prepared by A. Mandal
Example:
Assume that
string1=”Amit” and string2=”Amal”
n=strcmp(string1,string2)
The value of n will be 8.
Because the first non matching characters are ‘i’ and ‘a’. ASCII value of ‘i’ is 105 and ‘a’ is 97. So the
ASCII value difference is (105-97)=8
strncpy(): It copies only the leftmost n characters of the source string to target string variable.
It takes the following form:
strncpy(target_string, source_string, n);
strncat(): It concatenates leftmost n characters of string2 to the end of string1. It takes the
following form:
strncat(string1,string2,n);
strstr(): It is used to search a substring whether it is present or not in another string. It takes the
following form:
strstr(string1,string2);
It searches string1 to see whether string2 is present or not inside string1. If present then it returns
the position of the first occurrence of the string2 otherwise it returns null pointer.
strchr(): It is used to determine the existence of a character in a string. It returns the position of the
first occurrence of the character. It takes the following form:
strchr(string,character);
strrchr():It is used to determine the existence of a character in a string. It returns the position of the
last occurrence of the character. It takes the following form:
strrchr(string,character);
Prepared by A. Mandal
Pointer
A pointer is a derived data type in C. Pointer contains memory addresses as their values. It is used
to access and manipulate data stored in memory. On other hand we can say that the variable which
can store the address of another variable is called pointer variable.
Ex:
int *p;
a 179 5000
int a=10;
int *p; // declaration of pointer variable
p=&a; // initialization of pointer variable
We can also combine the initialization as
int *p=&a;
** Note that p=address of variable a
*p= value of variable a
Prepared by A. Mandal
Programming example
Write a program to initialize an integer variable and a pointer variable. Display the value and
address of this integer variable using pointer variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *p;
p=&a;
clrscr();
printf(“\n The value of a is %d”,a);
printf(“\n The address of a is %u”,&a);
printf(“\n The value of a is %d”,*p);
printf(“\n The address of a is %u”,p);
getch();
}
p2 p1 a
Address of p1 Address of a Value
Here p2 is pointer to pointer because p2 contains the address of another pointer variable p1.
We can declare a pointer to pointer variable using **.
Programming Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10, *p1, **p2;
clrscr();
p1=&a;
p2=&p1;
printf(“\n Value of a is %d”,**p2);
printf(“\n Address of a is %u”,*p2);
printf(“\n Address of p1 is %u”,p2);
getch();
}
Prepared by A. Mandal
Pointer increment and scale factor
When we increment a pointer, its value is increased by the length of the data type that it points to.
This length is called the scale factor.
char *str=”GOOD”;
The pointer str now points to the first character of the string “GOOD” as:
G O O D \0
str
Prepared by A. Mandal
Programming Example
Write a program using pointer to find the length of a string.
#include<stdio.h>
#include<conio.h>
Void main()
{
char *str=”Delhi”;
int len;
char *ptr=str;
clrscr();
printf(“\n The string is: %s”,str);
while(*cptr!=’\0’)
{
ptr++;
}
len=ptr-str;
printf(“\n Length is: %d”,len);
getch();
}
D e l h i \0
str ptr
Array of pointers
Write a program to input 5 strings and display them using array of pointer.
#include<stdio.h>
#include<conio.h>
Void main()
{
char *str[5];
int i;
clrscr();
printf(“\n Enter 5 strings: “);
for(i=0;i<5;i++)
scanf(“%s”,str[i]);
printf(“\n The strings are:”);
for(i=0;i<5;i++)
printf(“\n%s”,str[i]);
getch();
}
Prepared by A. Mandal
Functions
A function is a self-contained block of code that performs a particular task. Once a function has
been defined, it can be treated as a ‘black box’ that takes some data from the main program and
returns a value.
Types of Function
There are two types of functions:
a) Built-in functions: Functions which are defined in C library and performs a predefined task is
called built-in or library functions. User can’t modify them. Ex: printf(), scanf() etc.
b) User defined functions: Functions which are defined by users and performs user defined
task is called user defined functions. User can modify those functions.
Return_type function_name(Parameter_list)
{
//Body of the function
.
.
.
.
Return statement; //if required otherwise omitted
}
Ex:
int sum(int a, int b)
{
int c;
c=a+b;
return(c);
}
Prepared by A. Mandal
3. Function call: A function can be called by simply using the function name followed by a list
of actual parameter or arguments. It takes the following form:
Category of Functions:-
i) Functions with no arguments and no return values.
ii) Functions with arguments and no return values.
iii) Functions with no arguments but return a value.
iv) Functions with arguments and one return value.
A simple program with function (Function with no arguments and no return values):-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
void india(void); //Function prototype declaration
printf(\n Now I am in America \n”);
india(); //Function calling
printf(“\n Now I am in Kanada \n”);
india(); //Function calling
printf(“\n Now I am in Japan \n”);
india(); //Function calling
getch();
}
void india(void) //Function Definition
{
Printf(“\n Now I am in my country INDIA \n”);
}
Output:-
Now I am in America
Now I am in my country INDIA
Now I am in Kanada
Now I am in my country INDIA
Now I am in Japan
Now I am in my country INDIA
Prepared by A. Mandal
Function with no arguments and no return values:-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
void add(); //Function prototype declaration
printf(“Addition Program \n\n “);
add(); //Function calling
getch();
}
void add() //Function Definition
{
Output:-
Addition Program
#include<stdio.h>
#include<conio.h>
#define P 3.14 //Global variable
void area(int r); //Function prototype declaration
void peri(int r); //Function prototype declaration
void main()
{
int x;
clrscr();
printf(“\n Enter radious : “);
scanf(“ %d “, &x);
area(x); //Function calling
peri(x); //Function calling
getch();
}
Prepared by A. Mandal
void area(int r) //Function Definition
{
float a;
a=P * r * r;
printf("\n\n The area = %.2f " , a);
}
void peri(int r) //Function Definition
{
float per;
per=2 * P * r;
printf("\n\n The perimeter = %.2f " , per);
}
Output:-
Enter radious: 3
The area = 28.26
The perimeter = 18.84
#include<stdio.h>
#include<conio.h>
int add(); //Function prototype declaration
void main()
{
int x;
clrscr();
x=add(); //Function calling
printf("\n\n The addition result = %d" , x);
getch();
}
Output:-
Find the area of circles whose radious are 3 unit, 4 unit and 7 unit using function.
#include<stdio.h>
#include<conio.h>
#define P 3.14 // Global constant
float area( int r); //Function prototype declaration
void main()
{
float a;
clrscr();
a=area(3); //Function calling
printf("\n\n The area = %.2f ", a);
a=area(4); //Function calling
printf("\n\n The area = %.2f ", a);
a=area(7); //Function calling
printf("\n\n The area = %.2f ", a);
getch();
}
Output:-
Defn:-
A function is called ‘recursive‘ if a statement within a body of this function calls the same
function. This is known as recursion.
#include<stdio.h>
#include<conio.h>
int fact(int n); //Function prototype declaration
void main()
{
int n, f;
clrscr();
printf("\n\n Enter a number: ");
scanf("%d" , &n);
f=fact(n); //Function calling
printf("\n\n The factorial = %d", f);
getch();
}
Output:-
Enter a number: 5
#include <stdio.h>
#include<conio.h>
int fibo(int);
void main()
{
int num;
int result;
Local Variables
Local variables scope is confined within the block or function where it is defined. Local
variables must always be defined at the top of a block.
When a local variable is defined - it is not initialized by the system, you must initialize it
yourself.
When execution of the block starts the variable is available, and when the block ends the
variable 'dies'.
Global Variables
Global variable is defined at the top of the program file and it can be visible and modified by
any function that may reference it.
Global variables are initialized automatically by the system when you define them!
If same variable name is being used for global and local variable then local variable takes
preference in its scope. But it is not a good practice to use global variables and local
variables with the same name.
Block:
A set of statements enclosed in a set of braces is known as a block. A block can have its own
declarations and other statements.
void main()
{ //outer block
int a=20;
…………
{ //inner block
int b=10;
…………..
}
}
Prepared by A. Mandal
Passing one dimensional array to a function
Rules:
1. The function must be called by passing only the name of the array.
2. In the function definition, the formal parameter must be an array type; the size of the array
does not need to be specified.
3. The function prototype must show that the argument is an array.
Write a program to input some integer elements and sort them into ascending order using function.
#include<stdio.h>
#include<conio.h>
void sort(int a[], int n)
{
int t, i, j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
Printf(“\n After sorting:”);
for(i=0;i<n;i++)
printf(“\n %d”,a[i]);
}
void main()
{
int x[20],i,n;
clrscr();
printf(“\n Enter the number of elements: “);
scanf(“%d”,&n);
printf(“\n Enter the %d elements: “,n);
for(i=0;i<n;i++)
scanf(“%d”,&x[i]);
sort(x, n);
getch();
}
#include<stdio.h>
#include<conio.h>
int sum(int a[][10], int m, int n)
{
int s=0, i, j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
s=s+a[i][j];
}
}
return(s);
}
void main()
{
int x[10][10], i, j, r, c,p;
float q;
clrscr();
printf(“\n Enter order of the matrix: “);
scanf(“%d%d”,&r,&c);
printf(“\n Enter %d elements: “,r*c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf(“%d”,&a[i][j]);
p=sum(x,r,c);
q=average(x,r,c);
printf(“\n Sum=%d and Average=%d”,p,q);
getch();
}
Call by value
Whenever we called a function and passed the values of variables as its argument this is known as
Call by Value. In this case if we change the value of formal parameters then actual parameter
remain unchanged.
Ex:
Write a program using function to swap the value of two variables.
Prepared by A. Mandal
#include<stdio.h>
#include<conio.h>
void swapv(int a, int b)
{
int c;
c=a;
a=b;
b=c;
printf(“\n In sub function a=%d and b=%d”,a,b);
}
void main()
{
int a=10, b=20;
clrscr();
swapv(a,b);
printf(“\n In main function a=%d and b=%d”,a,b);
getch();
}
Output:
In sub function a=20 and b=10
In main function a=10 and b=20
Call by reference
When we called a function if we pass the address of a variable as its argument this is known as Call
by reference. In this case if we change the value of formal parameters then the value of actual
parameters will be changed.
Ex:
Write a program using function to swap the value of two variables.
#include<stdio.h>
#include<conio.h>
void swapr(int *a, int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
printf(“\n In sub function a=%d and b=%d”,*a,*b);
}
void main()
{
int a=10, b=20;
clrscr();
swapr(&a,&b);
printf(“\n In main function a=%d and b=%d”,a,b);
getch();
}
Output:
In sub function a=20 and b=10
In main function a=20 and b=10
Prepared by A. Mandal
Function returning pointer
Write a program to find the largest between two numbers.
#include<stdio.h>
#include<conio.h>
int *large(int *a, int *b)
{
If(*x>*y)
return(x);
else
return(y);
}
void main()
{
int a=20, b=10;
int *p;
clrscr();
p=large(&a,&b);
printf(“\n Largest number is %d”,*p);
getch();
}
Ex:
#include<stdio.h>
#include<conio.h>
float mult(float a,float b)
{
return (a*b);
}
void main()
{
float (*ptr)(float,float); //function pointer declaration
float x;
clrscr();
ptr=mult; //initialization of pointer
x=(*ptr)(3,5); //function call using pointer
printf("\n Multiplication result is %f",x);
getch();
}
Prepared by A. Mandal
Storage Class
A storage class tells us:
i) Where the variables would be stored.
ii) What will be the initial value of the variable, if initial value is not specifically assigned.
iii) What is the scope of the variable; i.e. in which functions the value of the variable would be
available.
iv) What is the life of the variable; i.e. how long would the variable exist.
Storage Memory
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
auto int x=10;
clrscr();
printf(“x=%d”,x);
getch();
}
O/P
x=10
Prepared by A. Mandal
External storage class
The variable that are both alive and active throughout the program are known as external variables.
They are also known as global variables. They can be accessed by any function in the program. It is
declared using ‘extern’ keyword explicitly.
Storage Memory
Scope Global
Example:
#include<stdio.h>
#include<conio.h>
int i=0; //Global variable
void incr()
{
i++;
printf(“\n %d”,i);
}
void decr()
{
i- -;
printf(“\n %d”,i);
}
void main()
{
clrscr();
incr();
incr();
decr();
decr();
getch();
}
O/P
1
2
1
0
Prepared by A. Mandal
Using extern keyword
#include<stdio.h>
#include<conio.h>
void main()
{
extern int y;
clrscr();
printf(“\n y=%d”,y);
getch();
}
int y=20;
O/P
y=20
Storage Register
O/P
1
2
3
4
5
6
7
8
9
10
Prepared by A. Mandal
Static storage class
As the name suggests, the value of static variables persists until the end of the program. A ststic
variable is declared using ‘static’ keyword.
Storage Memory
Example
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void incr() void incr()
{ {
int i=0; static int i=0;
i++; i++;
printf(“\n %d”,i); printf(“\n %d”,i);
} }
void main() void main()
{ {
clrscr(); clrscr();
incr(); incr();
incr(); incr();
incr(); incr();
getch(); getch();
} }
O/P O/P
1 1
1 2
1 3
Prepared by A. Mandal
Structure & Union
Structure
Structure is a user defined data type which allows to combine data items of different kinds. It is a
convenient tool for handling a group of logically related data items. For example, it can be used to
represent a set of attributes such as student_name, roll and marks.
Defining a structure
The general format of a structure definition is:
struct tag_name
{
data_type member1;
data_type member2;
………………………
………………………
……………………..
};
Example:
struct student
{
char name[20];
int roll;
float marks;
};
Declaration of structure variable
struct student
{
char name[20];
int roll;
float marks;
}s1,s2;
OR
struct student
{
char name[20];
int roll;
float marks;
};
struct student
{
char name[20];
int roll;
float marks;
} s1={“Amal”,1,92.0},s2={“Ajit”,2,88.0};
OR
struct student
{
char name[20];
int roll;
float marks;
};
Example:
struct student
{
char name[20];
int roll;
float marks;
}s1,s2;
person1=person2;
person1==person2
person1!=person2
are not permitted. We can compare structure members individually.
Prepared by A. Mandal
***Write a program to create a structure called “book” which contains book title, author, pages
and price. Take details of two books and display the details.
#include<stdio.h>
#include<conio.h>
struct book
{
chat btitle[15];
char author[20];
int page;
float price;
};
void main()
{
struct book b1={“ANSI C”,”E Balagurusamy”,600,325.0};
struct book b2={“Let Us C”,”Y Kanitkar”,650,350.0};
clrscr();
printf(“\n Book Name: %s Author: %s Pages: %d Price: %.2f”,b1.btitle,b1.author,b1.page,b1.price”);
printf(“\n Book Name: %s Author: %s Pages: %d Price: %.2f”,b2.btitle,b2.author,b2.page,b2.price”);
getch();
}
O/P
Book Name: ANSI C Author: E Balagurusamy Pags: 600 Price: 325.00
Book Name: Let Us C Author: Y Kanitkar Pags: 650 Price: 350.00
#include<stdio.h>
#include<conio.h>
struct address
{
char vill[15];
char po[15];
char ps[15];
};
struct employee
{
char name[20];
struct address add;
float sal;
};
Prepared by A. Mandal
void main()
{
struct employee emp;
clrscr();
printf(“\n Enter name of an employee: “);
scanf(“%s”, emp.name);
printf(“\n Enter village, post and ps: “);
scanf(“%s%s%s”, emp.add.vill,emp.add.po,emp.add.ps);
printf(“\n Enter salary: “);
scanf(“%f”, &emp.sal);
printf(“\n Name: %s”,emp.name);
printf(“\n Vill: %s PO: %s PS: %s”,emp.add.vill,emp.add.po,emp.add.ps);
printf(“\n Salary: %.2f”, emp.sal);
getch();
}
Array of structure
*** Write a program to create a structure called Student which contains name, roll and marks.
Take the details of n students and arrange them according to their marks from highest to lowest.
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int roll;
float marks;
};
void main()
{
struct student s[50];
struct student temp;
int n, i, j;
clrscr();
printf(“\n How many students? “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\n Enter name, roll and marks of student %d”,(i+1));
scanf(“%s%d%f”,s[i].name,&s[i].roll,&s[i].marks);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[j].marks>s[i].marks)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
Prepared by A. Mandal
}
}
}
getch();
}
Structure pointer
***Write a program to create a structure called “book” which contains book title, author, pages
and price. Take details of two books and display the details using structure pointer.
#include<stdio.h>
#include<conio.h>
struct book
{
chat btitle[15];
char author[20];
int page;
float price;
};
void main()
{
struct book *b1;
clrscr();
printf(“\n Enter book name, author, pages and price: “);
scanf(“%s%s%d%f”, b1->btitle, b1->author,&b1->page,&b1->price);
O/P
Enter book name, author, pages and price: Let_Us_C Y_Kanitkar 650 350
Example
#include<stdio.h>
#include<conio.h>
union student
{
char name[20];
int roll;
float marks;
};
void main()
{
union student st;
clrscr();
printf(“\n Enter student name: “);
scanf(“%s”,st.name);
printf(“\n Name is: %s”,st.name);
printf(“\n Enter roll: “);
scanf(“%d”,&st.roll);
printf(“\n Roll is: %d”,st.roll);
printf(“\n Enter mark: “);
scanf(“%f”,&st.marks);
printf(“\n Mark is: %.2f”,st.marks);
getch();
}
O/P
i) Structure is defined using keyword struct. On the other hand union is defined using
keyword union.
ii) The amount of memory required to store a structure variable is the sum of the size of all
the members.
On the other hand, in case of unions, the amount of memory required is always equal to
that required by its largest member.
iii) In case of structure, each member has their own memory space but In union, one block
is used by all the member of the union.
i) An array is a collection of related data elements of same type. But Structure can have
elements of different types.
ii) An array is a derived data type. But A structure is a user-defined data type.
iii) Any array behaves like a built-in data types. All we have to do is to declare an array
variable and use it. But in the case of structure, first we have to design and declare a
data structure before the variable of that type are declared and used.
Prepared by A. Mandal
DYNAMIC MEMORY ALLOCATION:
The process of allocating memory at run time is known as dynamic memory. There
are four library routines known as “memory management functions” that can be used for allocating
and freeing memory during program executions.
MEMORY ALLOCATION FUNCTIONS
Function Task
malloc Allocates request size of bytes and returns a pointer to the first byte of the
allocated space.
calloc Allocates space for an array of elements,initializes them to zero then returns a
pointer to the memory.
Free Frees previously allocated space.
Realloc Modifies the size of previously allocated space.
The above statements allocates contiguous space for n blocks, each of size elem-size bytes. All
bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If
there is not enough space, a null pointer is returned.
Example
. . . . .
. . . . .
struct student
{
char name[30];
float age;
longintid_num;
};
typedefstruct student record;
record *st_ptr;
intclass_size=30;
st_ptr=(record *)calloc(class_size, sizeof(record));
. . . . .
. . . . .
Prepared by A. Mandal
RELEASING THE USED SPACE : FREE
When we no longer need the data we stored in a block of memory, and we do not
intend to use that block for storing any other information, we may release that block of memory for
future use, using the free function.
free(ptr);
Example: write a program to store a character string in a block of memory space created by
malloc and then modify the same to store a larger string.
Ans : #include<stdio.h>
#include<stdlib.h>
#define null 0
main()
{
char *buffer;
/*Allocating memory*/
if(buffer= (char *)malloc(10)==NULL)
{
printf(“malloc failed.\n”);
exit(1);
}
printf(“Buffer of size %d created \n”,_msize(buffer));
strcpy(buffer,“HYDRABAD”);
printf(“\nBuffer contain:%s\n”,buffer);
/*Reallocation*/
if(buffer=(char *)realloc(buffer, 15)==NULL)
{
printf(“Reallocation failed. \n”);
exit(1);
}
printf(“\nBuffer size modified. \n”);
printf(“\nBuffer still contain: %s \n”,buffer);
strcpy(buffer, “SECUNDERABAD”);
printf(“\nBuffer now contains:%s \n”,buffer);
/*FREE MEMORY*/
free(buffer);
}
OUTPUT:
Buffer of size 10 created
Buffer contain: HYDERABAD
Buffer size modified
Buffer still contains: HYDERABAD
Buffer now contains: SECUNDERABAD
Prepared by A. Mandal
LINKED LISTS:
A completely different way to represent a list is to make each item in the list part of
a structure that also contains a “link” to the structure containing the next item. This type of list is
called a linked list because it is a list whose order is given by links form one item to the next.
Structure 1 structure 2 structure 3
item item item
mode Description
"w" Creates an empty file for writing. If a file with the same name already
exists, its content is erased and the file is considered as a new empty file.
"a" Appends to a file. Writing operations, append data at the end of the file.
The file is created if it does not exist.
"r+" Opens a file to update both reading and writing. The file must exist.
Here fp is a “pointer to the data type FILE”. FILE is a structure that is defined in the I/O library.
Example:-
FILE *f1;
f1=fopen(“Data.txt” , ”r”);
Syntax for closing a file:-
fclose(file_pointer);
Example:-
FILE *f1;
f1=fopen(“Data.txt”, “r”);
…………………..
fclose(f1);
Syntax of getc() :-
c=getc(fp);
Here c is a character type variable and fp is file pointer.
Syntax of putc() :-
putc(c , fp);
Syntax of getw() :-
n=getw(fp);
Here n is an integer type variable and fp is file pointer.
Syntax of putw() :-
putw(n , fp);
Here n is an integer type variable and fp is file pointer.
Prepared by A. Mandal
Sample Programs:-
******Write a C program to input some integer numbers to a file and display the numbers from
this file.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int number, i;
clrscr();
printf(“\n\n Enter numbers \n\n “);
fp=fopen(“data.txt” , “w”);
for(i=1, i<=30, i++)
{
scanf(“%d”, &number);
if(number == -1) break;
putw(number,fp);
}
fclose(fp);
fp=fopen("data.txt" , "r");
printf("\n\n The content of this file is:\n\n ");
while((number=getw(fp))!=EOF)
{
printf("%d ",number);
}
fclose(fp);
getch();
}
******Write a C program to input some characters to a file and display these characters from this
file.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1;
char ch;
clrscr();
printf(“\n\n Enter text \n\n “);
f1=fopen(“text.txt” , “w”);
while((ch=getchar())!=EOF)
{
putc(ch,f1);
}
fclose(f1);
f1=fopen("text.txt" , "r");
Prepared by A. Mandal
printf("\n\n The content of this file is:\n\n ");
while((ch=getc(f1))!=EOF)
{
printf("%c ",ch);
}
fclose(f1);
getch();
}
OUTPUT:
Input filename
TETS
Cannot open the file.
Type filename again.
TEST
10
20
30
40
50
60
70
80
90
100
Ran out of data.
Statements Meaning
fseek(fp,0L,0); Go to the beginning. (Similar to rewind)
fseek(fp,0L,1); Stay at the current position. (Rarely used)
fseek(fp,0L,2); Go to the end of the file, past the last character of the file.
fseek(fp,m,0); Move to (m+1)th byte in the file.
fseek(fp,m,0); Go forward by m bytes.
fseek(fp,m,0); Go backward by m bytes from the current position.
fseek(fp,m,0); Go backward by m bytes from the end. (Positions the file to the mth
character from the end.)
Prepared by A. Mandal
EXAMPLE: Write a program that uses the functions ftell and fseek.
A program employing ftell and fseek functions is shown in below. We have created a file RANDOM with
the following contents:
Position 0 1 2 …..25
Chrecter stored A B C …..Z
Program:
#include<stdio.h>
main()
{
FILE *fp;
long n;
char c;
fp = fopen(“RANDOM”,”w”);
while((c=getchar())!= EOF)
putc(c,fp);
printf(“No. of charecters entered = %ld\n”, ftell(fp));
fclose(fp);
fp = fopen(“RANDOM”,”r”);
n=0L;
while(feof(fp)==0)
{
fseek(fp,n,0); /*Position to (n+1)th character */
printf(“Position of %c is %ld\n”,getc(fp),ftell);
n=n+5L;
}
putchar(‘\n’);
fseek(fp,-1L,2); /*Position to the last character */
do
{
putchar(getc(fp));
}
while(!fseek(fp,-2L,1));
fclose(fp);
}
OUTPUT:
ABCDEFGHIJKLMNOPQRSTUVWXY^Z
No. of characters entered = 26
Position of A is 0
Position of F is 5
Position of K is 10
Position of P is 15
Position of U is 20
Position of Z is 25
Position of is 30
ZYXWVUTSRQPONMLKJIHGFEDCBA
Prepared by A. Mandal
Command Line Arguments
It is a parameter supplied to a program when the program is invoked. In fact main function can take
two arguments called argc and argv and the information contained in the command line is passed
onto the program through these arguments, when main is called up by the system.
The argument argc is an argument counter that counts the number of arguments on the command
line. The argument argv is an argument vector that stores the supplied arguments.
In order to access the command line arguments, we must declare the main function and its
parameter as follows:
……………….
……………….
}
Example:
Here
argc=3
argv[0]=copyfile
argv[1]=x_file
argv[2]=y_file
*** Write a program to copy the content of one file into another file using command line
arguments.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(int argc, char argv[])
{
FILE *fs, *ft;
Char ch;
If(argc!=3)
{
printf(“\n Improper number of arguments”);
exit(1);
}
fs=fopen(argv[1],”r”);
if(fs==NULL)
{
printf(“\n Cannot open source file”);
exit(2);
Prepared by A. Mandal
}
ft=fopen(argv[2],”w”);
if(ft==NULL)
{
printf(“\n Cannot open target file”);
exit(3);
}
while((ch=getchar())!=EOF)
{
putc(ch,ft);
}
fclose(fs);
fclose(ft);
}
The Preprocessor
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process.
In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do
required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character,
and for readability, a preprocessor directive should begin in the first column. The following section
lists down all the important preprocessor directives −
Directive Description
If this statement is included in the program at the beginning, then the preprocessor replaces every
occurrence of the identifier in the source code by the value.
Example: