cNew
cNew
I. Computer Hardware.
C. Primary Storage: It is also known as main memory . It is a place where the programs and
data is stored temporarily during processing. The Data in primary storage is erased
, when we turn off a personal computer or when we log off from a time-sharing
computer ( volatile ).
E. Auxiliary Storage Devices ( secondary storage devices ): It is used for both input and output.
It is also known as secondary storage. It is a place where the programs and data are
stored permanently. when we turn off the computer the programs and data remain in the
secondary storage, ready for the next time when we need them.
II. Computer Software : Software is the collection of Programs ( instructions ) that allow
the hardware to do its job.
They are two types of Computer Software.
A. System Software
B. Application Software
i. Operating System Software: It provides services such as a user interface, files and data base
access and interfaces to communication systems such as Internet protocols. The primary
purpose of this software is to keep the system operating in an efficient manner while
allowing the users access to the system.
ii. System Support Software : System Support Software provides system utilities and other
operating services. Examples of system utilities are sort programs and disk format programs.
Operating services consist of programs that provide performance statistics for the operational
staff and security monitors to protect the system and data.
iii. System Development Software: It includes language translators that convert programs in to
machine language for execution , debugging tools to ensure that programs are error - free and
computer -assisted software engineering ( CASE ) systems.
B. Application Software: It is directly responsible for helping users to solve their problems.
Application software is broken in to two classes.
i. General - Purpose Software
ii. Application - Specific Software
i. General Purpose Software: It is purchased from a software developer and can be used for
more than one application. Examples: word processors, database management systems, computer –
aided design systems. They are labeled general purpose because they can solve a variety of user
computing problems.
ii. Application Specific Software: It can be used only for its intended purpose.
Example: A general ledger system used by accountants.
They can be used only for the task for which they were designed.They can not be used for
other generalized tasks.
Relationship between system and application software is shown in the figure:
A. Writing and Editing Program : The Software to write programs is known as text
editor. A text editor helps us enter , change and store character data. Depending on the
editor on our system, it could be used to write letters, create reports or write programs.
Example : word processor.
The text editor could be generalized word processor, but every compiler comes with
associated text editor. Some of the features of editors are
Search : To locate and replace statements.
Copy , Paste : To copy and move statements.
Format : To set tabs to align text.
After the program is completed the program is saved in a file to disk. This file will be
input to the compiler, it is known as source file. The following figure shows the various
steps in building a C – program.
B. Compiling Programs: The code in a source file on the disk must be translated in to
machine language. This is the job of compiler which translates code in source file stored on
disk in to machine language. The C compiler is actually two separate programs: the
preprocessor and the translator. The preprocessor reads the source code and prepares it for
the compiler. It scans special instructions known as preprocessor commands. These commands
tell the preprocessor to take for special code libraries, make substitutions in the code. The
result of preprocessing is called translation unit. The translator reads the translation unit
and writes resulting object module to a file that can be combined with other precompiled
units to form the final program. An
object module is the code in machine language. This module is not ready for execution
because it does not have the required C and other functions included.
A. Understand the problem :The first step in solving any problem is understand it. We
begin by reading the requirements statements carefully.When we think that we fully understand
it, we review our understanding with the user and the system analyst.
Example: Calculate the square footage of house.
The questions that arise are
1. What is definition of square footage ?
2. How is it useful ?
C. Analysis: User requirements are transformed to technical terms like Blueprint and
also look for different alternatives considering all risks.
D. Design: In UML software users will develop flowcharts, structure charts, data flow diagrams
1. Choose the best way to find solution among different alternatives.
2. Choose in analysis , design files , databases and functions.
E. Code:
Unimportant in Software development life cycle
1. Uses software for code generation ( forward energy ).
2. Otherwise go for manual coding.
3. Basic testing is done ( compilation ).
F. System Test :Test if user requirements are met Blackbox Testing: Test programs
together, make sure system works as a whole. Whitebox Testing: Release ά-version to
customer, according to his/her feed back we develop β-Version: β - version is released to
selected group of people.
G. Maintenance :
Keeps the system working once it has been put in to production ?
Ans: Algorithm:
The same problem can be solved with different methods. So, to solve a problem different
algorithms, may be accomplished. Algorithm may vary in time, space utilized. User writes
algorithm in his / her own language. So, it can not be executed on computer. Algorithm
should be in sufficient detail that it can be easily translated in to any of the languages.
Example1 : Add two numbers.
Step 1: Start
Step 2: Read 2 numbers as A and B
Step 3: Add numbers A and B and store result in C
Step 4 : Display C
Step 5: Stop
Example2: Average of 3 numbers.
1. Start
2. Read the numbers a , b , c
3. Compute the sum and divide by 3
4. Store the result in variable d
5. Print value of d
6. End
Ans: Flowchart :
Purpose of a Flowchart :
Provides Communication.
Provides an Overview.
Shows all elements and their relationships.
Quick method of showing Program flow.
Checks Program logic.
Facilitates Coding.
Provides Program revision.
Provides Program documentation.
Advantages of a Flowchart :
· Flowchart is an important aid in the development of an algorithm itself.
· E asier to Understand than a Program itself.
· Independent of any particular programming language.
· Proper documentation.
· Proper debugging.
· Easy and Clear presentation.
Limitations of a Flowchart :
· Complex logic.
· Drawing is time consuming.
· Difficult to draw and remember.
· Technical detail.
Step 1 : Start
Step 2 : Input num1 , num2
Step 3 : temp = num1
Step 4 : num1 = num2
Step 5 : num2 = temp
Step 6 : Output num1 , num2
Step 7 : Stop
Algorithm : b. with out using third variable
Step 1 : Start
Step 2 : Input num1 , num2
Step 3 : calculate num1 = num1 + num2
Step 4 : calculate num2 = num1 – num2
Step 5 : calculate num1 = num1 – num2
Step 6 : Output num1 , num2
Step 7 : Stop
Flowcharts :
10. Write an algorithm and flowchart to find the largest among two numbers.
Ans:
Algorithm:
Step 1 : Start
Step 2 : Input A , B
Step 3 : if A > B then output A
else output B
Step 4 : Stop
Flowchart :
11. Write an algorithm and flowchart to find the largest among three numbers.
Algorithm: (method 1)
Step 1 : Start
Step 2 : Input A, B, C
Step 3 : if A > B go to step 4 , otherwise go to step 5
Step 4 : if A > C go to step 6 , otherwise go to step 8
Step 5 : if B > C go to step 7, otherwise go to step 8
Step 6 : print “ A is largest ” , go to step 9
Step 7 : print “ B is largest ”, go to step 9
Step 8 : print “ C is largest ” , go to step 9
Step 9 : Stop
Flowchart:
Algorithm: b.
Step 1 : Start
Step 2 : Input A, B, C
Step 3 : Let max = A
Step 4 : if B > max then max = B
Step 5 : if C > max then max = C
Step 6 : output max is largest
Step 7 : Stop
Flowchart:
12. Write an algorithm and flowchart to find factorial of a
number Hint: fact (4) = 1 * 2* 3* 4
Sol.
Alg
orithm: Step
1: Start
Step 2:
Input n
Step 3: Initialize counter variable, i , to 1 and factors
= 1 Step 4: if i <= n go to step 5 otherwise go to step
7
Step 5: calculate factors = factors * i
Step 6: increment counter variable, i, and go to
step 4 Step 7: output factors.
Step 8: stop
Flow chart:
13. Write an algorithm and flowchart to find whether a number is prime or not.
Hint: A number is said to be prime number for which the only factors are 1 and
itsel Algorithm:
Step 1: Start
Step 2: Input n
Step 3: Let i = 1,
count=0 Step 4: if i >
n/2 go to step 7
Step 5: if (n % i = = 0) count = count
+ 1 Step 6: increment i and go to step 4
Step 7: if count=2 then print “prime number” else print “not prime
number” Step 8: Stop
Flow chart:
15. Write an algorithm and flowchart to find the Sum of individual digits if a given number
Algorithm :-
Step 1 : Start
Step 2 : read
n Step 3 :
Sum = 0
Step 4 : While n > 0 do
4.1 : r = n % 10
4.2 : Sum = Sum + r
4.3 : n =
n/10 Step 5 : End
while
Step 6 : Write
Sum Step 7 :
Stop
Flowchart :-
16. what is the general structure of `C' program and explain with
example?
Ans: Structure of C program:
This section consists of a set of comment lines giving the name of the program, and other
details. In which the programmer would like to user later.
Ex:- /*…................................*/
Link section: Link section provides instructions to the compiler to link functions from the
system library.
Ex:- #
include<stdio.h
> #
include<conio.
h>
Definition section: Definition section defines all symbolic
constants. Ex:- # define A 10.
Global declaration section: Some of the variables that are used in more than one function
throughout the program are called global variables and declared outside of all the functions.
This section declares all the user-defined functions.
Every C program must have one main ( ) function section. This contains two parts.
i) Declaration part: This part declares all the variables used in the executable part.
ii) Executable part: This part contains at least one statement .These two parts must appear
between the opening and closing braces. The program execution begins at the opening brace
and ends at the closing brace. All the statements in the declaration and executable parts end
with a semicolon (;).
Sub program section:
This section contains all the user-defined functions, that are called in the main () function.
User- defined functions generally places immediately after the main() function, although they
may appear in any order.
Ex:
17. What is a variable? and write the rules for constructing variable?
Variables: It is a data name that may be used to store a data value. It cont be changed during
the execution of a program. A variable may taken different values at different times during
execution.
Rules: Variable names may consist of letters, digits and under score( _ ) character.
The declaration of variables must be done before they are used in the program.
Data-type v1,v2,…….,vn;
V1,v2,…vn are the names of variables. Variables are separated by commas. A declaration
statement must end with a semicolon. For example , valid declarations are:
int count;
int number,
total; double
ratio;
The simplest declaration of a variable is shown in the following code fragment:
Ex:
main()/*…………….Program Name…..................*/
/*……………….Declaration..........................................*/
float
x,y;
int
code;
short int
count; long
int amount;
double
deviation;
unsigned n;
char c;
/*…………………………Computation........................................ */
/*…………………………Program ends..............................*/
Initialization of variable :
Initialize a variable in c to assign it a starting value. Without this we can't get whatever
happened to memory at that moment.
C does not initialize variables automatically. So if you do not initialize them properly,
you can get unexpected results. Fortunately, C makes it easy to initialize variables when
you declare them.
For Example :
int x=45;
DATA TYPES
Data type is the type of the data that are going to access within the program. C supports
different data types. Each data type may have pre-defined memory requirement and storage
representation. C supports 4 classes of data types.
1. Primary or (fundamental) data type(int, char, float, double)
2. User-defined data type(type def)
3. Derived data type(arrays, pointers, structures, unions)
4. Empty data type(void)- void type has no value.
1 byte = 8 bits (0’s and 1’s)
1. Primary or (fundamental) data type
i) Integer (int)
ii) Character(char)
iii) Floating (float)
iv) Double – precision floating point(double)
1. Integer types:
Integers are whole numbers with a range of values supported by a particular machine.
Integers occupy one word of storage and since the word size of the machine vary. If we use
16 bit word length the size of an integer value is -32768 to +32767. In order to control over
the range of numbers and storage space, C has 3 classes of integer storage, namely short,
long, and unsigned.
2. Character type:-
Single character can be defined as a character (char) type data. Characters are usually stored
in 8 bits of internal storage. Two classes of char types are there.
Signed char, unsigned char.
Signed char(or) char 1 byte- -128 to +127%c
Unsigned char 1 byte 0 to 255%c
3. Floating point types:
Floating point (real) numbers are stored in 32 bits, with 6 digits of precision when accuracy
provided by a float number is not sufficient
Float 4 bytes3.4e-38 to 3.4e+38%f
Double data type number uses 64 bits giving a precision of 14 digits. These are known as
double precision no.s. Double type represents the same data type that float represents, but
with a greater precision. To extend the precision further, we may we long double which uses
80 bits.
double 8 bytes 1.7e-308 to 1.7e+308%lf
long double 10 bytes 3.4e-4932 to
1.1e+4932 %lf
2. User defined data types:
C –supports a feature known as “type definition” that allows users define an identifier that
would represents an existing type.
Ex:- typedef data-type identifier;
typedef cont create a new data type ,it can rename the existing datatype. The main
advantage of typedef is that we can create meaningful datatype names for increasing the
readability of the program.
Another user-defined datatype is “enumerated data
type(enum)” Syntax: enum identifier{value1, value2,…
valuen};
Where identifier is user-defined datatype which is used to declare variables that can have one
of the values enclosed within the braces. Value1 ,value2,.valuen all these are known as
enumeration constants.
Ex:- enum identifier v1, v2,……vn
V1=value3;
V2=value1;…
……
Ex:- enum day {Monday,Tuesday..................sunday};
Enum day week-f,week-end
Week-f = Monday
-
-
-
-
(or)
enum day{Monday…Sunday}week-f, week-end;
20. (a) Describe the different types of constants in C with example?
(b) What are the rules for creating C constants explain with example?
TYPES OF C CONSTANTS
1. Integer constants
2. Real constants
3. Character constants
4. String constants
1. Integer constants: An integer constant refers to a sequence of digits. There are three
types of integers, namely, decimal integer, octal integer and hexadecimal integer.
Examples of Integer Constant:
426 ,+786 , -34(decimal integers)
2. Real constants: These quantities are represented by numbers containing fractional parts like
18.234. Such numbers are called real (or floating point) constants.
Examples of Real Constants:
+325.34
426.0
-32.67 etc.
The exponential form of representation of real constants is usually used if the value of the
constant is either too small or too large. In exponential form of representation the Real
Constant is represented in two parts. The first part present before 'e' is called Mantissa and
the part following 'e' is called Exponent.
For ex. .000342 can be written in Exponential form as 3.42e-4.
Note that the character constant’5’ is not same as the number 5. The last constant is a blank
space.Character constant has integer values known as ASCII values. For example, the statement
Printf(“%d”,a); would print the number 97,the ASCII value of the letter a. Similarly, the
statement printf(“%c”,97); would output the letter ‘a’
String constants: A string constant is a sequence of character enclosed in double quotes. the
characters may be letters, numbers, special characters and blank space.
Examples are:
“HELL
O!”
“1979”
“welco
me” “?
..........!”
“5+3”
“X”
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
6. Conditional operators
7. Bitwise Operators
8. Special operators
1. Arithmetic Operators:
The arithmetic operators are
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
Here a and b are operands, assign values for a=14 and b=4 we have the following
results a-b = 10
a+b = 18
a*b = 56
a/b =
3(coefficient)
a%b =
2(remainder)
2.Relational Operators:
Relational operators are used for comparing two quantities, and take certain decision. For
example we may compare the age of two persons or the price of two items….these
comparisons can be done with the help of relational operators.
23>35(false) C supports 6
relational operators
Operator Meaning
< is less than
<= is less than or equal to
> is greater than t
>= is greater than or equal to
== is equal to
!= is not equal to
Ex:- 4.5<=10(true)
6.5<-10(false)
10<4+12(true)
When arithmetic expression are used on either side of a relational operator, the arithmetic
expression will be evaluated first and then the results compared, that means arithmetic
operators have a higher priority over relational operators.
3. Logical Operator:
C has 3 logical operators. The logical operators are used when we want to test more than one
condition and make decisions.
Operator Meaning
&& Logical AND
|| Logical OR
! LogicalNOT
The logical operators && and || are used when we test more than one condition and make decisions.
4. Assignment operator:
These operators are used to assign the result of an expression to a variable. The usual
assignment operator is ‘=’
V op = exp;
++ and - - are increment and decrement operators in C. The operator ++ adds 1 to the
operand, while - - subtracts 1.both are unary operators.
++m; or m++; is equal to m=m+1(m+=1;)
We use the increment and decrement statements in for and while loops
extensively. Ex:- m=5;
Y=++m; the value of y=6 and m =6.
A prefix operator first adds 1 to the operand and then the result is assigned to the variable on
left. On the other hand, a postfix operator first assigns the value to the variable on left and
then increments the operand.
6. Conditional operator:
The operator?: works as follows: exp1 is evaluated first. If it is non-zero (true), then the
expression exp 2 is evaluated and becomes the value of the expression. If exp1 is false, exp3
is evaluated and its value becomes the value of the expression.
X = (a>b) ?
a:b; o/p:- X value
of b (45).
7. Bitwise Operator:
C supports a special operator knows as bitwise operators for manipulation of data at bit
level. These operators are used for testing the bits, or shifting them right to left. Bitwise
operators may not be applied to float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
ꞈ Bitwise exclusive OR
8. Special operators:
C supports some special operators such as comma operator, size of operator, pointer operator
(& and *) and member selection operators (. and -> ).
The comma operator: The comma operator is used to link the related expression together.
A comma linked list of expressions is evaluated left to right and the value of right- most
expression is the value of the combined expression. For example, the statement
Value = (x=10, y=5, x+y);
In for loops: for (n=1 , m=10, n<=m; n++, m++);
The sizeof operator: The sizeof is a compile time operator and when used with an operand,
it returns the number of bytes the operand occupies. The operand may be variable, a constant
or a data type qualifier.
m = sizeof (sum);
n = sizeof (long int);
The sizeof operator is normally used to determine the lengths of arrays and structures when
their sizes are not known to the programmer. It is also used to allocate memory space
dynamically to variables during execution of a program.
Z = a-b / c+d;
Operator Precedence:
gets( ):- This function is used to read group of characters(string) from the standard I/P
device. Syntax:- gets(character array variable);
Ex:- gets(s);
Puts( ):- This function is used to display string to the standard O/P
device. Syntax:- puts(char array variables);
Ex:- puts(s);
Ex:- main()
{
char s[10];
Puts(“enter
name”);
gets(s);
puts(“print
name”);
puts(s);
}
getch():- This function reads single character directly from the keyboard without displaying
on the screen. This function is used at the end of the program for displaying the output
(without pressing (Alt-F5).
Syntax: char variable_name = getch();
Ex:- char c
c = getch();
getche():- This function reads single character from the keyboard and echoes(displays) it to the
current text window.
Syntax:- char variable_name = getche();
Ex:- char c
c=
getche(); ex:-
main()
{
char ch, c;
Printf(“enter
char”); ch =
getch();
printf(“%c”,
ch);
printf(“enter
char”); c =
getche();
printf(“%c”,c);
}
O/P:- enter character a
Enter character b
b
Ex:-
main()
{
Char a;
Printf(“enter
char”); a =
getchar();
if (isupper(a))
{
x=
tolower(a)
;
putchar(x)
;
}
else
putchar(toupper(a));
}
O/P:- enter char A
a
Formatted I/O Functions: Formatted I/O refers to input and output that has been arranged in a
particular format.
UNIT-II
Whenever simple if statement is encountered, first the condition is tested. It returns either true or
false. If the condition is false, the control transfers directly to stmt-x with out considering the stmt
block. If the condition is true, the control enters into the stmt block. Once, the end of stmt block is
reached, the control transfers to stmt-x
Example Program:
PROGRAM FOR IF STATEMENT:
#include<stdio.h>
#include<conio.h> int
main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n"); getch();
}
2. If—else statement
if…else statement is used to make a decision based on two choices. It has the following form:
syntax:
if(condition)
{
True Stmt block;
}
Else
{
False stmt block;
}
Stmt-x;
In this syntax,
· If and else are the keywords.
· <condition> is a relational expression or logical expression or any expression that returns either
true or false. It is important to note that the condition should be enclosed within parentheses
( and ).
· The true stmt block and false stmt block are simple statements or compound statements or null
statements.
· Stmt-x is any valid C statement.
The flow of control using if...else statement is determined as follows:
Whenever if...else statement is encountered, first the condition is tested. It returns either true or
false. If the condition is true, the control enters into the true stmt block. Once, the end of true stmt
block is reached, the control transfers to stmt-x without considering else-body.
If the condition is false, the control enters into the false stmt block by skipping true stmt block.
Once, the end of false stmt block is reached, the control transfers to stmt-x.
Example Program:
PROGRAM FOR IF ELSE STATEMENT:
#include<stdio.h>
#include<conio.h> int
main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n");
else
printf("person is not retired\n");
getch();
}
3. Nested If—else statement
Nested if…else statement is one of the conditional control-flow statements. If the body of if
statement contains at least one if statement, then that if statement is called as “Nested if…else
statement”. The nested if…else statement can be used in such a situation where at least two
conditions should be satisfied in order to execute particular set of instructions. It can also be used to
make a decision among multiple choices. The nested if…else statement has the following form:
Syntax: If(condition1)
{
If(condition 2)
{
Stmt1
}
Else
{
Stmt 2
}
}
Else
{
Stmt 3;
}
Stmt-x;
In this syntax,
· if and else are keywords.
· <condition1>,<condition2> … <condition> are relational expressions or logical expressions or
any other expressions that return true or false. It is important to note that the condition should be
enclosed within parentheses ( and ).
· If-body and else-body are simple statements or compound statements or empty statements.
· Stmt-x is a valid C statement.
The flow of control using Nested if...else statement is determined as follows:
4. Else—if Ladder
Else if ladder is one of the conditional control-flow statements. It is used to make a decision among
multiple choices. It has the following form:
Syntax:
If(condition 1)
{
Statement 1;
}
Else if(condition 2)
{
Statement 2;
}
Else if(condition 3)
{
Statement 3;
}
Else if(condition n)
{
Statement n;
}
Else
{
Default Statement;
}
Stmt- x;
In this syntax,
· if and else are keywords. There should be a space between else and if, if they come together.
· <condition1>,<condition2>….<condtionN> are relational expressions or logical expressions or
any other expressions that return either true or false. It is important to note that the condition
should be enclosed within parentheses ( and ).
· Statement 1, statement 2,statement 3……,statement n and default statement are either simple
statements or compound statements or null statements.
· Stmt-x is a valid C statement.
The flow of control using else--- if Ladder statement is determined as follows:
Whenever else if ladder is encountered, condition1 is tested first. If it is true, the statement 1
gets executed. After then the control transfers to stmt-x.
If condition1 is false, then condition2 is tested. If condition2 is false, the other conditions are
tested. If all are false, the default stmt at the end gets executed. After then the control transfers to
stmt-x.
If any one of all conditions is true, then the body associated with it gets executed. After then the
control transfers to stmt-x.
Example Program:
PROGRAM FOR THE ELSE IF LADDER STATEMENT:
#include<stdio.h>
#include<conio.h>
void main()
{
int m1,m2,m3,avg,tot; printf("enter
three subject marks");
scanf("%d%d%d", &m1,&m2,&m3);
tot=m1+m2+m3;
avg=tot/3; if(avg>=75)
{
printf("distinction");
}
else if(avg>=60 && avg<75)
{
printf("first class"); }
else if(avg>=50 && avg<60)
{
printf("second class");
}
else if (avg<50)
{
printf("fail");
}
getch(); }
Whenever, switch statement is encountered, first the value of <exp> gets matched with case
values. If suitable match is found, the statements block related to that matched case gets executed.
The break statement at the end transfers the control to the Next-statement.
If suitable match is not found, the default statements block gets executed. After then the control
gets transferred to Next-statement.
Example Program:
#include<stdio.h>
void main()
{
int a,b,c,ch;
clrscr();
printf("\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
c=a+b;
break;
case 2: printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
c=a-b;
break;
case 3: printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
c=a*b;
break;
case 4: printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
c=a/b;
break;
case 5:return;
}
printf("\nThe result is: %d",c);
getch();
}
do-while statement:
It is one of the looping control statements. It is also called as exit-controlled looping control
statement. i.e., it tests the condition after executing the do-while loop body.
The main difference between “while” and “do-while” is that in “do-while” statement, the loop body
gets executed at least once, though the condition returns the value false for the first time, which is
not possible with while statement. In “while” statement, the control enters into the loop body when
only the condition returns true.
Syntax:
Initialization statement;
do
{ statement(s);
} while(<condition>);
next statement;
While and do are the keywords. <condition> is a relational expression or a compound relational
expression or any expression that returns either true or false. initialization statement, statement(s)
and next_statement are valid ‘c’ statements. The statements with in the curly braces are called as do-
while loop body. The updating statement should be included with in the do-while loop body. There
should be a semi-colon (;) at the end of while(<condition>).
In this syntax,
for is a keyword. exp1 is the initialization statement. If there is more than one statement, then those
should be separated with commas. exp2 is the condition. It is a relational expression or a compound
relational expression or any expression that returns either true or false. The exp3 is the updating
statement. If there is more than one statement, then those should be separated with commas. exp1,
exp2 and exp3 should be separated with two semi-colons. exp1, exp2, exp3, for- body and
next_statement are valid ‘c’ statements. for-body is a simple statement or compound statement or a
null statement.
Whenever “for” statement is encountered, first exp1 gets executed. After then, exp2 is tested. If
exp2 is true then the body of the loop will be executed otherwise loop will be terminated.
When the body of the loop is executed the control is transferred back to the for statement after
evaluating last statement in the loop.now exp3 will be evaluated and the new value is again
tested .if it satisfies body of the loop is executed .This process continues till condition is false.
Example Program:
FOR LOOP:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
printf("enter the value");
scanf("%d",&n); for(i=1;i<=n;i++)
{
printf("%d\n",i);
}
getch();
}
Jumping control-flow statements are the control-flow statements that transfer the control to the
specified location or out of the loop or to the beginning of the loop. There are 3 jumping control
statements:
1. break statement
The “break” statement is used with in the looping control statements, switch statement and nested
loops. When it is used with the for, while or do-while statements, the control comes out of the
corresponding loop and continues with the next statement.
When it is used in the nested loop or switch statement, the control comes out of that loop / switch
statement within which it is used. But, it does not come out of the complete nesting.
The syntax for the “break” statement is:
break;
In this syntax, break is the keyword. The following diagram shows the transfer of control when
break statement is used:
Any loop
{
statement_1;
statement_2;
:
break;
:
}
next_statement
Example Program:
BREAK STATEMENT:
#include<stdio.h>
#include<conio.h> int
main()
{
int i;
for(i=1; i<=10; i++)
{
if(i==6) break;
printf("%d",i);}
getch();
}
2.continue statement
A continue statement is used within loops to end the execution of the current iteration and proceed to
the next iteration. It provides a way of skipping the remaining statements in that iteration after the
continue statement. It is important to note that a continue statement should be used only in loop
constructs and not in selective control statements. The syntax for continue statement is:
continue;
where continue is the keyword. The following diagram shows the transfer of control when continue
statement is
used:
Any loop
{
statement_1;
statement_2;
:
continue;
:
}
next_statement
The goto statement transfers the control to the specified location unconditionally. There are certain
situations where goto statement makes the program simpler. For example, if a deeply nested loop is
to be exited earlier, goto may be used for breaking more than one loop at a time. In this case, a break
statement will not serve the purpose because it only exits a single loop.
If the block of statements that has label appears before the goto statement, then the control
has to move to backward and that goto is called as backward goto. If the block of statements that has
label appears after the goto statement, then the control has to move to forward and that goto is called
as forward goto.
Example Program:
PROGRAM FOR GOTO STATEMENT:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("www."); goto x;
y: printf("expert");
goto z; x:
printf("c programming");
goto y;
z:
printf(".com"); getch();
}
5. What are the differences between break statement and Continue statement?
The break statement will immediately jump to the end of the current block of code.
The continue statement will skip the rest of the code in the current loop block and will return to the
evaluation part of the loop. In a do or while loop, the condition will be tested and the loop will keep
executing or exit as necessary. In a for loop, the counting expression (rightmost part of the for loop
declaration) will be evaluated and then the condition will be tested. Take the
following example:
int i;
for (i=0;i<10;i++)
{
if (i==5) continue;
printf("%d",i); if
(i==8) break;
}
Continue means, whatever code that follows the continue statement WITHIN the loop code
block will not be exectued and the program will go to the next iteration, in this case, when the
program reaches i=5 it checks the condition in the if statement and executes 'continue', everything
after continue, which are the printf statement, the next if statement, will not be executed.
Break statement will just stop execution of the look and go to the next statement after the loop
if any. In this case when i=8 the program will jump out of the loop. Meaning, it wont continue till
i=9,10.
1) It is used to come out of loop or switch 1) It is used to come out of entire program.
or block in which it is placed.
The main difference between the while and do-while loop is in the place where the condition is to be
tested.
In the while loops the condition is tested following the while statement then the body gets
executed. Where as in do-while, the condition is checked at the end of the loop. The do-while loop will
execute at least one time even if the condition is false initially. The do-while loop executes until the
condition becomes false.
while do-while
2) The body gets executed only when the condition 2) The body gets executed at least once though the
is true. condition is false for the first time.
8. What is an array? How to declare and initialize arrays? Explain with examples
Array:-
An array is defined as an ordered set of similar data items. All the data items of an array are stored
in consecutive memory locations in RAM. The elements of an array are of same data type and each
item can be accessed using the same name.
Declaration of an array:- We know that all the variables are declared before the are used in the
program. Similarly, an array must be declared before it is used. During declaration, the size of the
array has to be specified. The size used during declaration of the array informs the compiler to
allocate and reserve the specified memory locations.
Syntax:- data_type array_name[n];
where, n is the number of data items (or) index(or) dimension.
0 to (n-1) is the range of array.
Ex: int a[5];
float x[10];
Initialization of Arrays:-
The different types of initializing arrays:
1. At Compile time
(i) Initializing all specified memory locations.
(ii) Partial array initialization
(iii) Initialization without size.
(iv) String initialization.
2. At Run Time
1. Compile Time Initialization
We can initialize the elements of arrays in the same way as the ordinary variables when they are
declared. The general form of initialization of arrays is
Type array-name[size]={ list of values};
(i) Initializing all specified memory locations:- Arrays can be initialized at the time of
declaration when their initial values are known in advance. Array elements can be initialized
with data items of type int, char etc.
Ex:- int a[5]={10,15,1,3,20};
During compilation, 5 contiguous memory locations are reserved by the compiler for the variable a
and all these locations are initialized as shown in figure.
(iii) Initialization without size:- Consider the declaration along with the initialization.
Ex:-
char b[]={'C','O','M','P','U','T','E','R'};
In this declaration, eventhough we have not specified exact number of elements to be used in array
b, the array size will be set of the total number of initial values specified. So, the array size will be
set to 8 automatically. the array b is initialized as shown in figure.
An array consisting of two subscripts is known as two-dimensional array. These are often known as
array of the array. In two dimensional arrays the array is divided into rows and columns,. These are
well suited to handle the table of data. In 2-D array we can declare an array as :
Declaration:-
Syntax:
Data_type array_name[row_size][column_size] = {{list of first row elements},
{list of second row elements},….
{list of last row elements}};
where first index value shows the number of the rows and second index value shows the no. of the
columns in the array. We will learn about the 2-D array in detail in the next section, but now
emphasize more on how these are stored in the memory.
Initialization:-
Where first index value shows the number of the rows and second index value shows the no. of the
columns in the array.
10. Explain how two dimensional arrays can be used to represent matrices.
(or)
Define an array and how the memory is allocated for a 2D array?
In Row-Major Implementation of the arrays, the arrays are stored in the memory in terms of the
row design, i.e. first the first row of the array is stored in the memory then second and so on.
Suppose we have an array named arr having 3 rows and 3 columns then it can be stored in the
memory in the following manner :
int arr[3][3];
arr[3][3] = { 1, 2, 3,
4, 5, 6,
7, 8, 9 };
and it will be represented in the memory with row major implementation as follows :
1 2 3 4 5 6 7 8 9
In Column-Major Implementation of the arrays, the arrays are stored in the memory in the term of
the column design, i.e. the first column of the array is stored in the memory then the second and so
on. By taking above eg. we can show it as follows :
arr[3][3] = { 1, 2, 3,
4, 5, 6,
7, 8, 9 };
and it will be represented in the memory with column major implementation as follows :
1 4 7 2 5 8 3 6 9
An array consisting of two subscripts is known as two-dimensional array. These are often known as
array of the array. In two dimensional arrays the array is divided into rows and columns,. These are
well suited to handle the table of data. In 2-D array we can declare an array as :
Declaration:-
Syntax:
Data_type array_name[row_size][column_size];
Initialization :-
int arr[3][3] ;
Where first index value shows the number of the rows and second index value shows the no. of the
columns in the array.
These are stored in the memory as given below.
arr[0][0] arr[0][1] arr[0][2]
Multidimensional arrays are often known as array of the arrays. In multidimensional arrays the
array is divided into rows and columns, mainly while considering multidimensional arrays we will
be discussing mainly about two dimensional arrays and a bit about three dimensional arrays.
Syntax:
4, 5, 6,
7, 8, 9
};
where first index value shows the number of the rows and second index value shows the no. of the
columns in the array. To access the various elements in 2-D we can access it like this:
printf("%d", a[2][3]);
/* its output will be 6, as a[2][3] means third element of the second row of the array */ In 3-
D we can declare the array in the following manner :
int arr[3][3][3] =
{ 1, 2, 3,
4, 5, 6,
7, 8, 9,
/* here we have divided array into grid for sake of convenience as in above declaration we have created
3 different grids, each have rows and columns */
If we want to access the element the in 3-D array we can do it as follows :
printf("%d",a[2][2][2]);
/* its output will be 26, as a[2][2][2] means first value in [] corresponds to the grid no. i.e. 3 and
the second value in [] means third row in the corresponding grid and last [] means third column
*/
Ex:-
Int arr[3][5][12];
Float table[5][4][5][3];
Arr is 3D array declared to contain 180 (3*5*12) int type elements. Similarlly tabnle is a 4D
array comntaining 300 elements of float type.
12. Write a program to perform matrix addition.
/*ADDITION OF TWO MATRICES*/
#include<stdio.h> void
main()
{
int i,j;int a[2][2]={1,2,3,4};
int b[2][2]={1,2,3,4};
int c[2][2]; clrscr();
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%2d",a[i][j]);
}
printf("\n\n");
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{printf("%d",b[i][j]);
}
printf("\n\n");
}
Printf(“\n The addition of given two matrices is\n”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
Printf(“%d”,c[i][j]);
getch();
}
OUTPUT:
1 2
3 4
1 2
3 4
The addition of given two matrices is
2 4
6 8
13. Write a program to perform matrix multiplication
/*MATRIX MULTIPLICATION*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
clrscr();
printf("\n enter the matrix elements");
for(i=0;i<3;i++);
{
for(j=0;j<3;j++);
{
scanf("%d",&a[i][j]);
}
}
printf("\n a matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d\t",&b[i][j]);
}
}
printf("\n b matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ c[i][j]=0;
for(k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("\n The multiplication of given two matrices is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
OUTPUT:
enter the matrix elements
1 1 1
1 1 1
1 1 1
22 2
22 2
22 2
A matrix is:
1 1 1
1 1 1
1 1 1
B matrix is:
2 2 2
2 2 2
2 2 2
15. Define C string? How to declare and initialize C strings with an example?
C Strings:-
In C language a string is group of characters (or) array of characters, which is terminated by
delimiter \0 (null). Thus, C uses variable-length delimited strings in programs.
Declaring Strings:-
Since strings are group of characters, generally we use the structure to store these characters is a
character array.
Syntax:- char string_name[size];
The size determines the number of characters in the string name.
Ex:- char city[10];
Char name[30];
Initializing strings:-
There are several methods to initialize values for string variables.
A string is stored in array, the name of the string is a pointer to the beginning of the string. The
character requires only one memory location.
If we use one-character string it requires two locations. The difference shown below,
Because strings are variable-length structure, we must provide enough room for maximum- length
string to store and one byte for delimiter.
16. Explain about the string Input/ Output functions with example?
Reading and Writing strings:-
C language provides several string functions for input and output.
String Input/Output Functions:-
C provides two basic methods to read and write strings. Using formatted input/output functions and
using a special set of string only functions.
Reading strings from terminal:-
(a) Using formatted input/output:- scanf can be used with %s format specification to read a string.
Ex:- char name[10];
scanf(“%s”,name);
Here don’t use ‘&’ because name of string is a pointer to array. The problem with scanf, %s is that it
terminates when input consisting of blank space between them.
Ex:- NEW YORK
Reads only NEW (from above example).
(b) Special set of functions:-
(1) getchar():- It is used to read a single character from keyboard. Using this function repeatedly we
may read entire line of text and stored in memory.
Ex:- char ch=’z’;
ch=getchar();
(2) gets():- It is more convenient method of reading a string of text including blank spaces.
Ex:- char line[100];
gets(line);
Writing strings on to the screen:-
(1) Using formatted output functions:- printf with %s format specifier we can print strings in
different formats on to screen.
Ex:- char name[10];
printf(“%s”,name);
Ex:- char name[10];
printf(“%0.4”,name);
/* If name is JANUARY prints only 4 characters ie., JANU */
Printf(“%10.4s”,name);
printf(“%-10.4s”,name);
(2) Using special set of functions:-
(a) putchar():- It is used to print one by one character.
Ex:- putchar(ch);
(b) puts():- It is used to print strings including blank spaces.
Ex:- char line[15]=”Welcome to lab”;
puts(line);
17. Explain about the following string handling functions with example programs.
(i) strlen ( ) (ii) strcpy (iii) strcmp ( ) (iv) strcat
(i) strlen( )
C supports a number of string handling functions. All of these built-in functions are aimed at
performing various operations on strings. All of these built-in functions are defined in the header file
string.h.
strlen() function: This function is used to find the length of the string excluding the NULL
character. In other words, this function is used to count the number of characters in a string. Its
syntax is as follows:
intstrlen(string);
strcpy(string1,string2);
intstrcmp(string1,string2);
#include<stdio.h>
#include<string.h>
main()
{
char string1[30],string2[15];
int x;
printf(“\n Enter first string:”);
gets(string1);
printf(“\n Enter second string:”);
gets(string2);
x=strcmp(string1,string2);
if(x==0)
printf(“\n Both strings are equal”);
else if(x>0)
printf(“\n First string is bigger”);
else
printf(“\n Second string is bigger”);
}
(iv) strcat ( )
This function is used to concatenate two strings. i.e., it appends one string at the end of the
specified string. Its syntax as follows:
strcat(string1,string2);
#include<stdio.h>
#include<string.h>
main()
{
char string1[30],string2[15];
printf(“\n Enter first string:”);
gets(string1);
printf(“\n Enter second string:”);
gets(string2);
strcat(string1,string2);
printf(“\n Concatenated string=%s”,string1);
}
18. Write about storage representation of fixed and variable length format strings with
example?
String concepts:-
In general a string is a series of characters (or) a group of characters. While implementation of
strings, a string created in pascal differs from a string created in C language.
1. Fixed-length strings:
When implementing fixed-length strings, the size of the variable is fixed. If we make it too small we
can’t store, if we make it too big, then waste of memory. And another problem is we can’t
differentiate data (characters) from non-data (spaces, null etc).
2. Variable-length string:
The solution is creating strings in variable size; so that it can expand and contract to accommodate
data. Two common techniques used,
(a) Length controlled strings:
These strings added a count which specifies the number of characters in the string.
Ex:-
5 H E L L O
Ex:-
19. How can we declare and initialize Array of strings in C? Write a program to read
and display array of strings.
We have array of integers, array of floating point numbers, etc.. similarly we have array of
strings also.
Collection of strings is represented using array of strings.
Declaration:-
char arr[row][col];
where,
arr - name of the array
row - represents number of strings
col - represents size of each string
Initialization:-
char arr[row][col] = { list of strings };
Example:-
char city[5][10] = { “DELHI”, “CHENNAI”, “BANGALORE”, “HYDERABAD”,
“MUMBAI” };
D E L H I \0
C H E N N A I \0
B A N G A L O R E \0
H Y D E R A B A D \0
M U M B A I \0
In the above storage representation memory is wasted due to the fixed length for all strings. More
convenient way to initialize array of strings is as follows.
char *city[5] = { “DELHI”, “CHENNAI”, “BANGALORE”, “HYDERABAD”,
“MUMBAI” };
D E L H I \0
C H E N N A I \0
B A N G A L O R E \0
H Y D E R A B A D \0
M U M B A I \0
String Variables
where,
str - the string contains the data to be scanned. The string may be read from file or using gets function.
format string – format specifiers such as %d, %c, %f etc.
variables – list of variables in which the data will be converted
3.1 : Introduction: Functions are a group of statements that have been given a name. This allows you to break
your program down into manageable pieces and reuse your code.
🞂 The advantages of functions are:
◦ Function makes the lengthy and complex program easy and in short forms. It means large
program can be sub-divided into self-contained and convenient small modules having unique
name.
◦ The length of source program can be reduced by using function by using it at different places in
the program according to the user’s requirement.
◦ By using function, memory space can be properly utilized. Also less memory is required to run
program if function is used.
◦ They also allow more than one person to work on one program.
◦ Function increases the execution speed of the program and makes the programming
simple.
◦ By using the function, portability of the program is very easy.
◦ It removes the redundancy (occurrence of duplication of programs) i.e. avoids the repetition and
saves the time and space.
◦ Debugging (removing error) becomes very easier and fast using the function sub-programming.
◦ Functions are more flexible than library functions.
◦ Testing (verification and validation) is very easy by using functions.
◦ User can build a customized library of different functions used in daily routine having specific
goal and link with the main program similar to the library functions.
The functions are classified into standard functions and user-defined functions. The standard functions
are also called library functions or built in functions. All standard functions, such as sqrt(), abs(), log(), sin(),
pow() etc. are provided in the library of functions. These are selective.
Most of the applications need other functions than those available in the software. These functions
must be written by the user (programmer), hence, the name user-defined functions.
You can write as many functions as you like in a program as long as there is only one main ().
As long as these functions are saved in the same file, you do not need to include a header file.
They will be found automatically by the compiler.
There are 3 parts for using functions:
Declaring them (prototypes).
Calling them,
Defining them and
3.2 Function Declaration (Prototype):
Function declaration means specifying the function as a variable depending on the return value.
It is declared in the declaration part of the main program. The
default return value from a function is always an integer.
If the function is returning a value other than an integer, it must be declared with the data type of the
value it returns.
The general form of function declaration in ANSI form is as follows:
Type_of_return_value function_name (parameter types);
The return causes an immediate exit from a function to the point from where the function is called.
It may also be used to return one value per call. All functions, except those of type void, return a
value. If no return statement is present, most compilers will cause a 0 to be returned. The return
statement can be any one of the types as shown below:
1. return;
2. return ();
3. return (constant);
4. return (variable);
5. return (expression);
6. return (conditional expression);
7. return (function);
The first and second return statements, does not return any value and are just equal to the closing
brace the function. If the function reaches the end without using a return statement, the control is
simply transferred back to the calling portion of the program without returning any value. The
presence of empty return statement is recommended in such situations.
if (x <= 10)
return (1);
The fourth return statement returns a variable to the calling function. For example:
if (x <= 10)
return (x);
The fifth return statement returns a value depending upon the expression specified inside the
parenthesis. For example:
return (a + b * c);
The sixth return statement returns a value depending upon the result of the conditional
expression specified inside the parenthesis. For example:
The parenthesis used around the expression or value used in a return statement is optional.
Arguments and parameters are the variables used in a program and a function. Variables used in the
calling function are called arguments. These are written within the parentheses followed by the name
of the function. They are also called actual parameters, as they are accepted in the main program (or
calling function).
Variables used in the function definition (called function) are called parameters. They are also
referred to as formal parameters, because they are not the accepted values. They receive values from
the calling function. Parameters must be written within the parentheses followed by the name of the
function, in the function definition.
Example:
# include <stdio.h>
void swap (int x, int y); /* function prototype */ main
()
{
int x, y; x
= 10;
y = 20;
swap (x, y); /* values passed */
}
temp = a;
a = b;
b = temp;
printf (“%d %d\n”, a, b);
}
3.6.2. Call by Reference:
The call by reference method copies the address of an argument into the formal parameter. Inside the
function, this address is used to access the argument used in the call. In this way, changes made to
the parameter affect the variable used in the call to the function.
Call by reference is achieved by passing a pointer as the argument. Of course, in this case, the
parameters must be declared as pointer types. The following program demonstrates this:
Example:
# include <stdio.h>
void swap (int *x, int *y); /* function prototype */ main
()
{
int x, y; x
= 10;
y = 20;
swap (&x, &y); /* addresses passed */ printf
(“%d %d\n”, x, y);
}
void swap (int *a, int *b)
{
int temp; temp =
*a;
*a = *b;
*b = temp;
}
The differences between call by value and call by reference:
int a; int a;
Formal parameter ‘a’ is a local variable. Formal parameter is ‘a’ local reference.
It cannot change the actual parameter. It can change the actual parameter.
We have some other type of functions where the arguments and return value may be present or
absent. Such functions can be categorized into:
Example:
This program illustrates the function with no arguments but has a return value.
#include <stdio.h>
float total ();
main ()
{
float sum;
sum =
total ();
printf (“Sum = %f\n”, sum);
}
float total ()
{
float x, y;
x = 20.0;
y = 10.0;
return (x + y);
}
Output:
Sum = 30.000000
Function with arguments and return value:
When a function has arguments it receives data from the calling function and does some
process and then returns the result to the called function. In this way the main() function will
have control over the function.
Example:
/* program to find the sum of first N natural numbers */
#include <stdio.h>
int sum (int x); /* function
prototype*/ void main ()
{
int n;
printf (“Enter the limit: ”);
scanf (“%d”, &n);
printf (“sum of first %d natural numbers is: %d”, n, sum(n));
}
int sum(int x)
{
int i, result = 0
for (i=1; i <= x; i++)
result += i;
return (result);
}
Output:
The main() is the calling function which calls the function sum(). The function sum() receives
a single argument. Note that the called function (i.e., sum ()) receives its data from the calling
function (i.e., main()). The return statement is employed in this function to return the sum of
the n natural numbers entered from the standard input device and the result is displayed from
the main() function to the standard output device. Note that int is used before the function name
sum() instead of void since it returns the value of type int to the called function.
Nested Functions:
We have seen programs using functions called only from the main() function. But there are
situations, where functions other than main() can call any other function(s) used in the
program. This process is referred as nested functions.
Example:
#include <stdio.h>
void func1();
void func2();
void main()
{
printf (“\n Inside main function”);
func1();
printf (“\n Again inside main function”);
}
void func1()
{
printf (“\n Inside function
1”); func2();
printf (“\n Again inside function 1”);
}
void func2()
{
printf (“\n Inside function 2”);
}
Output:
Inside main function
Inside function 1
Inside function 2
Again inside
function 1
Again inside main function
Uses two functions func1() and func2() other than the main() function. The main() function
calls the function func1() and the function func1() calls the function func2().
Position Type
Local Variables
🞂 Variables that are declared within the function block and can be used only within the
function is called local variables.
🞂 Local scope or block scope
◦ A local scope or block is collective program statements put in and declared within a
function or block (a specific region enclosed with curly braces) and variables lying
inside such blocks are termed as local variables.
◦ All these locally scoped statements are written and enclosed within left ({) and right
braces (}) curly braces.
◦ There's a provision for nested blocks also in C which means there can be a block or a
function within another block or function.
◦ So it can be said that variable(s) that are declared within a block can be accessed within that
specific block and all other inner blocks of that block, but those variables cannot be
accessed outside the block.
#include
<stdio.h> int
main ()
{
/* local variable definition and
initialization */ int x,y,z;
/* actual
initialization */ x =
20;
y = 30;
z = x + y;
printf("value of x = %d,y = %d and z = %d\n", x, y,
z); return 0;
}
Global variables
🞂 Variables that are declared outside of a function block and can be accessed inside the
function is called global variables.
🞂 Global scope
◦ Global variables are defined outside a function or any specific block, in most of the case,
on the top of the C program.
◦ These variables hold their values all through the end of the program and are accessible
within any of the functions defined in your program.
◦ Any function can access variables defined within the global scope, i.e., its availability
stays for the entire program after being declared.
include <stdio.h>
/* global variable
definition */ int z;
int main ()
{
/* local variable definition and
initialization */ int x,y;
/* actual
initialization */ x =
20;
y = 30;
z = x + y;
printf ("value of x = %d, y = %d and z = %d\n", x, y,
z); return 0;
}
🞂 A program can have same name for local and global variables but the value of
local variable inside a function will take preference. Here is an example −
#include <stdio.h>
/* global variable
declaration */ int g = 20;
int main ()
{ /* local variable
declaration */ int g = 10;
printf ("value of g
= %d\n", g); return 0;
}
When the above code is compiled and executed, it produces the following result −
value of g = 10
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take
precedence over global variables. Following is an example –
#include <stdio.h>
Int a=20; /* global variable
declaration */ int main ()
{ /* local variable declaration in main
function */ int a = 10; b=20;c=0;
printf ("value of a in main()
= %d\n", a); c = sum( a, b);
printf ("value of c in main()
= %d\n", c); return 0;
}
/* function to add two
integers */ int sum(int a, int
b)
{
printf ("value of a in sum()
= %d\n", a); printf ("value of b in
sum() = %d\n", b); return a + b;
When the above code is compiled and executed, it produces the following
result − value of a in main() = 10
value of a in
sum() = 10 value
of b in sum() = 20
value of c in
main() = 30
🞂 When a local variable is defined, it is not initialized by the system, you must
initialize it yourself. Global variables are initialized automatically by the system
when you define them as follows −
int 0
char '\0'
float 0
double 0
pointer NULL
It is a good programming practice to initialize variables properly, otherwise your
program may produce unexpected results, because uninitialized variables will take
some garbage value already available at their memory location.
3.9 Storage Classes
Storage classes are used to define the scope (visibility) and life-time of variables and/or
functions. Every variable and function in C has two attributes: type and storage class. There are
four storage classes:
· auto
· static
· extern or global and
· register
The auto storage class:
Variables declared within function bodies are automatic by default. If a compound statement
starts with variable declarations, then these variables can be acted on within the scope of the
enclosing compound statement. A compound statement with declarations is called a block to
distinguish it from one that does not begin with declarations.
Declarations of variables within blocks are implicitly of storage class automatic. The key- word
auto can be used to explicitly specify the storage class. An example is:
auto int a, b, c;
auto float f;
Because the storage class is auto by default, the key-word auto is seldom used.
When a block is entered, the system allocates memory for the automatic variables. With in that
block, these variables are defined and are considered “local” to the block. When the block is
exited, the system releases the memory that was set aside for the automatic variables. Thus, the
values of these variables are lost. If the block is reentered, the system once again allocates
memory, but previous values are unknown. The body of a function.
definition constitutes a block if it contains declarations. If it does, then each invocation of the
function set up a new environment.
One method of transmitting information across blocks and functions is to use external
variables. When a variable is declared outside a function, storage is permanently assigned to it,
and its storage class is extern. Such a variable is considered to be global to all functions
declared after it, and upon exit from the block or function, the external variable remains in
existence. The following program illustrates this:
# include <stdio.h>
int a = 1, b = 2, c = 3; /* global variable*/
int fun (void); /* function
prototype*/ int main (void)
{
printf (“%3d\n”, fun ()); /* 12 is printed */
printf (“%3d%3d%3d\n”, a, b, c); /* 4 2 3 is
printed */}
int fun (void)
{
int b, c;
a = b = c = 4; /* b and c are local */
return (a + b + c); /* global b, c are masked*/
}
Note that we could have written:
extern int a = 1, b = 2, c = 3;
The extern variables cannot be initialised in other functions whereas we can use for assignment.
This use of extern will cause some traditional C compilers to complain. In ANSI C, this use is
allowed but not required. Variables defined outside a function have external storage class, even
if the keyword extern is not used. Such variables cannot have auto or register storage class.
The keyword extern is used to tell the compiler to “look for it else where, either in this file or
in some other file”. Let us rewrite the last program to illustrate a typical use of the keyword
extern:
In file file1.c
#include <stdio.h>
# include “file2.c”
int a=1, b=2, c=3; /* external
variable */ int fun (void)
int main (void)
{
printf (“The values of a, b and c are: %3d%3d%3d\n”, a, b, c);
printf (“The sum of a + b + c is: %3d\n”, fun ());
printf (“The values of a, b and c are: %3d%3d%3d\n”, a, b, c);
return 0;
}
In file file2.c
int fun (void)
{
extern int a; /* look for it
elsewhere */ int b, c;
a = b = c = 4;
return (a + b +
c);
}
Output:
The values of a, b and c are: 1 2 3 The sum of a + b + c is: 12
The values of a, b and c are: 4 2 3
The two files can be compiled separately. The use of extern in the second file tells the compiler
that the variable a will be defined elsewhere, either in this file or in some other. The ability to
compile files separately is important when writing large programs.
External variables never disappear. Because they exist throughout the execution life of the
program, they can be used to transmit values across functions. They may, however, be hidden if
the identifier is redefined.
ormation can be passed into a function two ways; by use of external variable and by use of the
parameter passing mechanism. The use of the parameter mechanism is the best preferred
method. Don't overuse ‘extern’ variables. It is usually better to pass lots of arguments to
functions rather than to rely on hidden variables being passed (since you end up with clearer
code and reusuable functions).
Examples:
1) register int x;
2) register int counter;
The declaration register i; is equivalent to register int i;
extern RAM Zero Global Till the end of the main program
Maybe declared anywhere in the
program
static RAM Zero Local Till the end of the main program,
Retains value between multiple
functions call
Recursion in C language is basically the process that describes the action when a function calls
a copy of itself in order to work on a smaller problem. Recursive functions are the function that
calls themselves and this type of function calls are known as recursive calls. The recursion in C
generally involves various numbers of recursive calls. It is considered to be very important to
impose a termination condition of recursion. Recursion code in the C language is generally
shorter than the iterative code and it is known to be difficult to understand.
ursion cannot be applied to all the problem, but Recursion in C language is very useful for the
tasks that can be generally be defined in terms of similar subtasks but it cannot be applied to all
the problems. For instance: recursion in C can be applied to sorting, searching, and traversal
problems.
As function call is always overhead, iterative solutions are more efficient than recursion. Any of
the problems that can generally be solved recursively; it can be also solved iteratively. Apart
from these facts, there are some problems that are best suited to only be solved by the recursion
for instance: tower of Hanoi, factorial finding, Fibonacci series, etc.
The base case is the case at which the function doesn’t recur in C and there are instances
where the function keeps calling itself in order to perform a subtask and that is known as the
recursive case.
Exampl
e:
void
main(
)
{
main();
}
Indirect recursion: If a function calls another function and if that function calls it self. Then
it is indirect recursion.
Exampl
e:
Void
main()
{
--
--
Print();
--
--
}
Void Print()
{
--
--
Print();--
} Check:Output:0 12 3 4567 89
Example:
#include <stdio.h>
void printnum ( int begin )
{
printf( "%d", begin );
if ( begin < 9 ) /* The base case is when begin is no longer */
{ /* less than 9 */
printnum ( begin + 1 );
}
/* display begin again after we've already printed everything from 1 to 9
* and from 9 to begin + 1
*/ printf( "%d", begin );
}
int main()
{
printnum
(0);
getchar()
;
}
Pointer Introduction:-
Advantages of Pointers:-
1. A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
Definition :-
A variable that holds a physical memory address is called a pointer variable or Pointer
Declaration :Datatype * Variable-name;
Dangling Pointers in C
The most common bugs related to pointers and memory management is dangling/wild pointers.
Sometimes the programmer fails to initialize the pointer with a valid address, then this type of
initialized pointer is known as a dangling pointer in C.
Dangling pointer occurs at the time of the object destruction when the object is deleted or de-
allocated from memory without modifying the value of the pointer. In this case, the pointer is
pointing to the memory, which is de-allocated. The dangling pointer can point to the memory,
which contains either the program code or the code of the operating system. If we assign the value
to this pointer, then it overwrites the value of the program code or operating system instructions;
in such cases, the program will show the undesirable result or may even crash. If the memory is
re-allocated to some other process, then we dereference the dangling pointer will cause the
segmentation faults.
Let's understand the dangling pointer through some C programs. Using
free() function to de-allocate the memory.
1. #include <stdio.h>
2. int main()
3. {
5. int a=560;
6. ptr=&a;
7. free(ptr);
8. return 0;
9. }
In the above code, we have created two variables, i.e., *ptr and a where 'ptr' is a pointer and 'a' is a
integer variable. The *ptr is a pointer variable which is created with the help of malloc()
function. As we know that malloc() function returns void, so we use int * to convert void pointer into
int pointer.
The statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4 bytes shown
in the below image:
The statement free(ptr) de-allocates the memory as shown in the below image with a cross sign,
and 'ptr' pointer becomes dangling as it is pointing to the de-allocated memory.
If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted memory. Therefore,
we can say that ptr is not a dangling pointer, as shown in the below image:
Variable goes out of the scope
When the variable goes out of the scope then the pointer pointing to the variable becomes a
dangling pointer.
· A pointer is a variable that contains an address which is a location ofanother
variable in memory.
The operator & returns the memory address of variable on which it isoperated, this is
called Referencing.
The * operator is called an indirection operator or dereferencing operatorwhich is used to
display the contents of the Pointer Variable.
Pointers to pointers:-
A pointer to a pointer is a form of multiple indirection, or a chain ofpointers.
Normally, a pointer contains the address of a variable.
When we define a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the location that containsthe actual value as shown below.
· A variable that is a pointer to a pointer must be declared assuch.
· This is done by placing an additional asterisk in front of itsname. For
example, the following declaration declares a pointer to a pointer of type
int –
int **var;
Arrays:-
An array is defined as the collection of similar type of dataitems stored at contiguous
memory locations.
Arrays are the derived data type in C programming language which can store the
primitive type of data suchas int, char, double, float, etc.
It also has the capability to store the collection of deriveddata types, such as
pointers, structure, etc.
The array is the simplest data structure where each dataelement can be randomly
accessed by using its index number.
Pointer Arithmetic in C:-
Pointer Arithmetic in C
o Increment
o Decrement
o Addition
o Subtraction
o Comparison
Decrementing Pointer in C
C Pointer Addition
We can add a value to the pointer variable. The formula ofadding value to pointer is given
below:
new_address= current_address + (number * size_of(data type))
Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. Subtracting any
number from a pointer willgive an address. The formula of subtracting value from the
pointer variable is given below:
new_address= current_address - (number * size_of(data type))
memory is allocated at
compiletime. memory is allocated at run
time.
Now let's have a quick look at the methods used for dynamic memoryallocation.
Array of Pointers:-
In computer programming, an array of pointers is an indexed set of variables in which the
variables are pointers (a referenceto a location in memory).
Pointers are an important tool in computer science forcreating, using, and
destroying all types of data structures.
An array of pointers is useful for the same reason that allarrays are useful: it allows
you to numerically index a large set of variables.
Below is an array of pointers in C that sets each pointer inone array to point to an
integer in another and then print the values of the integers by dereferencing the
pointers.
When an array is declared, elements of array are stored in contiguous locations. The
address of the first element of an array is called its base address.
The name of the array is called its base address.i.e., a and k& a[20] are equal
Now both a and a[0] points to location 2000. If we declare p as an integer pointer, then we can
make the pointer P to point to the array a by followingassignment.
P = a;
We can access every value of array a by moving P from one element to another.i.e., P
points to 0th element
P+1 points to 1st element
P+2 points to 2nd element
P+3 points to 3rd element P
+4 points to 4th element
Let's understand the dangling pointer through some C programs. Using
free() function to de-allocate the memory.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr=(int *)malloc(sizeof(int));
5. int a=560;
6. ptr=&a;
7. free(ptr);
8. return 0;
9. }
In the above code, we have created two variables, i.e., *ptr and a where 'ptr' is a pointer and 'a' is
a integer variable. The *ptr is a pointer variable which is created with the help of
malloc() function. As we know that malloc() function returns void, so we use int * to convert void
pointer into int pointer.
e statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4 bytes shown
in the below image:
The statement free(ptr) de-allocates the memory as shown in the below image with a cross sign,
and 'ptr' pointer becomes dangling as it is pointing to the de-allocated memory.
If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted memory.
Therefore, we can say that ptr is not a dangling pointer, as shown in the below image:
When the variable goes out of the scope then the pointer pointing to the variable becomes a
dangling pointer.
The arguments passed from command line are called command line arguments. These
arguments are handled by main() function.
To support command line argument, you need to change the structure of main() function as given
below.
Example
Let's see the example of command line arguments where we are passing one argument with file
name.
#include <stdio.h>
else{
Output:
Programnameis:program First
Output:
Programnameis:program
Firstargumentis:hello
C language provides facilities to allocate memory to variables during the execution time and also to
release memory when no longer required. This is called dynamic memory allocation.
In C language there are four functions used with dynamic memory management. – malloc(), calloc()
and realloc() for allocation and free() to return memory. These functions are defined in the header file
<stdlib.h>.
A conceptual view of memory is shown below though the actual implementations may vary slightly.
main() must be in memory all the times. Called functions may be present in the memory only
when active or at all times (depending on the implementation)
Local variables for a function available only when the function is active and are managed from the
stack.
Dynamic memory allocation is done using the heap.
malloc()
· Allocates a block of memory as specified in its parameters.
· Returns a pointer to the first byte of the allocated memory.
· The allocated memory is not initialized (contains garbage).
Prototype:
void * malloc(size_t size);
Usage:
ptr = malloc (sizeof(data_type));
It is better to make the pointer to be of a specific type using typecasting as below: ptr =
E.g.:
int *p;
p = (int *) malloc(sizeof(int)); // allocates two bytes of memory to store an integer
calloc()
Prototype:
void *calloc(size_t element_count, size_t element_size);
· returns a pointer to size bytes of memory block else returns NULL.
· size is usually specified using sizeof() function.
Usage:
ptr = calloc (integer value, sizeof(data_type));
It is better to make the pointer to be of a specific type using typecasting as below: ptr =
E.g.:
int *p;
p = (int *) calloc(200, sizeof(int)); // allocates memory for 200 integers
realloc()
· changes the size of the previously allocated memory block.
· Can be highly inefficient and hence should be used carefully.
· Prototype:
void *realloc(void *ptr, size_t newsize);
E.g.:
int *p;
p = (int *) malloc(sizeof(int)); //initially only 2 bytes allocated
p = (int *) realloc(p, 15 * sizeof(int)); // reallocates memory for 15 integers
free()
· When memory allocated by malloc(), calloc() or realloc() are no longer needed, it can be freed.
· Prototype:
void free(void *ptr);
E.g.:
free(ptr);
Note: Any pointer to the freed memory is not destroyed and hence it is better to set
it to NULL and avoid errors.
Programming example:
//Write a program that uses a table of integers whose size will be specified interactively at run
time.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h> void
main()
{
int *p, *table; int size;
clrscr();
printf("\nWhat is the size of the table");
scanf("%d",&size);
table = (int *)malloc(size * size(int)); // allocates memory for specified numbers using malloc
printf("Enter %d numbers", size); for(p=table;
p<table + size; p++)
scanf("%d",p);
for(p=table; p<table + size; p++)
printf("%d is stored at address %u",*p, p); getch();
}
//Same program using calloc function
#include<stdio.h>
#include<stdlib.h>
#include<conio.h> void
main()
{
int *p, *table; int size;
clrscr();
printf("\nWhat is the size of the table");
scanf("%d",&size);
table = (int *)calloc(size, size(int)); // allocates memory for specified numbers using calloc
printf("Enter %d numbers", size); for(p=table;
p<table + size; p++)
scanf("%d",p);
for(p=table; p<table + size; p++)
printf("%d is stored at address %u",*p, p); getch();
}
What is a structure?
A structure is a user defined data type in C and C++ language. It creates a data type that can be used
to group items of possibly different types into a single type.
Syntax: struct<structure_name>
{
data_type variable1;
data_type variable2;
data_type variable3;
----
----
};
Example:struct address
{
char name[50]; char city[50]; char state[20]; int pin;
};
· How to declare structure variables?
A structure variable can either be declared with structure declaration or as a separate declaration like basic
types.
// Type-1Structure variable declaration.
struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'
void main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}How to initialize structure members?
Structure members cannot be initialized with declaration.
For example, the following C program used to show WRONG initialization
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here int y =
0; // COMPILER ERROR: cannot initialize members here
};
The reason for above error is simple, when a datatype is declared; no memory is allocated for it. Memory is
allocated only when variables are created.
struct Point
{
int x, y;
};
void main()
{
struct Point p1 = {0, 1};
}
void main()
{
structTESTt1 = {0, 1};
#include<stdio.h> #include<conio.h>
void main()
{
struct Point arr[10]; // Create an array of structures
· Limitations of C Structures
In C language, Structures provide a method for packing together data of different types. A Structure is a
helpful tool to handle a group of logically related data items. However, C structures have some limitations.
a. The C structure does not allow the struct data type to be treated like built-in data types.We cannot use
operators like +,- etc. on Structure variables.
b. No Data Hiding:C Structures do not permit data hiding. Structure members can be accessed by
any function, anywhere in the scope of the Structure.
c. Functions inside Structure: C structures do not permit functions inside Structure.
d. Static Members: C Structures cannot have static members inside their body.
e. Access Modifiers: C Programming language do not support access modifiers. So they cannot be used
95
in C Structures.
1. Array elements are accessed using the Subscript variable, Similarly Structure members are
accessed using dot [.] operator.
2. (.) is called as “Structure member Operator”.
3. Use this Operator in between “Structure name” & “member name”
Example:
#include<stdio.h>
#include<conio.h>
structVehicle
{
intwheels;
charvname[20];
charcolor[10];
}v1={4,"Maruti800","White"};
voidmain()
{
printf("VehicleNoofWheels:%d",v1.wheels);
printf("Vehicle Name : %s",v1.vname);
printf("Vehicle Color
: %s",v1.color);getch();
}
structEmployee
{
charename[20];
intssn;floatsalary;str
uctdate
{
intdate;intmonth;int
year;
}doj;
}emp1;
Voidmain()
{
printf("\nEmployeeName:%s",emp.ename);
printf("\nEmployee SSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", \
emp.doj.date,emp.doj.month,emp.doj.year);
getch();
}
Pointer to structure : Pointer which stores address of structure is called as “Pointer to Structure“.
Explanation :
1. sptr is pointer to structure address.
2. -> and (*). both represent the same.
3. These operators are used to access data member of structure by using structure’s pointer.
Program :
#include<stdio.h>
struct team {
char *name;
int members;
char captain[20];
}t1={"India",11,"Dhoni"} ,*sptr=&t1;
int main()
{
printf("\nTeam : %s",(*sptr).name);
printf("\nMemebers:%d",sptr->members);
98
printf("\nCaptain : %s",(*sptr).captain);
return0;
}
Passing Structure to Function in C Programming
1. Structure can be passed to function as a Parameter.
2. function can also Structure as return type.
3. Structure can be passed as follow
Example:
#include<stdio.h>
#include<conio.h>
//
struct Example
{
int num1;
int num2;
}s[3];
//
void accept(struct Example*sptr)
{
printf("\nEnter num1: ");
scanf("%d",&sptr->num1);
printf("\nEnter num2 :");
scanf("%d",&sptr->num2);
}
//
void print(struct Example*sptr)
{
printf("\nNum1:%d",sptr->num1);
printf("\nNum2:%d",sptr->num2);
}
//
void main()
{
int i;
clrscr();
for(i=0;i<3;i++)
accept(&s[i]);
for(i=0;i<3;i++) print(&s[i]);
getch();
99
}
Example:
#include<stdio.h>
#include<conio.h>
struct Employee
{
int ssn;
char ename[20];
char dept[20];
}emp[3];
//
void main()
{
inti,sum;
Unions
· A union is declared and used in the same ways that a structure.
· Unions are defined and declared in the same fashion as structures.
100
· In unions, all the members share the space which is according to the space requirement of the largest
member.
· The union can hold only one value at a time.
· A union can be initialized on its declaration.
· Because only one member can be used at a time, only one can be initialized.
· To avoid confusion, only the first member of the union can be initialized.
Defining of Union
· A union has to defined, before it can be used.
· The syntax of defining a structure is union
<union_name>
{
<data_type> <variable_name>;
<data_type> <variable_name>;
………….
<data_type> <variable_name>;
};
Example
To define a simple union of a char variable and an integer variable union
shared
{ char c;
int i;
};
This union, shared, can be used to create instances of a union that can hold either a character
value(c) or an integer value( i ).
Union Data Type
· A union is a user defined data type like structure.
· The union groups logically related variables into a single unit.
· The union data type allocates the space equal to space needed to hold the largest data member of
union.
· The union allows different types of variable to share same space in memory.
· There is no other difference between structure and union than internal difference.
· The method to declare, use and access the union is same as structure.
Example
union shared
{ char c; int i;
};
Example
#include<stdio.h>
union job
{ char name[32]; float salary;
int worker_no;
} u;
struct job1
{ char name[32]; float salary;
int worker_no;
} s;
void main( )
{
printf("size of union = %d", sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
}
output
size of union = 32
size of structure = 40
Difference between Structure and Union
Structure Union
1. It can be defined using struct keyword. It can be defined using a union keyword.
2. Every member within structure is assigned a In union, a memory location is shared by all the data
unique memory location. members.
3. Changing the value of one data member will not Changing the value of one data member will change the
affect other data members in structure. value of other data members in union.
4. It allows initializing several members at once. It allows initializing only the first member of union.
5. The total size of the structure is the sum of the size The total size of the union is the size of the largest data
of every data member. member.
6. It is used for storing various data types. It is used for storing one of the many data types that are
available.
7. It reserves space for each and every member It reserves space for a member having the highest size.
separately. 102
8. Any member can be retrieve at a time. Only one member can be retrieve at a time.
9. It allows dynamic array as member. It does not allows dynamic array as member.
Example.
unionshared structshared
{charc; int {charc; int
i; i;
}; };
structA BC unionABC
{ intx; { intx;
unionsharedy; structsharedy;
}; };
103