Programming in C by Kute T. B.
Programming in C by Kute T. B.
Engineering Group
Programming in C
T. B. Kute
tbkute@gmail.com
Programming in C
(Sub Code: 9017)
Computer Engineering Group, Semester: II
First Edition
( March 2009 )
T. B. Kute
(B. E. Computer)
Lecturer in Information Technology,
K. K. Wagh Polytechnic,
Nashik, India, 422003.
Windows of Knowledge are Wide and Open
Semester : Second
Rationale:
‘C’ is the most widely used computer language, which is being taught as a
core subject. C is general-purpose structural language that is powerful, efficient
and compact, which combines features of high-level language and low-level
language. It is closer to Man and Machine both. Due to this inherent flexibility
and tolerance it is suitable for different development environments .Due to
these powerful features C has not lost its importance and popularity in recently
developed and advanced software industry C can also be used for system level
programming, C is still considered as first priority programming language.
This subject covers from the basic concept of C to pointers in C. This
subject will act as “programming concept developer” for students. It will also
act as “Backbone” for subjects like OOPS, VB, Windows Programming, JAVA,
OOMD, etc.
Objectives:
The students will be able to
• Describe the concepts of constants, variables, data types and operators.
• Develop programs using input and output operations.
• Write programs using different looping and branching statements.
• Write programs based on arrays and strings handling functions.
• Write programs using user-defined functions, structures and union.
• Write programs using C pointers.
Chap. Contents Hours Marks
01 Basics of C 10 16
1.1 History of C, where C stands
1.2 C character set, tokens, constants, variables,
keywords
1.3 C operators (arithmetic, Logical, assignment,
relational, increment and decrement,
conditional, bit wise, special, operator
precedence), C expressions data types
1.4 Formatted input, formatted output.
02 Decision Making and Branching 12 24
2.1 Decision making and branching
if statement (if, if-else, else-if ladder, nested
if-else) Switch case statement, break statement.
2.2 Decision making and looping while, do, do-
while statements for loop, continue statement
03 Arrays and Strings 14 12
3.1 Arrays
Declaration and initialization of one
dimensional, two dimensional and character
arrays, accessing array elements
3.2 Declaration and initialization of string
variables, string handling functions from standard
library (strlen(), strcpy(), strcat(), strcmp()).
04 Functions and Structures 14 12
4.1 Functions
Need of functions, scope and lifetime of
variables, defining functions, function call (call
by value, call by reference), return values,
storage classes. category of function( No
argument No return value, No argument with
return value, argument with return value),
recursion
4.2 Structures
Defining structure, declaring and accessing
structure members, initialization of structure,
arrays of structure.
05 Pointers 14 16
5.1 Understanding pointers, declaring and
accessing pointers, Pointers arithmetic, pointers
and arrays
Total 64 80
Chapter 01 Basics of C
Chapter 01
Basics of ‘C’
Lectures allotted: 10
Marks Given: 16
Contents:
Compiler
It is system software, collection of intelligence program which converts
higher level language program into machine code (Binary code). Compiler
checks for syntactical errors in the program.
Compiler of ‘C’ is designed by Dennis Ritchie at AT&T Bell laboratory
in 1974, which generally used for system programming. The name of ‘C’
language was derived from ‘BCPL’ (Basic Combine Programming Language).
Programming Languages
Language Year Originator Purpose
FORTRAN 1954-57 John Backus, IBM Numerical processing
ALGOL 60 1958-60 Committee Numerical processing
COBOL 1959-60 Committee Business Data Processing
APL 1956-60 K. Iverson Array Processing
LISP 1956-62 John McCarthy Symbolic Computation
SNOBOL 1962-66 R. Griswold String processing
PL/I 1963-64 IBM General purpose
SIMULA 67 1967 O. J. Dahl General purpose
ALGOL 68 1963-68 Committee General purpose
BLISS 1971 Wulf et. al. System Programming
PASCAL 1971 Niklaus Wirth General and Education
C 1974 Dennis Ritchie System Programming
MESA 1974 Xerox PARC System Programming
CONCURRENT 1975 P. Brinch Concurrent Programming
CLU 1974-77 B. Liskov Abstraction Methodology
EUCLID 1977 Committee Verifiable System Programs
GYPSY 1977 Good et. al. Verifiable System Programs
PLZ 1977 Zilog inc. System Programming
MODULA 1977 Niklaus Wirth System Programming
ADA 1979 J. Ichbiah General and Embedded
C++ 1983 Bjarne Stroustrup Object Oriented Prog.
JAVA 1991 James Gosling OOP + Embedded + N/W
Computer Languages
Imperative Declarative
Procedural Logical
e.g. C e.g. PROLOG
Object Based
e.g. ADA Functional
Object Oriented e.g. LISP
e.g. C++, JAVA
Database
Block Structured e.g. SQL
e.g. PASCAL
Start / Stop
General Processing
Decision
Input / Output
Connector
Function / Subroutine
Start
Input radius in
cm.
Calculate area =
3.14 * (radius * radius)
Display area
Stop
Start
Calculate, per =
(m1+m2+m3+m4+m5) / 5
Yes
Display
per >=75 “Distinction”
No
Yes
Display
per >=60 “First Class”
No
Yes
Display “Second
per >=50 Class”
No
Yes
Display
per >=40 “Pass Class”
No
Display
“Fail”
Stop
[Ref. 2a]
Forming a C program
Alphabets, Digits,
Special Symbols
Program
Constants,
Variables,
And Instructions
Keywords
Compiler
Assembly Language
Assembler Code
Loader
Executable Code
Primary Constants
Integer Constant:
1. Integer constant must have at least one digit.
2. They must not have a decimal point.
3. They can be positive or negative.
4. If there is no any sign to integer it is assume to be positive.
5. No comma or blank spaces are allowed within the integer constant.
e.g. 426, +756,-588 etc.
Real Constant:
1. These are generally called as floating point constant. They can be
written two forms. That is, fractional form & exponential form.
2. Real constant can be positive or negative.
Character Constants:
1. The character constant is a single alphabet or a single digit or a single
special symbol enclosed within the single quotation marks.
2. Maximum length of a character is one character.
e.g. ‘f’, ‘h’, ‘=’, ‘8’ etc.
Variables
[Asked in W’07, S’08, W’08]
It is an entity that may vary during the program is executing. Variable
is the name given to the location of the memory. This location can contain
integer, real or character constants.
Keywords
[Asked in S’08]
Keyword is the word who’s meaning as already being given to the ‘C’
compiler. The keywords can not be given as variable name in ‘C’. These are
also called as reserve words. The C supports 32 different keywords listed
below:
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
while volatile near for asm
[Ref. 1a]
Operators
Operators are the special symbol use to perform special operation (for
example, arithmetic & logical) on operands. Operands are the variables,
constants or expressions on which operators perform operation.
As per the number of operands required by the operator, it is classified
in three categories:
1. Unary operators
2. Binary operators
3. Ternary operators
These operators require one, two and three operands respectively for
performing their operation.
Relational Operators
[Asked in S’W’08]
These operators are used to check the relation between the operands.
Logical Operators
[Asked in S’07’08, W’08]
These operators are used to combine two conditions.
Conditional Operator
[Asked in W’08]
The only ternary operator (operator having three operands) is defined
in ‘C’ called as conditional operator. The character pair ? : is termed as
conditional operator. This is used to construct the conditional expression of
the following form:
x = 45;
y = 22;
(y>25) ? x = y : x = 50;
Bitwise operators
[Asked in S’W’07]
Operator Type Meaning
& Bitwise AND
| Binary Bitwise OR
^ Bitwise EX-OR
~ Unary Bitwise NOT
<< Left shift
Binary
>> Right shift
Special Operators
Separators
These are the symbols which are used to indicate where groups of
codes are divided and arranged. They are basically used to define the shape
and function of the program code. The most commonly used separator is
semicolon. All these separators are listed below:
Comments
variable = expression;
a = (x + y) * (x + y);
b = (x / y) + c;
x = a * b / c;
[Ref. 2d, 1c]
Precedence and Associativity of operators
When the expression involves more than one operation, then which
operation is to be performed first is decided by the precedence of that
operator. Highest precedence operation is solved first. Each operator of ‘C’
has precedence associated with it. The operators with the same precedence
are evaluated according to there associativity. That is, the expression is
evaluated either from left to right or right to left. The precedence and
associativity of all these operators is given in the following table.
[Ref. 2e]
Hierarchy of operations
i = 5 * 6 – 8 + 9 – (43 + 2) /5 – 5;
i = 30 – 8 + 9 – 45/5 – 5;
i = 30 – 8 + 9 – 9 – 5;
i = 22 + 0 – 5;
i = 17;
Data types
[Asked in S’W’07, S’08]
int a; /* General declaration */
int a = 10; /* Valued Declaration */
float b = 12.6;
float b;
char c;
char c = ‘y’;
[Ref. 1d]
Maximum values of Data Types
-3.4e38 to 3.4e38
• char requires 1 byte to store.
A….Z and a….z also special symbols
• long int requires 4 bytes to store.
-2147483648 to 2147483647.
• double requires 8 bytes to store.
-1.7e308 to 1.7e308
• long double requires 10 bytes to store.
-1.7e4932 to 1.7e4932
[Ref. 1e]
Structure of a C program
Preprocessor Directives
main( )
{
Local variables
Declaration
Actual
Processing Processing Statements
starts here
} // End of main( )
1. printf
[Asked in S’08]
This formatted output function statement defined in stdio.h file used to
print the string or the values of variables on the output screen.
Syntax:
printf(“<format string>”, <variables-list>);
Here, the format string will contain the string and the format specifiers
or format codes to display the values of variables in the sequence of
format specifiers.
e.g.
printf(“Welcome to C”);
Welcome to C
In order to print the values of the variables printf can also be used as:
Here the %d is called as integer format specifier and used to print the
integer value of variable on the screen. Such 16 different format
specifiers / format codes are used in printf as well as scanf. These are
listed below:
[Ref. 1h]
Format Specifiers / format codes
[Asked in S’W’08]
%c Character format specifier.
%d Decimal integer format specifier.
%e Scientific notation for floating point format specifier.
%E Scientific notation for floating point format specifier.
%f Floating-point format specifier.
%g Uses %f or %e, whichever result is shorter.
%G Uses %f or %E, whichever result is shorter.
%i Integer format specifier (same as %d).
%n Records the number of characters written so far.
%o Unsigned octal format specifier.
%p Displays the corresponding argument that is a pointer.
%s String format specifier.
%u Unsigned integer format specifier.
%x Unsigned hexadecimal format specifier.
%X Unsigned hexadecimal format specifier.
%% Outputs a percent sign (%).
[Ref. 1i]
Escape Sequences
Character Meaning
\n New line
\t Tab
\b Backspace
\v Vertical tab
\a Audible Alert (Bell)
\r Carriage return
\f Farm Feed
\\ Backslash
\‘ Single Quote
\“ Double Quote
2. scanf
[Asked in S’08]
This formatted input function statement defined in stdio.h file and used
to accept the values of variables from the keyboard.
Syntax:
scanf(“<format string>”, <variables-list>);
Here, the format string will contain the format specifiers or format codes
to accept the values of variables in the sequence of format specifiers.
For example:
int var1;
float var2;
scanf(“%d%f”, &var1, &var2);
This statement will read an integer number and a float number from
keyboard and store these values in var1 and var2 respectively. The scanf
allows all the above format specifiers to use for inputting the values.
[Ref. 1j]
Type casting or Type conversion
will always result in the long type of the data. And the expression,
num2 + x * num1;
will result in float type of the data. This is because, it is the property of
the expression. It is referred as automatic type casting. The type cast
operator - ( ) can be used to convert one data type into another
temporarily. This is referred as manual type casting. Such as:
int x = 10, y = 4;
float result;
result = x / y;
printf(“Division: %f”, result);
Division: 2.000000
But, it is not the accurate answer. So type casting is required. Such as,
result = (float) x / y;
Division: 2.500000
Sample Programs:
Ans : #include<stdio.h>
#include<conio.h>
void main( )
{
float Basic, DA, HRA, GS;
clrscr( );
printf(“Enter the basic salary”);
scanf(“%f”, &basic);
DA = (40/100) * basic;
Ans : #include<stdio.h>
#include<conio.h>
void main( )
{
float centi;
int faren;
printf(“Enter Fahrenheit temp”);
scanf(“%d”, &faren);
centi = (( float) faren -32) * 5 / 9;
printf(“ cent temp = %f”, cent);
getch( );
}
3) The length and breadth of the rectangle & radius of the circle are input
through key board. Write a program to calculate the area, perimeter & the
circumference of the circle.
Ans : #include<stdio.h>
#include<conio.h>
void main( )
{
float l, b, r, area, perim, circumf;
clrscr( );
printf(“Enter length & breadth”, l, b,);
scanf(“%f%f”, &l,&b);
area = l * b;
perim = 2 * (l + b);
printf(“\n area =%f ”, area);
printf(“\n perim = %f ”, perim);
printf(“\n enter radius ”,r);
scanf(“%f ”, &r);
area = 3.14 * r * r;
circumf = 2 * 3.14 * r;
printf(“\n area = %f ”,area);
printf(“\n circumf = %f ”, circumf);
getch( );
}
4) Two numbers are input through keyboard into two locations C & D. Write
a program to interchange the content of C & D.
Ans : #include<stdio.h>
#include<conio.h>
void main( )
{
int a, b, c;
clrscr( );
printf(“a = %d, b = %d ”, a, b);
c = a;
a = b;
b = c;
printf(“\n a = %d, b = %d”, a, b);
getch( );
}
-----------
Review Questions
Summer 2007 Marks
1. State different data types supported by ‘C’ language (W-2007). 2
2. Write a ‘C’ statement for each of the following: 2
i. Relational operator.
ii. Assignment operator.
3. State the use of increment and decrement operator and give its
precedence and Associativity. 4
4. Define the following: 4
i. Expressions
ii. Data types
iii. Bitwise operators
iv. Logical operators
Winter 2007
1. Explain the use of bitwise operator. 2
2. State the use of increment and decrement operators. Also give
difference between i++ and ++i with example. 4
3. What is variable? How to declare it? How variable differs from
constant? 4
Summer 2008
a) What is variable declaration and variable initialization? 2
b) What are the uses of printf( ) and scanf( )? 2
c) List different relational and logical operators. What will be the output of
following program? 4
#include<stdio.h>
void main( )
{
float a = 5, b = 2;
int c;
c = a % b;
printf(“%d”,c);
}
d) State use of %c %d and %f. 4
Write output of following:
#include<stdio.h>
main( )
{
float y = 123.456;
printf(“%f %.3f %.1f \n\n”, y, y, y);
}
e) Define the following: 4
1) Keyword
2) Variable.
3) Data types
4) Constants.
Winter 2008
a) State four relational operators with its meaning. 2
b) State four printf format codes. 2
c) State the arithmetic and logical operators with its meaning. 4
d) Write a program to take marks of five subjects and display the total
and average. 4
e) State four rules of choosing variable’s name. 4
f) What is the output of the following code? 4
void main( )
{
int i = 1, j = -1, k = 0, w, x, y, z;
w = i || j ||k ;
x = i && j && k ;
y = i || j && k ;
z = i && j && k ;
printf(« w=%d x=%d y=%d z=%d »,w,x,y,z) ;
}
Other:
1. Differentiate between unary, binary and ternary operators. 4
2. What is precedence and associativity of operators? 2
3. Explain the use of manual and automatic type casting with suitable.
Example. 4
4. What is comment? Explain its use. 2
Programming Exercises
1. Write a program to input the temperature in Celsius and display its
equivalent Fahrenheit temperature value.
2. The distance between two cities (in km.) is input through the
keyboard. Write a program to convert and print this distance in
meters, feet, inches and centimeters.
3. Write a program to input the radius of the circle in centimeters and
find the area of that circle.
4. Write a program to input the height and base of the right angle
triangle and find the hypotenuse of it using Pythagoras’ Theorem.
5. Input to the program is length and width of rectangle. Find the area
and perimeter of it.
6. Two numbers are input through the keyboard into two locations C and
D. Write a program to interchange the contents of C and D.
----------------
References
1. Programming in ANSI C
by, E Balagurusamy, Tata McGraw Hill, 4th Edition
a. Chapter 3, Page 52
b. Chapter 3, Table 3.6, Page 64
c. Chapter 3, Table 3.8, Page 73
d. Chapter 3, Table 2.7, 2.8, Page 32
e. Chapter 1, Fig. 1.3, 1.9, Page 6, 13
f. Chapter 1, Topic 1.3, Page 3
g. Chapter 2, Topic 2.10, Page 38
h. Chapter 4, Table 1.4, Page 104
i. Chapter 2, Table 2.5, Page 29
j. Chapter 3, Topic 3.14, Page 68
2. Let us C
By, Yashwant Kanetkar, BPB Publications, 7th Edition
a. Chapter 1, Fig. 1.1, Page: 5
b. Chapter 1, Page: 5
c. Chapter 1, Fig. 1.19, Page: 35
d. Appendix A, Page 707
e. Chapter 1, Example 1.1, Page 33
-----------
Chapter 02
Decision Making and Branching
Lectures allotted: 12
Marks Given: 24
Contents:
a) The if statement
b) The if - else statement
c) Nested if – else
d) The else – if ladder
[Ref. 1a, 2a]
The if Statement
if (condition)
{
//execute these statements;
}
Here, the keyword ‘if’ tells the compiler that what follows, is a decision
control instruction. The condition following the keyword if is always enclosed
within a pair of parentheses. If the condition is true, then the statements in
the parenthesis are executed. It the condition is not true then the statement
is not executed instead the program skips this part. The condition in C is
evaluated using C’s relational operators as well as logical operators. These
operators help us to build expression, which are either true or false.
For example:
X == Y X is equal to Y
X != Y X is not equal to Y
X < Y X is less than Y
X > Y X is greater than Y
X <= Y X is less than or equal to Y
X >= Y X is greater than or equal to Y
Demonstration of if statement:
/* Example 2.1 */
#include<stdio.h>
main( )
{
int num;
printf(“Enter a number less than 10 :”);
scanf(“%d”, &num);
if(num < = 10)
true condition
false
Statement-1 Statement-2
Statement-3
if (i > 1 || j!=5)
{
printf("i = %d “, i );
}
[Ref. 2b]
Multiple Statements within if
main( )
{
int bonus, cy, yoj, yos;
printf(“Enter current year and year of joining : ”);
scanf(“%d%d”,&cy,&yoj);
yos = cy - yoj;
if(yos > 3)
{
bonus = 2500;
printf(“Bonus = Rs. %d”, bonus);
}
}
In this program, value of cy and yoj are taken from user i.e. 2006 and
2001. Value of yos will become 5. The condition within ‘if’ will check whether
the value of yos is greater than 3 or not. Here, condition will become true
and the statements followed by if are executed.
if(condition)
{
//statements1
}
else
{
//statements2
}
if(bs <1500)
{
hra = bs * 10/100;
da = bs * 90/100;
}
else
{
hra = 500;
da = bs * 98/100;
}
gs = bs+hra+da;
printf(“gross salary = Rs. %f”, gs);
}
true condition
false
Statement-1 Statement-2
Statement-3
Note:
1. Statements inside the ‘if’s curly braces are called as ‘if block’ and
statements for else’s curly braces are called as ‘else block’.
2. There is no necessity to have an else for if but, each else must match
an if statement else there will be a compiler error. The error will be
‘Misplaced else’.
3. If there is only one statement inside ‘if’ as well as ‘else’ block, we can
eliminate the curly braces.
Syntax:
if(condition)
{
//statements1
if (condition)
{
//statements2
}
else
{
//statements3
}
}
else
//statements4
Here, the inner condition executed only when the outer condition of ‘if’
is true. This hierarchy of nesting of ‘if’ can be extended in deep with any
number of ‘if-else’ statements.
false
condition1
true
Statements-4
Statements-1
false
condition2
true
Statements-3
Statements-2
/* Example 2.4 */
#include<stdio.h>
main( )
{
int y;
printf(“Enter year : “);
scanf(“%d”, &y);
if(y > 2000)
{
printf(“\n Number is greater than 2000”);
if(y % 4 == 0)
{
printf(“\n This is leap year”);
}
else
printf(“\n This is not leap year”);
}
else
{
printf(“\n Number is less than 2000);
if(y % 4 ==0)
{
printf(“\n This is leap year”);
}
else
printf(“\n This is not leap year”);
}
Output:
Enter year : 1988
Number is less than 2000
This is leap year
b) if (condition)
{
//perform this;
//as well as this;
}
c) if (condition)
//perform this;
else
//perform this;
d) if (condition)
{
//perform this;
//as well as this;
}
else
{
//perform this;
//as well as this;
}
e) if (condition)
{
//if (condition)
//perform this;
}
else
{
//perform this;
//as well as this;
}
f) if (condition)
{
if (condition)
//perform this;
else
//perform this;
}
else
{
if (condition)
//perform this;
else
//perform this;
}
[Ref. 2h]
Using Logical operators
As we have already seen the logical operators. The basic use of these
is related to if – else statement. These conditional operators are:
a) && (AND operator)
b) || (OR operator)
c) ! (NOT operator)
When, we want to specify more than one condition in the single if
statement we can use logical operators among these conditions. Though,
there are two & (and) in the operator it is pronounced as AND and || as OR.
&& Operator is used when there is necessity that both the conditions to be
true. || Operator is used when there is necessity that any one conditions to
be true. e.g.
! (a > 10)
This means that whether ‘a’ is not greater than 10. In other words, it
can be written as (a <= 10).
//statements-default;
//statements-x;
false
condition
Statement-1
false
true condition
Statement-2
true
Statement-3
Default
Statements
/* Example 2.5 */
#include<stdio.h>
main( )
{
int a, b, c, d, e, per;
printf(“Enter marks of four subjects : “);
scanf(“%d %d %d %d”, &a, &b, &c, &d);
if(a < 40 || b < 40 || c < 40 || d < 40)
printf(“\n You have failed in one subject”);
per = (a + b + c + d) / 4;
if(per > = 60)
printf(“\n First class”);
else
{
if (per <=59 && per >=55)
printf(“\n Higher second class”);
else
if(per <=54 && per >=40)
printf(“Second class);
else
printf(“\n Fail”);
}
}
In this example we have used else – if ladder as well as logical
operators.
This statement will check whether marks of any one subjects is less
than 40 or not? If it is, it will execute the statement followed by ‘if’ i.e.
switch(variable)
{
case value-1:
//statements1;
break;
case value-2:
//statements2;
break;
case value-3:
//statements3;
break;
- - - - -
- - - - -
default:
//default-statements;
break;
}
statements-x;
In the above given syntax, value-1, value-2, value-3…. are the set the
constants. When the value of the variable given in the switch brackets is
matched with any one of these values, the particular set of statements are
executed and then program control transfers out of the switch block. For
example, if value of variable is matched with ‘value-2’ then statements2 are
executed and the break statement transfers the program control out of the
switch. If the match is not found, the ‘default’ block is executed. Remember,
statements-x are executed in any case. Generally, switch case are executed
for menu selection problems.
For example:
/* Example 2.6 */
int number = 2;
switch(number)
{
case 0 :
printf("None\n");
break;
case 1 :
printf("One\n");
break;
case 2 :
printf("Two\n");
break;
case 5 :
printf("Several\n");
break;
default :
printf("Many\n");
break;
}
Variable
Value1 default
Value2
Next Statement
OR
Variable
Value1
Statements1
Value2
Statements2
Value3
Statements3
default
default-block
Statements-x
[Ref. 1i]
[Ref. 1j]
Rules of switch statement
The break statement is optional. When the break is not written in any
‘case’ then the statements following the next case are also executed
until the ‘break’ is not found.
The default case is optional. If present, it will be executed when the
match with any ‘case’ is not found.
There can be at most one default label.
The default may be placed any where but generally written at the end.
When placed at end it is not compulsory to write the ‘break’ for it.
We can nest the switch statements.
while(condition)
{
//loop statements or body of loop
}
false
condition
true
Loop body
Statements after
the loop
See one more practical example of ‘while’ loop. That is, if we want to
find the addition of all the numbers from 10 to 20. It can be written as:
do
{
//loop statements or loop body
}
while(condition);
Loop body
true
condition
false
Statements after
the loop
See one more practical example of ‘do-while’ loop. That is, if we want
to find the addition of all the numbers from 10 to 20. It can be written as:
do /* do-statement */
{ /* start of the loop */
sum = sum + x; /* add the values */
x++; /* increment counter */
} /* end of the loop */
while(x <=20); /* check the condition */
printf(“\nAddition is : %d”,sum); /* print addition */
The ‘for loop is an entry controlled loop structure which provides more
concise loop structure having following general form:
int x;
for(x = 0; x < 10; x++)
{
printf(“%d”, x);
}
This for loop is executed for 10 times and prints the 0 to 9 digits in one
line. In short the statements are executed in following sequence:
1. x = 0;
2. if(x<10)
print value of x on screen
3. increment value of x by one
4. if(x<10)
print value of x on screen
5. increment value of x by one
……….
When the condition becomes false, the loop gets terminated.
For example if we want to print all the even numbers from 1 to 25 it can be
written using ‘for’ loop as:
int i;
for(i = 1;i < 25; i++)
{
if(i%2 == 0)
printf(“\n%d”, i);
}
Initialization
false
condition
true
Increment/
decrement Loop body
Statements after
the loop
/* Example 2.7 */
#include<stdio.h>
main()
{
int fact, num;
printf("Enter the number: ");
scanf("%d", &num);
for(fact=1 ; num>0 ; num--)
fact = fact * num;
printf("Factorial: %d", fact);
}
[Ref. 1o]
Additional features of ‘for’ loop
The ‘for’ loop have lot of capabilities that are not easily found in other
loop constructs. These are listed below:
a. More than one variable can be initialized at a time in the ‘for’ statement.
For example:
p = 1;
for(n = 0;n<10;n++)
for(p=1,n=0;n<10;n++)
b. Like initialization section, the increment section can also contain more
than one increment or decrement statements.
For example:
c. The condition may have any compound relation and the testing need not
be only loop control variable such as–
sum=0;
for(i=1; i<20 && sum<100; i++)
{
sum = sum + i;
}
m = 5;
for( ; m!=100 ; )
{
printf(“%d\n”, m);
m = m + 5;
}
f. Giving a semicolon at the end of ‘for’ will not give any syntactical error
but, all the iterations of the loop will be taken place. (Note: iteration is
one execution of the loop). Such as–
for(i=0;i<100;i++);
This loop will be executed for 100 times without any output.
The nesting may be continued up to any desired level. Here, for each
iteration of outer loop inner loop completes its all iterations. In above
example, the inner loop statements will be executed for 10 X 10 = 100
number of times. See one application of this concept. For example we
require following output:
*
**
***
****
In this case, the loops must be nested as shown below:
/* Example 2.8 */
#include<stdio.h>
main()
{
int x,y;
for(x = 0 ; x <= 3 ; x++)
{
for( y = 0 ; y <= x ; y++)
printf("*");
printf("\n");
}
}
[Ref. 1q]
Jumps in the loop
structures. That is, the ‘break’ statement is used to jump out of the loop.
When the ‘break’ is executed inside the loop, the program control will not
execute the loop for further iterations. Generally, the ‘break’ is associated
with if-statement. General form of using ‘break’ is:
break;
Flowchart
false
condition
true
break;
Loop body
Statements after
the loop
The dotted line shows the path where the program control will transfer.
For example:
/* Example 2.9 */
int x;
for(x = 10;x < 20; x++)
{
if(x%4==0)
break;
printf(“%d\n”);
}
10
11
continue;
Flowchart:
false
condition
Statements after
the loop
The dotted line shows the path where the program control will transfer.
For example:
/* Example 2.10 */
int x;
for(x = 10;x < 20; x++)
{
if(x%4==0)
continue;
printf(“%d\n”);
}
It has skipped the numbers which are divisible by 4, for which we have
skipped the printf statement.
Review Questions
Programming Exercises
1. Write a program to input two numbers from keyboard and find the
result of subtraction of greater number – smaller number.
2. Input a year from keyboard and determine whether it is leap year or
not using the conditional operator.
3. Accept three numbers from user and determine which of the two
numbers or all three numbers are equal or not using logical
operators.
4. Enter the amount saved in the bank from keyboard to a program.
The interest rate to this amount is 5% per six months. Find out how
much interest will be obtained on the amount saved for 1.5 years.
5. Imran’s basic salary is input through the keyboard. His dearness
allowance is 40% of basic salary, and house rent allowance is 20% of
basic salary. Write a program to calculate his gross salary.
* * *
* * * *
20. Accept a number from user and print it in reverse order using do-
while loop.
21. Write a program to find sum of all even numbers from n to m. Accept
values of variables n and m from keyboard.
22. Generate the following Fibonacci series using while loop till ‘n’
number. Accept n from user.
0 1 1 2 3 5 8 13 … … … n
23. Find the addition of all the numbers from n to –n. Take value of n as
input from keyboard. Use for loop.
24. Using while loop, write a program to print all Armstrong numbers
between 1 and 500. If sum of cubes of each digit of the numbers is
equal to the number itself, then number is called Armstrong number.
For example: 153 = (1*1*1) + (5*5*5) + (3*3*3)
---------------
References
1. Programming in ANSI C
by, E Balagurusamy, Tata McGraw Hill, 4th Edition
a. Chapter 5, Topic 5.2, Page No. 114
b. Chapter 5, Figure 5.2, Page 116
c. Chapter 5, Topic 5.4, Page 119
d. Chapter 5, Figure 5.5, Page 120
e. Chapter 5, Topic 5.5, Page 122
f. Chapter 5, Topic 5.6, Page 126
g. Chapter 5, Figure 5.9, Page 127
h. Chapter 5, Topic 5.7, Page 129
i. Chapter 5, Figure 5.11, Page 131
j. Chapter 5, Page 133
k. Chapter 6, Topic 6.1, Page 152
l. Chapter 6, Topic 6.2, Page 154
m. Chapter 6, Topic 6.3, Page 157
n. Chapter 6, Topic 6.4, Page 159
o. Chapter 6, Page 161
p. Chapter 6, Page 164
q. Chapter 6, Topic 6.5, Page 166
r. Chapter 6, Topic 6.5, Page 167
s. Chapter 6, Page 171
2. Let us C
By, Yashwant Kanetkar, BPB Publications, 7th Edition
a. Chapter 2, Page 51
b. Chapter 2, Page 56
c. Chapter 2, Page 58
d. Chapter 2, Page 59
e. Chapter 2, Figure 2.5, Page 60
f. Chapter 2, Page 61
g. Chapter 2, Page 62
h. Chapter 2, Page 64
i. Chapter 2, Page 67
j. Chapter 4, Page 136
k. Chapter 3, Page 98
l. Chapter 3, Page 99
m. Chapter 3, Figure 3.2, Page 101
n. Chapter 3, Page 121
o. Chapter 3, Figure 3.5, Page 121
p. Chapter 3, Page 108
q. Chapter 3, Figure 3.4, Page 111
r. Chapter 3, Page 114
s. Chapter 3, Page 118
t. Chapter 3, Page 120
Chapter 03
Arrays and Strings
Lectures allotted: 14
Marks Given: 12
Contents:
3.1 Arrays
Declaration and initialization of one dimensional array,
Two dimensional and character arrays,
Accessing array elements
3.2 Declaration and initialization of string variables,
String handling functions from standard library:
strlen( ), strcpy( ), strcat( ), strcmp( )
[Asked in S’08]
An array is a fixed-size collection of elements having same data-type.
It is simply a grouping of like-type data. Array is one of the derived data-
type (derived from other types of the data). That is array can be used to
represent a list of numbers, a list of names etc.
A list of items can be given one variable name using only one
subscript; such a variable is called as one dimensional array. It is very
generalized form of the array.
data-type variable-name[size];
[Asked in S’07]
The ‘data-type’ specifies type of the array. That is, int, char, float etc.
The ‘variable-name’ is the name given to the array, by which we will refer it.
Finally, size is the maximum number of elements that an array can hold.
For example:
int var[10];
1. Compile time
2. Run time
For example:
Here, the array variables are initialized with the values given in front of
it. That is, the 0th element of array will contain 5, 1st will contain 7 and so on.
Remember, the array indexing or subscripting is always done from 0th
position. The values of the array will be get stored as following manner
5 var[0]
7 var[1]
9 var[2]
3 var[3]
4 var[4]
Each element in the array will be referred individually by its index such
as, var[0], var[1], var[2], . . .
They can also be initialized individually such as:
var[0] = 5;
var[1] = 7;
var[2] = 9;
etc. after declaration of the array.
In the array declaration, the size can also be omitted. In such cases
the compiler will automatically identify the total number of elements and size
will be given to it. For example:
This array is not declared with size, but initialized with values. Here,
size of the array will be automatically set to 8. Now it can be referred as the
general array onwards.
Compile time initialization can also be done partially. Such as –
Here, array ‘x’ is having size 5, but only 0th, 1st, and 2nd elements are
declared with values. The remaining 3rd and 4th element of the array will be
automatically set to 0. This property is applicable to all numerical type of the
array in C. remember, however, if we have more values than the declared
size, the compiler will give an error. For example –
int sum[20];
for (i = 0;i<20;i++)
sum[i] = 1;
Here, all the elements of the array ‘sum’ are initialized with the value
1. Remember the loop control structures are applicable in these cases.
We can also use the scanf function to input the values from the user.
In such cases, the loop control structure is applicable. For example:
int sum[10], x;
printf(“Enter 10 numbers: ”);
for(x=0;x<10;x++)
scanf(“%d”,&sum[x]);
Here, the array ‘sum’ is initialized by taking the values as input from
the keyboard.
/* Program 3.1 */
/* Input 10 numbers from user and find the total of all of
them */
#include<stdio.h>
main( )
{
int val[10], i, total=0;
printf(“Enter any ten numbers: ”);
for(i=0;i<10;i++)
scanf(“%d”, &val[i]); // input numbers
for(i=0;i<10;i++)
total = total + val[i]; // find total
Sample Output:
table[5][4]
datatype arrayname[rows][columns];
For example:
int table[5][4];
This will create total 20 storage locations for two dimensional arrays
as,
Columns
[0][0] [0][1] [0][2] [0][3]
[1][0] [1][1] [1][2] [1][3]
Rows [2][0] [2][1] [2][2] [2][3]
[3][0] [3][1] [3][2] [3][3]
[4][0] [4][1] [4][2] [4][3]
table[2][3] = 10;
table[1][1] = -52;
8 5
9 6
or
int table[][] = {
{8, 5},
{9, 6}
};
The large two dimensional arrays can also be initialized using loops
such as,
int arr[5][5];
int z = 0, x, y ;
for(x=0;x<5;x++)
{
for(y=0;y<5;y++)
{
arr[x][y] = z;
z++;
}
}
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
}
}
Output:
First matrix:
8 5 6
1 2 1
0 8 7
Second matrix:
4 3 2
3 6 4
0 0 0
Addition:
12 8 8
4 8 5
0 8 7
[Asked in W’07]
The string is sequence of characters that is treated as a single data
item. In general, the character array is called as string. Any group of
characters defined between double quotation marks is a string constant.
Such as –
“The C Programming Language.”
[Ref. 1h]
Declaring a string
char string_name[size];
Here, string_name is the valid variable name given to the string and
‘size’ determines the number of characters in the string. For example:
char city[10];
char name[30];
Like numerical arrays the strings can also be initialized when they are
declared which is referred as compile time initialization. It can be done in
following three forms:
char str[10];
scanf(“%s”, str);
This statement will initialize the string ‘str’ by taking the input from the
keyboard. This will read the character sequence until occurrence of first
separator such as space character, tab or enter and store it into ‘str’. We can
also use the following function to input the string including spaces.
char str[10];
gets(str);
The gets() function defined in stdio.h file reads the string from the
keyboard until the enter is not pressed.
For printing the string, we can use the printf function in the similar
format such as:
printf(“%s”, str);
[Ref. 1j]
Arithmetic operations on character
printf(“%d”, ‘m’);
or
char ch = ‘m’;
printf(“%d”,ch);
ch = ch + 1;
1. strlen()
[Asked in W’07, W’08]
This function counts and returns number of characters from the string.
It takes the following form:
n = strlen(string);
2. strcat()
[Asked in W’07, S’08]
This function joins two strings together. That is, this function is used to
concatenate the strings. It takes the following general form:
strcat(string1, string2);
here, string1 and string2 are character arrays. When this function is
executed, content of string2 is attached at the end of string1. Content
of string2 remains unchanged.
For example:
strcat(str1, “York”);
printf(“%s”, str1); //outputs “NewYork”
3. strcpy()
[Asked in S’07, W’07, W’08]
This function almost works like string-assignment operator. That
is, strcpy() function is used to copy contents of one string into another.
It takes the following general form:
strcpy(string1, string2);
We can also use the constant as the parameter to the strcpy(). Such
as:
strcpy(city2, “Pimpri”);
4. strcmp()
[Asked in S’07, S’08]
This function is used to compare two strings and accordingly
returns the value. That is, it returns the numerical difference between
the strings. It takes the following general form:
strcmp(string1, string2);
strcmp(city1, city2);
strcmp(“Pune”, city1); etc.
strcmpi(string1, string2); or
stricmp(string1, string2);
5. strrev()
This function reverses the contents of the string. It takes the following
general form:
strrev(string);
if(strcmp(str1, str2)==0)
printf(“\nStrings are equal”);
else
printf(“\nStrings are not equal”);
In above example, 5 specify total number of strings that the array may
contain and 10 specifies maximum length of each string in the array. This
will create the following table in memory.
T h o m a s \0
R a j n e e s h \0
A t i s h \0
A n e e t a \0
N i l o f a r \0
We can access these elements using the array in the following manner.
for(x=0;x<5;x++)
printf(“\n%s”, tab[x]);
For initializing the array of strings, we can also use the same way but
using scanf function.
------------------
Review Questions
Programming Exercises
1. Enter ages of ten different men from user and find out who is the
eldest in all?
2. Accept 10 different values from keyboard; determine their average and
find out is there any number in the array whose value equals to
average.
3. Write a program to copy contents of one array into another array.
Accept size of both arrays as 7.
4. Input 10 different numbers from user. Count and display total even
numbers from it.
5. Accept values of two different arrays (size 5) from user and determine
how many numbers they are having common.
6. Write a program to accept 15 different float number from user and
display those numbers which are positioned on odd index positions in
reverse order. For example, you have to print the numbers on
array[13], array[11], array[9], array[7]………so on.
7. Initialize the matrix of 3 X 3 from user and determine whether it is
zero matrix or not?
8. Accept the values of 2 X 2 matrix from keyboard and find determinant
of it.
9. Initialize a 3 X 3 matrix and copy the contents of it into a single
dimensional array whose size is 9. Print all the values of 1D array.
10. Declare a 2D array of 4 X 3. Initialize first row values with 5, second
row values with 9, third row values with 3, and fourth row values with
7 using loop control structures.
11. Accept a 3 X 5 matrix from keyboard and copy the contents of it into
another 5 X 3 matrix by finding the transpose.
12. Input a 4 X 4 matrix and find the diagonal positions of it contains all
values same or not?
13. Accept any sentence from keyboard using gets( ) function and count
total number of words in it.
14. Accept any string from keyboard, convert it into the upper case and
display it.
15. Read a string from keyboard and inverse the case of it. That is, convert
lower case letters to upper-case and vice versa.
16. Input any two strings from user and find whether these are equal or
not. Don’t consider the case.
17. Read a string from user and analyze it. That is, count total number of
alphabets, digits, special symbols and display their counts.
18. Write a program to accept a string and display a list of ASCII codes
which represent accepted string (Asked in Summer 2007 Examination)
------------------
References
1. Programming in ANSI C
by, E Balagurusamy, Tata McGraw Hill, 4th Edition
a. Chapter 7, Topic 7.1, Page 190
b. Chapter 7, Topic 7.2, Page 192
c. Chapter 7, Topic 7.3, Page 193
d. Chapter 7, Topic 7.4, Page 195
e. Chapter 7, Topic 7.5, Page 199
f. Chapter 7, Topic 7.6, Page 204
g. Chapter 8, Topic 8.1, Page 229
h. Chapter 8, Topic 8.2, Page 230
i. Chapter 8, Topic 8.3, Page 231
j. Chapter 8, Topic 8.5, Page 231
k. Chapter 8, Topic 8.8, Page 244
l. Chapter 8, Topic 8.9, Page 250
------------------
Chapter 04
Functions and Structures
Lectures allotted: 14
Marks Given: 12
Contents:
4.1 Functions
Need of functions,
Scope and lifetime of variables,
Defining functions,
Function calls (call by value, call by reference),
Return values,
Storage classes,
Category of function (No argument No return value, No argument with
return value, argument with return value), recursion
4.2 Structures
Defining structure,
Declaring and accessing structure members,
Initialization of structure,
Arrays of structure.
Function
[Asked in W’07, W’08]
A function is self-contained block of statements that performs
particular task. C functions can be classified into two types:
• Library functions
• User-defined functions
The library functions are the functions which are already defined in C’s
functions library i.e. header files. For example, the functions scanf() and
printf() are the library functions defined in file stdio.h same as functions
sqrt() is defined in math.h and getch() is defined in conio.h. User defined
function is the function defined by the programmer who has written the
program. The task to perform is decided by the user. For example, the
main() function is an user-defined function. We decide what is to be written
in this function.
Main Program
B1 B2
Definition of functions
[Asked in S’08]
The function definition is an independent program module that is
specially written to implement the requirements of the function. So it is also
called as function implementation. It includes following topics:
• Function Header
• Function Body
The general form of function definition is as given below:
Function Header
task. Since, they represent the actual input values they are referred as
formal parameters or formal arguments.
For example:
void print_line()
{
--------
}
Function Body
For example:
{
printf(“Subtraction: %d”, a – b); /* no variables */
return; /* optional */
}
Return values
A function may or may not send back any value to the calling function.
If it does, it is done by return statement. The return statement also sends
the program control back to the calling function. It is possible to pass a
calling function any number of values but called function can only return one
value per call, at most.
The return statement can take one of the following forms:
return;
return(value);
return(variable);
return(expression);
The first plain return does not return any value; it acts much as closing
brace of the function. The remaining three statements can eliminates the
brackets also. When the return is executed, the program control immediately
transfers back to the calling function. None of the statements written after
return are executed afterwards. For example:
return(x);
printf(“Bye…Bye”);
In this case the printf statement will not be executed in any case.
Because the return statement will transfer program control immediately back
to the calling function. Some examples of return are:
return(x*y);
OR
return x*y;
if(x>y)
return x;
else
return y;
Function calls
A function can be called by simply using function name followed by a
list of actual parameters (or arguments) if any, enclosed in parentheses. For
example:
main()
{
float m;
m = mul(5.2, 3.71); /* function call */
printf(“\n%d”,m);
}
mul(5.2, 3.71);
mul(m, 3.71);
mul(5.2, m);
mul(m, n);
mul(m+5.1, 3.71);
mul(m+3.6, m+9.1);
mul(mul(6.1,8.2), 4.5);
Only we have to remember that the function call must satisfy type and
number of arguments passed as parameters to the called function.
For example:
void printline(void)
{
int i;
for(i=0;i<25;i++)
printf(“–”);
}
For example:
For example:
For example:
float value_of_PI(void)
{
float pi = 22/7;
return pi;
}
Recursion
[Asked in W’08]
It is a special case of calling a function when a function calls itself
again and again. It forms a chaining of calling a function. For example:
void main(void)
{
printf(“\nHello”);
main(); /* recursive call */
}
factorial of 5 = factorial of 4 × 5
factorial of 4 = factorial of 3 × 4
factorial of 3 = factorial of 2 × 3
factorial of 2 = factorial of 1 × 2
factorial of 1 = 1
int factorial(int n)
{
int fact;
if(n==1)
return 1;
else
return(n*factorial(n-1));
}
#include<stdio.h>
#include<conio.h>
int power(int x, int y)
{
if(y<1)
return(1);
else
return( x * power(x,--y));
}
void main()
{
printf("%d", power(4, 3));
getch();
}
Rules of use
Storage Classes
The properties of the variables tell us about following things, referred
as storage class:
1. Where the variable would be stored?
2. What will be the initial value of the variable? (i. e. default initial value)
3. What is scope of the variable?
4. What is lifetime of the variable?
Storage: Memory.
Default initial Value: Garbage.
Scope: Local (to block in which variable defined)
Lifetime: Till control remains within block where it is defined.
Example:
main()
{
auto int x, y;
x = 10;
printf(“Values : %d %d”, x, y);
}
We can tell the compiler that a variable should be kept in one of the
microprocessor’s register, instead of keeping in memory.
Example:
main()
{
register int a;
for(a=0;a<10;a++)
printf(“\nValues : %d ”, a);
}
The value of this local variable remains as it is until the end of the
program.
Storage: Memory.
Default initial Value: Zero.
Scope: Local (to block in which variable defined)
Lifetime: Value of the variable remains as it is between
function calls.
Example:
void insert()
{
static int m;
m++;
printf(“\n%d”, m);
}
main()
{
insert();
insert();
insert();
}
Storage: Memory.
Default initial Value: Zero.
Scope: Global
Lifetime: As long as the program execution doesn’t come to an
end.
Example:
main()
{
extern int y;
printf(“Value: %d ”, y);
}
int y = 30;
Start
int mul(a, b)
Accept values of x
and y Let, m = a × b
Let,
z = mul(x, y) return (m)
Print value of z
Stop
Structure
[Asked in W’07, W’08]
It is a derived data-type in C, which is a collection of different data-
type elements. It is a convenient tool for handling a group of logically related
data items. Structure helps to organize the complex data in more meaningful
way.
Defining a structure
[Asked in W’07, W’08]
Unlike arrays, structures must be defined first for their format that
may be used later to declare structure variables. The general format or
syntax to create a structure is:
struct tag_name
{
data_type variable1;
data_type variable1;
- - - - -;
- - - - -;
};
struct book
{
char title[20];
char author[15];
int pages;
float price;
};
Here, the fields: title, author, pages and price are called as structure
elements or members. Each of these members belongs to different data
types. The name of structure ‘book’ is called structure tag. It simply
describes a format called template to represent information as shown below:
pages Integer
price Float
Arrays vs Structures
struct book
{
char title[20];
char author[15];
int pages;
float price;
};
struct book book1, book2, book3;
struct book
{
char title[20];
char author[15];
int pages;
float price;
}book book1, book2, book3;
struct
{
char title[20];
char author[15];
int pages;
float price;
}book book1, book2, book3;
book1.price
is the variable representing the price of book1 and can be treated like
any other ordinary variable. Here is how we would assign values to the
members of book1:
strcpy(book1.title, “Programming”);
strcpy(book1.author, “T.B.Kute”);
book1.pages = 375;
book1.price = 275.00;
scanf(“%s”, book1.title);
scanf(“%s”, book1.author);
scanf(“%d”, book1.pages);
Structure Initialization
[Asked in S’07]
Like any other data type, a structure variable can be initialized at
compile time.
struct time
{
int hrs;
int mins;
int secs;
};
struct time t1 = {4, 52, 29};
struct time t2 = {10, 40, 21};
#include<stdio.h>
main()
{
struct student
{
int roll_no;
char name[10];
int age;
}s;
printf(“Enter roll, name and age: ”);
scanf(“%d%s%d”, &s.roll_no, s.name, &s.age);
printf(“\nEntered information: \n”);
printf(“Roll number: %d”, s.roll_no);
printf(“\nName: %s”, s.name);
printf(“\nAge: %d”,s.age);
}
Two variables of the same structure type can be copied the same way
as ordinary variables. if person1 and person2 belongs to the same structure,
then the following statements are valid:
person1 = person2;
person2 = person1;
person1 == person2
person2 != person1
are not permitted. C does not permit any logical operation on structure
variables. In case, we need to compare them, we may do so by comparing
members individually.
The individual members are identified using the member operator, the
dot. A member with dot operator along with its structure variable can be
treated like any other variable name and therefore can be manipulated using
expressions and operators. Consider the following structure,
struct person
{
char name[15];
int age;
int salary;
} p1, p2, p3;
p1.age++;
––p2.salary;
Arrays of structure
[Asked in W’07, W’08]
We use structure to describe the format of number of related variables.
For example, in analyzing the marks obtained by a class of students, we may
use a template to describe student name and marks obtained in various
subjects and then declare all the students as structure variables. In such
cases, we may declare an array of structures, each element of the array
representing a structure variable. For example:
struct marks
{
int subject1;
int subject2;
int subject3;
};
main()
{
struct marks student[3] =
{{52,96,86}, {42, 49, 52}, {81, 89, 84}};
}
student[0].subject1 = 52;
student[0].subject2 = 96;
student[0].subject3 = 86;
------
------
student[2].subject3 = 84;
52 96 86 subject1
42 49 subject1
52
81 89 84 subject1
float marks;
} a[10];
int i;
printf(“Enter info. of students:”);
for(i = 0 ; i < 10 ; i++)
{
scanf(“%d %s %f”, &a.roll[i],
a.name[i], &a.marks[i]);
}
for(i = 0 ; i < 10 ; i++)
{
printf(“\n%d %s %f”,
a.roll[i], a.name[i], a.marks[i]);
}
}
------------------
Review Questions
Other: Marks
a) Explain recursion with example 4
b) State types of the functions. 2
c) Describe the use of static and extern variables. 4
d) Explain the meaning of register and auto storage classes. 4
e) Define scope, lifetime & visibility of variables. 2
f) Differentiate structure and array with example. 4
g) Give syntax of declaring a function. 2
h) Define global and local variables. 2
Programming Exercises
1. Create a function add( ) which will calculate the sum of the array
elements passed as parameters to it.
2. Write a function to calculate the factorial of the number.
3. Create a user defined function to find the minimum value of three
float numbers which are passed as the arguments to it.
4. Write a function range( ) which will take value of A and B as
parameter and displays total numbers divisible by 3 in the range A to
B.
5. Write a function which will take a year as argument and find whether
that year is a leap year or not?
6. Create a function to pass any string as argument. This function will
find the total number of vowels in that string. Take integer as the
return type of the function.
7. Define a structure Cricket having data members as team name,
player name and average. Accept the values of 5 different players
and display their data team-wise.
8. Define a structure Nation contains data members as name, capital
and population. Accept the data for 10 nations and display it in
reverse order.
9. Define a structure Book having data members as book name, author,
pages and price. Accept this data for 7 different books and display
those data having pages greater than 300.
10. Declare two structures named Date and Time. Date contains day,
month and year whereas Time contains hours, minutes and seconds.
Accept the date and time and display date in month day, year (e.g.
February 9, 2009) and time in hh:mm:ss (e.g. 12:56:02) format.
11. Define a structure Student having data members as name, age, class
and marks. Accept this data for 5 students and display this data for
student who is youngest?
12. Define a structure College having data members as name, branches,
result. Accept this data for 5 colleges and identify whose result is
worst?
------------------
References
1. Programming in ANSI C
by, E Balagurusamy, Tata McGraw Hill, 4th Edition
Chapter 9: User-defined functions
Chapter 10: Structures and Unions
------------------
Chapter 05
Pointers
Lectures allotted: 14
Marks Given: 16
Contents:
Pointers
[Asked in S’07, W’07, S’08, W’08]
A pointer is a derived data type in ‘C’. It is built from any one of the
primary data type available in ‘C’ programming language. Pointers contain
memory addresses as their values. Since these memory addresses are the
locations in the computer memory where the program instructions and data
are stored. Pointers can be used to access and manipulate data in memory.
Advantages of Pointers
1) Pointers are most efficient in handling arrays.
2) They can be used to return multiple values from function through
function argument.
3) They permit references to functions and thereby they provide facility
to pass function as argument to another function.
4) The use of pointer arrays to character string saves the data storage
space in the memory.
5) Pointers allow C to supports dynamic memory management.
6) They provide an efficient tool for manipulating dynamic data
structures such as structures, link lists, quos, stacks, trees and
graphs.
7) Pointers reduce the complexity and length of the program.
8) Pointers increase the execution speed and thus reduce the program
execution time. Of course the real power of C lies in the proper use of
pointers.
Understanding Pointers
Computer memory is sequential collection of storage cells as shown
in figure. Each cell is commonly known as byte and has a number called as
address associated with it. Typically the addresses are numbered
sequentially starting from zero. The last address depends upon the memory
size. A computer having 64KB memory will have its last address as 65535.
int quantity=150;
150 value
4096 address
During the execution of program computer always associates the name
quantity with address 4096. We may have access to the value 150 by using
either the name quantity or the address 4096. Since memory addresses are
simply numbers they can be assigned to some variables which can be stored
in memory like any other variables. Such variables that hold memory
addresses are called as ‘pointer variables’ the pointer variable is nothing but
a variable that contains an address which is location of another variable in
memory.
Remember: pointer is a variable. Its value is stored in memory in
another location. Suppose we assign the address of quantity to a variable ‘p’,
the link between the variable ‘p’ and quantity can be visualized as:
p 4096 1012
Since the value of variable ‘p’ is the address of variable quantity for
using the value of ‘p’ and therefore we say that the variable p points to the
variable quantity. Thus p is called as ‘pointer’.
Pointer
int x=10;
printf(“%u”,&x);
data-type *variable-name;
int *p;
float *x;
int *p;
int x = 10;
p = &x;
int * p; /*style 1 */
int *p; /*style 2 */
int * p; /*style 3 */
Multiple declarations
int *p, x, *q;
Pointer’s flexibility
Pointers are flexible. We can make the same pointer to point different
data variables in different statements.
Example:
int x, y, z, *p; y x z
. . . . . . .
p = &x;
. . . . . . .
p = &y;
. . . . . . . p
p = &z;
We can also use different pointers to point the same data variable. For
example:
int x; p1 p2 p3
int *p1=&x;
int *p2=&x;
int *p3=&x;
. . . . . .
. . . . . . x
int marks,*p,n;
marks=79;
p=&marks;
n=*p;
p=&marks;
n=*p;
is equivalent to:
n=*&marks;
Chain of pointers
It is possible to make a pointer to point to another pointer thus
creating a chain of pointer as shown below:
p2 p1 variable
int **p;
void main()
{
int x,*p,**p;
x=100;
p1=&x; /* pointer to variable*/
p2=&p1; /* pointers to pointer*/
printf(“%d”,**p2);
}
Output: 100
Pointer’s Arithmetic
[Asked in S’07, W’07, S’08, W’08]
Addition on pointers
p++; /* valid */
4. We can add or subtract the constant from pointer variable. In this case
value of pointer is incremented or decremented by the scaling factor of
respective data type. Example:
p = p + 2; /* valid */
*p = *p * 4; /* valid */
x = x * y;
x = x / y;
is not allowed.
3. We cannot multiply or divide a pointer by constant. Example:
p = p * 4; /* invalid */
p = p / 2; /* invalid */
int a=20;
&a=1000; // It is illegal.
int *p;
p = &x[0];
OR
p = x;
Now we can access every value of x using p++ to move from first
element to another i. e.
p = &x[0]; = 9092
p = &x[1]; = 9094
p = &x[2]; = 9096
p = &x[3]; = 9098
p = &x[4]; = 9100
for(i=0;i<5;i++)
printf(“\n%d”,*(p+i));
#include<stdio.h>
main()
{
int x[5],*p, sum = 0,i;
for(i=0;i<5;i++)
scanf(“%d”, &x[i]);
p=x;
for(i=0;i<5;i++)
sum=sum + *(p+i);
printf(“%d”, sum/5);
}
Pointers to String
Strings are created like character array. Therefore, they are declared
and initialized as:
M u M b a i \0 \0 \0 \0
M u M b a i \0
city
This creates a string and then stores its address in the pointer variable
city. This pointer variable now points to the first character of the string. That
is, the statements:
printf(“%c”,*city);
will print the current pointing character ‘M’ on the screen and the
statement,
printf(“%s”, city);
will print all the sets of characters from current pointing location to the
first occurrence of ‘\0’. We can also use the runtime assignment for
initializing the pointer such as,
char *city;
city = “Mumbai”;
This is not a string copy. It will only copy the address of first constant
from array i.e. ‘M’ into the character pointer city. We can also use scanf
statement to initialize the string using pointers. Example:
char *name;
printf(“Enter your name: ”);
scanf(“%s”, name);
printf(“%s”, name);
OR
while(*name!= ‘\0’)
{
printf(“%c”,*name);
name++;
}
Array of Pointers
[Asked in W’08]
We can create the array of pointers also with the same declaration of
the array. For example:
int *a[10];
here, the array of pointers will be created i.e. the array will point to 10
different integers, such as:
a[0]=&x;
a[1]=&y;
a[2]=&z;
.
.
.
Example:
for(i=0;i<10;i++)
scanf(“%d”,a[i]);
for(i=0;i<10;i++)
printf(“%d”,*a[i]);
char nations[3][3];
name[0] “India”
name[1] “Australia”
name[2] “Newzeland”
for(i=0;i<3;i++)
printf(“\n %s”, nations[i]);
Pointers to Function
change(int x)
{
x=x+10;
}
main()
{
int a=5;
change(a); //call by value
printf(“%d”, a);
}
Here function change() is called by value in the function main(). The ‘a’
is the actual parameter of the function and ‘x’ is the formal parameter of the
function. When the function is called by value, the value of variable ‘a’ is
passed into variable ‘x’. Therefore, it is called as ‘call by value’. The ‘x’ & ‘a’
are the local variables of individual functions that is main() and change().
Therefore, the changes made on variable ‘x’ will not affect variable ‘a’.
Therefore the ‘call by value’ doesn’t reflect the change. Instead of doing this
change(int *x)
{
*x=*x+10;
}
main()
{
int a+5;
change(&a); // call by reference
printf(“%d”,a);
}
When the function change() is called, the address of variable ‘a’ (not
the value) is passed into the function change(). Inside change(), variable ‘x’
is declared as a pointer. Therefore ‘x’ will contain the address of variable ‘a’.
The statement:
*x = *x + 10;
means add 10 to the value stored at address of ‘a’ that is ‘x’. Since ‘x’
represents the address of ‘a’, value of ‘a’ is changed from 5 to 15. Therefore
call by reference provides mechanism by which the function can change the
stored value in the calling function. This mechanism is also known as ‘call by
address’ or ‘pass by pointers’. Example:
Example:
*n = *m;
}
main()
{
int a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int b[10];
copy(b, a); //call by reference
for(i=0;i<10;i++)
printf(“\n%d”, b[i]);
}
------------------
Review Questions
d) Two numbers are input through keyboard into two locations C and D.
Write a program to interchange the contents of C and D. 4
e) Write a program for exchanging values of two variables using call by
reference. 4
f) Explain concept of pointer arithmetic operations. 4
g) Explain how array elements are accessed by using pointers. 4
h) What will be the output of the following program? 4
#include<stdio.h>
void main( )
{
int i = 3; int * j;
j = &i;
printf(“\n Address of i = %u”, &i);
printf(“\n Address of i = %u”, j);
printf(“\n Address of j = %u”, &j);
printf(“\n value of j = %u”, j);
printf(“\n value of i = %d”, i);
printf(“\n value of i = %d”, *(&i));
printf(“\n value of i = %d”, *j);
}
Programming Exercises
------------------
References
1. Programming in ANSI C
by, E Balagurusamy, Tata McGraw Hill, 4th Edition
(All the data is referred from this book, Chapter No. 11 Pointers)
Understanding Pointers in C
by, Yashvant Kanetkar, BPB Publications, First Edition, 2006
------------------
Notes
¾ Most of the books used as reference for the chapters are available in e-
copy on the following sites. You can use them for reference too.
• www.esnips.com
• www.4shared.com
• www.isbnonline.com
• www.pdfchm.com
• www.scribd.com
¾ The reference material that is not been included in this book such as
transparencies, objective questions, notes, MSBTE and Sample
question papers, program’s soft copy are available on following link of
Google sites:
http://sites.google.com/site/tusharkute
¾ The following software are used for compiling programs:
Borland Turbo C++ Compiler
¾ The following software are used for formatting this documents:
Editing: Microsoft Office Word 2003, Windows notepad.
PDF Creation: Adobe PDF Maker 6.0
¾ By analyzing last 4 questions papers of MSBTE, I have analyzed the
format of the paper. This will be beneficial for the students learning
diploma in Computer group under MSBTE. It is given on the next page.
¾ You are free to send the queries and suggestions at:
tbkute@gmail.com
-------------------
Chapter Marks
Chapter 1 16 / 20
Chapter 2 32 / 36
Chapter 3 16
Chapter 4 12 / 16
Chapter 5 28
Total 108
Programs:
Compulsory Questions
1. Operators
02 + 04 Marks
2. If-else, else-if
04 Marks
3. Difference between while and do-while
02 / 04 Marks
4. The switch statement
02 / 04 Marks
5. break / continue
02 Marks
6. 2D Array
04 Marks
7. Two string library functions
02 + 04 Marks
8. A Program on simple structure
04 Marks
9. Call by reference
04 Marks
10. Pointer Arithmetic
04 Marks
11. What is pointer?
02 Marks