C Programming Notes
C Programming Notes
UNIT-1
Introduction to computers
A computer is an electronic device capable of manipulating numbers and symbols under the
control of a set of instructions known as computer program.
Types of Computers
Mainframe Computers
Mini Computers
Micro Computers
Super Computers
Mainframe Computers work at a high speed, and have a high storage capacity
4bits = 1 Nibble
8bits = 1 byte
Organization of Computer:
Department of CSE, GIT, GU Page 2
“Programming with C” course material
Memory unit
Control unit
Input unit
Output unit
The Input and Output units are used to receive and display Inputs & Solutions
CU (Control Unit)
MU (Memory Unit)
The Control Unit Controls all the activities of the Computer. It sends commands and control
signals and finds the sequence of instruction to be executed.
Memory Unit is the place where all input data and results are stored. Computer memory is also
available in the form of Random Access Memory (RAM)
1.
Keyboard
1.
Printer
2.
Mouse
2.
Monitor
3.
Joystic
3.
4. Laser printers
5.LCD
Department of CSE, GIT, GU
Page 3
“Programming with C” course material
Storage Devices :
1.
Floppy disk
2.
Hard disk
3.
Compact disk
Hard disk
ROM (Read only Memory) : This is a non-volatile or data storage medium which stores start
up programs (operating systems). This essentially stores the BIOS (Basic Input Operating
System)
Note : Basically Computer System components communicate it binaries as (0‟s & 1‟s, 0
refers OFF state,1 refer ON state)
Eg : 00110101011101110001, 101100001010101
Second – Generation Language: all the instruction are in the forms of mnemonics. The
symbolic instruction language called as Assembly Language. All the symbolic instructions are
converted into binaries with the help of translator called Assembles. ASCII (American
Standard Code For Information Interchange) is commonly used for translation of source
Program into object program
More R,S
Object Program
0101
10101010
0100
00001101
Third – Generation Language : These are written in English with symbols and digits. Then are
known as High level language (HLL). common high level languages are c,c++, COBOL,
BASIC, FORTRAN, PASCAL, etc.
For execution the program is translation into binary form by compiler or interpreter. Source
program
Compiler
Object Prog.
Linker
Executable Program
the 3GL in an upward trend toward higher abstraction and statement power. The 4GL was
followed by efforts to define and use a 5GL.
1972. It was developed Dennis Ritche in late 1970‟s. it began to replace the more familiar
languages of that time like PL/1, ALGOL etc.
“C” became popular because of its reliability, simple and easy to use
ALGOL 60 was developed and did not become popular because it was too general and too
abstract.
Next as it could not come up to make ALGOL 60 better one they moved to
At the same time a language called “B” written by ken Thompson at AT & T‟S.
Bell laboaratories as a further simplification of BCPL.
“C” s compactness and coherence is mainly due to it‟s one man language. Ex-LISP, AASCA
Year
Lang
Developed by
Remarks
1960
ALGOL
International Committe
1963
CPL
camebridge university
1967
BCPL
Camebridge university
1970
AT&T
1972
AT & T
Note : C is a middle level language because it was due to have both a relatively good
programming efficiency and relativity good machine effecience.
It is efficient and fast because of its variant data-types and powerful operation.
It is highly Portable i.e., programs written in one computer can be run on another
It is well suited for structure program, thus allows the user to think about the problem in the
terms of functional blocks.
ability to extend itself, we can continuously add our own functions to the program.
Complier : This reads the entire source program and converts it to the object code. It provides
error not of one line, but errors of the entire program. It executes as a whole and it is fast
Interpreter : It reads only one line of a source program at a time and converts it into an object
code. In case of errors/same will be indicated instantly. It executes line by line and it is slow.
Linker is a function which links up the files that an present in the operating system, it also
links the files for the hardware and makes the system ready for executing.
Preprocessor : This is a program, that processes the source program before it is passed on to
the compiler. The program typed in the editor is the source code to the preprocessor, then it
passed the source code to the compiler. It is not necessary to write program with preprocessor
& activity
Preprocessor directories are always initialized at the beginning of the program. it begins with
the symbol (#) hash. It place before the main() function
# define PI 3.14
Character Set : The characters that can be used to form words and expressions depends upon
the computer to which the program is run
Digits 0-9
“C” Tokens:
Individual words and punctuation marks are characters. In a “C” program the smallest
individual units are known as “C” tokens. It has 6types of token‟s
Keywords : Keywords are reserved words by compiler. Keywords are assigned with fixed
meaning and they cannot be used as variable name. No header file is needed to include the
keywords.
Identifiers :
These are the names of variables ,functions and arrays, these are the user
defined names
Eg : # define NUM 10
# define A 20
Constants : constants in “C” are applicable to the values which not change during the
execution of a program.
Integer Constants : Sequence of numberr 0-9 without decimal points, fractional part or any
other symbols. It requires two or four bytes, can be +ve, -ve or Zero the number without a
sign is as positive.
Character Constants
Single character const : A single character constants are given within a pair of single quote
mark.
String Constant : These are the sequence of character within double quote marks
Variables : This is a data name used for storing a data, its value may be changed during the
execution. The variables value keep‟s changing during the execution of the program
Integer (int)
Character (char)
double-precession (double)
void
Data type
Bytes in Ram
char
1 bytes
-128 to 127
int
2 bytes
float
4 bytes
3.4c-38 to 3.4 c+ 38
double
8 bytes
1.7C – 308 to 1.7c +308
Page 9
“Programming with C” course material
Integer Types : Integers are whole numbers with a range of variables supported by a
particular machine.
In a signed integer uses one bit for sign and 15 bits for magnitude
short int
int
long int
sign qualifier
unsigned qualifier
short int uses half the range of storage amount of data, unsigned int use all the bits for the
magnitude of the number and are positive.
short int
int
long int
Datatype
Size
Range
1 byte
-128 to 127
unsigned char
1 byte
0 to 255
2 byte
unsigned int
2 bytes
0 to 65535
Floating Point Datatype: Floating Point numbers are stored with 6 digits of precision. Those
are defined with keyword float. When the accuracy is not sufficient then the datatype double
can be used. double gives a precesion of 14 digits these known as double precesion numbers.
Still for a better process we can use long double which uses 80 bits.
float
double
long double
Void datatype : A void type has no value this is usually used to specify the return type of
function , this function does not return any value to calling function
Declaration of Variable :
It tells the complier what the variable name is used, what type of date is held by the variable.
Eg : int a, b;
float sum;
double ratio;
representation of Constant
x= 10;
y=5;
Type def : Defined as type definition by using typedef we can create new datatype.
main( )
O/P :
x= 10.10000
p = 5.2
main ( )
Operators
Operator:
They include:
Arithmetic
Relational
Logical
Assignment
Conditional
Bitwise
Special
Arithmetic Operators: C provides all the basic arithmetic operators, they are +, -, *, /, %
Integer division truncates any fractional part. The modulo division produces the remainder of
an integer division.
Eg:
a+b
a–b
a*b
-a * b
a/b
a%b
Here „a‟ and „b‟ are variables and are known as operands. % cannot be used for floating
point data. C does not have an operator for exponentiation.
Integer Arithmetic: When the operands in an expression are integers then the expression is
an integer expression and the operation is called integer arithmetic. This always yields an
integer value. For Eg. a = 14 and n = 4 then
a - b = 10
a + b = 18
a * b = 56
a/b=3
- 14 % 3 = -2
a%b=2
-14 % - 3 = 2
14 % -3 = 2
1).
main ( )
{
int sum, prod , sub, div, mod, a, b ; printf(“Enter values of a, b :”) ; scanf(“ /.d %d”, & a, & b)
;
2). WAP to convert given no. of days into years, months days
3). WAP to use various relational operators and display their return values.
main ( )
printf(“ in condition :
printf(“ In 10! = 10
printf(“ In 10 = 10
%5d” , 10 == 10);
printf(“ In 10>=10
%5d”, 10>=10);
printf(“ In 10<+100
%5d”, 10<100);
printf(“ In 10! = 9
%5d”, 10!=9);
Floating Point Arithmetic involves only real operands of decimal or exponential notation. If x,
y & z are floats, then
x = 6.0/7.0 = 0.857143
y = -1.0/3.0 = 0.333333
z = 3.0/2.0 = 1.500000
Mixed mode Arithmetic: When one of the operands is real and the other is integer the
expression is a mixed mode arithmetic expression.
15/10 = 1
10/15 = 0
-10.0/15 = -0.666667
Relational Operator: These are the operators used to Compare arithmetic, logical and
character expressions.the value of a relational express is either one or zero .it is 1 if one is the
specified relation is true and zero if it is false For eg:
10 < 20 is true
20<10 is false
Operator
Meaning
<
is less than
<=
>
>=
==
is equal to
!=
is not equal to
O/P
Condition
:
Return values
10! = 10
10 = = 10
10> = 10
10! = 9
void main ( )
printf(“In
{ !(8 = =8)
clrscr ( ); }
printf(“In
printf(“ In
O/P 5>3
&&
5<10
8<5
||
5= =5
!(8 = =8)
main ( )
z= x * y ++;
a=x*y;
z = x * ++y;
a = x * y;
220 220
12 10
Logical operator : Logical Operators are used when we want to test more than one
condition and make decisions. here the operands can be constants, variables and expressions
&&, ||, !
Eg:a > b
&& x = = 10
Truth Table
&&
||,
OP1
OP2
OPJ&OP2
OP1 ||OP2
OP
1
1
0
Department of CSE, GIT, GU
Page 17
“Programming with C” course material
Assignment Operator: Used to assign the result of an expression to a variable. „= „is the
assignment operator. In addition C has a set of „short hand‟ assignment operators of the form
Var Op = Exp :
Variable
operator
shorthand assignment
Binary arithmetic
operator
var
op = exp;
is equivalent to
Eg:x + = 1;
== > x = x+1
x+ = y+1
== > x = x+y+1
main()
{ int a, b
b = a%z;
char x ; int y;
printf((“ \n nter a character” );
O/P
1) Enter a character
2) Enter a character
Shorthand operator
Assignment operator
a+=1
a = a+1
a-=1
a=a-1
a * = n+1
a = a* (n + 1)
a / = n+1
a = a/(n+1)
a%=b
a=a%b
++
and
--
The Operator + + adds 1 to the operand while -- subtracts 1, Both are unary operators
Eg :
++x
or
x ++
== > x+=1
== > x=x+1
.
-- x
or
x- -
== > x-=1
== > x=x-1
A Profix operator first adds 1 to the operand and then the result is assigned to the variable on
left. A postfix operator first assigns the value to the variable on the left and the increments the
operand.
Eg:
1) m = 5;
2). m = 5
y = ++m;
y = m++
O/P
m =6, y=6
m=6, y=5
Page 19
“Programming with C” course material
Conditional operator: is used to check a condition and Select a Value depending on the
Value of the condition.
If the Value of the condition is true then Value 1 is e valued assigned to the varable, otherwise
Value2.
if (a>b)
big = a;
else
big = b;
Bitwise operator : are used to perform operations at binary level i. e. bitwise. these operators
are used for testing the bits, or Shifting them right or left . These operators are not applicable
to float or double. Following are the Bitwise operators with their meanings.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive – OR
~ Complement
Page 20
“Programming with C” course material
a = 13
Binary
00001101
b=6
00000110
Shifts two bits to left , that is 2 zeros are inserted at the right
00001101
Moved
00110100
Note : when you shift a bit towards left its Decimal Value is multiplied by Two (2).
a >>2 00000011
000000 11 Decimal 3 (13/4)
main ( )
{ int x = 2;
float y = 2;
o/p sizeof ( x ) = 2
sizeof ( y ) = 4
~ Complement
to
1‟s
and 1‟s
to O‟s .
)
op1
op2 &
a = 13
0000 1101
b=6
0000 0110
a&b
0000 0100
1
| (Bitwise Logical
or
)
a = 13
0000 1101
b=6
0000 0110
a 1b
0000 1111
^ ( Bitwise
Exclusive
or
op1
op2
0
a = 13
0000 1101
b=6
0000 0110
a^b
0000 1011
0
special operators : these are two other operators in c.
computer memory.
eg :
sizeof
(float)
returns
int
m,
[ 50 ]
sizeof (m)
returns 2
sizeof ( x )
returns 100
( 50 x 2 )
comma operator : can be used to link the related expressions together. A comma- linked: list
of expressions are evaluated left to right and the value of right-most exp is the value of
combined expression.
Eg : value = ( x = 10, y = 5, x = y)
First 10 is assigned to x
then 5 is assigned to y
since comma has the lowest precedence of all operator, the parantheses are necessary .
Operator - precedence & Associativity
precedence is nothing but priority that indicates which operator has to be evaluated first when
there are more than one operator.
Associativity : when there are more than one operator with same precedence [ priority ] then
we consider associativity , which indicated the order in‟ which the expression has to be
evaluated. It may be either from Left to Right or Right to Left.
eg : 5 * 4 + 10 / 2
1 2
= 20 + 5
3
=25
Highest
Function call
Precedence
Array Subscript
->
L→R
::
unary
Page 23
“Programming with C” course material
S
iz
~
e
Bitwise is complement o
f
r
et
u
+
n
unary plus s
si
z
e
o
_ f
o
unary minus
p
e
r
a
n
++
d
pre/pest increment i
n
2 b
y
te
__ s
pre/pest decrement
M
e
m
& b
e
Address r
A
c
c
e
*
s
Indirection s
.* 6
Dereference
>
>
S
h
→*
if
t
Dereference
R
3 i
g
Multiplication
h
* t
Multiply 6
R
el
at
/ i
o
Divide n
4 al
<
% L
e
Remainder (Modules) s
s
t
Additive h
a
+
n
Binary Plus
<
- =
Binary mains
Shift
<<
Shift left
Less then equal to
>
Greater than
>=
Equality
==
L
Equal to →
R
!=
Not Equal to
L
→
R
R→ L
L
→
R
L
→
R
L→R
L→R
L
→
R
Bitwise AND
&
Bitwise AND
L→R
Bitwise XOR
Bitwise XOR
10
L→R
Bitwise OR
Bitwise OR
11
L→R
Logical AND
&&
Logical AND
12
L→R
Logical Or
||
Logical OR
13
L→R
Conditional
?:
R→L
Simple Assignment
=
*
Assign product
/=
Assign quotient
%=
15
R→L
Assignment
+=
Assign sum
-=
Assign Difference
&=
^=
1=
Assign Bitwise OR
<<
>>
Comma
,
Evaluate
16
L→R
Note : Unary, Conditional & Assignment operators are evaluated from Right to Left,
remaining operators are from Left to Right
Type Casting: Normally before an operation takes pace both the operands must have the
same type. C converts One or both the operands to the appropriate date types by “Type
conversion”. This can be achieved in 3 ways.
Implicit Type conversion : In this the data type /Variable of lower type (which holds lower range of
values or has lower precision ) is converted to a higher type (which holds higher range of values or has
high precision). This type of conversion is also called “promotion”.
char C;
C = „A‟;
I = C;
Now the int Variable I holds the ASCII code of the char „A‟
Eg:5/2 = 2
2/5 = 0
5.0/2 = 2.5
2.0/50. = 0.4
5/2.0 = 2.5
2/5.0 = 0.4
5.0/2.0 = 2.5
2.0/5.0 = 0.4
int k;
yes
float a;
yes
Page 26
“Programming with C” course material
k= 5/2
k=2/5
a = 5/2
2.0
k=5.0/2
k=2.0/5
a = 5.0/2
2.5
k=55.0/2
k=2/5.0
a = 5/2.0
2.5
k=5.0/2.0
k=2.0/5.0
a = 2/5
0.0
a = 2.0/5
0.4
a = 2.0/0.5
0.4
WAP to read & display characters & strings Using unformatted I/O functions
main ( )
{ char ch,s[20] ;
gets (s);
O/P
press Special c
ch = *
Special char is
ch = z
You pressed
ch = 1
You pressed
1
C Language
Page 27
“Programming with C” course material
Explicit Type Conversion: When we want to convent a type forcibly in a way that is
different from automatic type conversion, we need to go for explicit type conversion.
Type name is one of the standard data type. Expression may be a constant variable Or an
expression this process of conversion is called as casting a value.
Y =( int) (a + b)
P = (double)sum/n
Basic Input output : C has many input output functions in order to read data from
input devices and display the results on the screen.
Formatted Functions: These functions read and write all types of data values. They require a
conversion symbol to indents the data type using these functions the O/P can be presented in
an aligned manner.
Classification:
I / O Functions
Formatted Unformatted
Input
Out Put
Input
Output
scanf ( )
printf( )
getch()
putch()
getche()
getchar ( )
puts ( )
Page 28
“Programming with C” course material
gets ( )
Data Type
Conversion symbol
Integer
Short integer
%d
or
%i
Short unsigned
%u
long signed
% ld
Long unsigned
% lu
Unsigned hexadecimal
%x
Unsigned octal
%0
real
float
%f
or
%g
double
% lf
signed character
%c
unsigned char
%c
string
%s
Escape Sequence
Use
ASC|| Value
\n
New line
10
\b
Backspace
\f
Form feed
12
\‟
Single Quote
39
\\
Back slash
92
\o
Null
0
\t
Horizontal tab
\r
Carriage return
13
\a
Alert
|?
Question marks
63
\“
Double Quote
34
Page 29
“Programming with C” course material
\v Vertical tab 11
a). scanf ( ) function is used to read values using key board. It is used for runtime assignment
of variables.
„&‟ is called the “address” operator. In scanf( ) the „&‟ operator indicates the memory location
of the variable. So that the Value read would be placed at that location.
Eg: Program
main ( )
Percentage = 69.200000
printf( ) examines the format string from left to right and prints all the characters until it
encounter a „%‟ or „\‟ on the screen. When it finds % (Conversion Specifier) it picks up the
first value. when it finds „\‟ (escape sequence) it takes appropriate action (\n-new line). This
process continues till the end of format string is reached.
Eg: Program ( )
main ( )
float per;
Percentage = 69.200000
getchar ( ) function is used to read one character at a time from the key board
main ( )
char ch;
ch = M
When this function is executed, the computer will wait for a key to be pressed and assigns the
value to the variable when the “enter” key pressed.
Ex char ch = „M‟
putchar (ch);
The Computer display the value char of variable „ch‟ i.e M on the Screen.
getch ( ): function is used to read a char from a key board and does not expect the
When this function is executed ,computer waits for a key to be pressed from the dey board.
As soon as a key is pressed, the control is transferred to the nextline of the program and the
value is assigned to the char variable. It is noted that the char pressed will not be display on
the screen.
getche ( ): function is used to read a char from the key board without expecting the enter key
to be pressed. The char read will be displayed on the monitor.
Syntax: ch = getche ( );
Note that getche ( ) is similar to getch ( ) except that getche ( ) displays the key pressed from
the dey board on the monitor. In getch ( ) „e‟ stands for echo.
gets ( ) function is used to read a string of characters including white spaces. Note that wite
spaces in a strng cannot be read using scanf( ) with %s format specifier.
Ex: char S[ 20 ];
gets (S);
When this function is executed the computer waits for the string to be entered
Department of CSE, GIT, GU Page 33
“Programming with C” course material
Quite often, it is desirable to alter the sequence of the statements in the program depending
upon certain circumstances.
(i.e., we have a number of situations where we may have to change the order of execution of
statements based on certain conditions)
(or)
This involves a kind of decision making to see whether a particular condition has occurred or
not and direct the computer to execute certain statements accordingly.
Control the flow of execution as per the selection these conditions can be placed in the
program using decision-making statements.
if – else Statement
else – if Ladder
switch statement
for Loop
while Loop
do-while Loop
goto Statement
break Statement
continue Statement
The „if‟ statement is a powerful decision making statement and is used to control the flow of
execution of statements.
Syntax:
Statement; OR Statement;
In case the condition is false the compiler skips the lines within the “if Block”.
The conditional statement should not the terminated with Semi-colons (ie ;)
The Statements following the “if”-statement are normally enclosed in Curly Braces ie { }.
The default scope is one statement. But it is good practice to use curly braces even with a
single statement.
If the Test Expression / Conditions is TRUE, the Statement Block will be executed
If the Test Expression / Condition is FALSE, the Statement Block will be skipped and
Cond
ition False
True
if block
Rest of the program
Write a program to check equivalence of two numbers. Use “if” statement.
include<stdio.h>
include<conio.h>
void main( )
if((m-n)= =0)
getch();
Output:
If „true‟ the numbers are equal and the message is displayed as shown in the output.
It is observed that the if statement executes only when the condition following if is true.
Syntax:
else
}
Department of CSE, GIT, GU Page 37
“Programming with C” course material
Flow chart
ENTRY
TRUE
Test
FALSE
Expressio
n?
True Block
False Block
Statement
Statement
Rest of program
Example 1:
include<conio.h> main( )
int n; clrscr( );
if( (n%2)==0 )
else
Output:
Run 1:
Enter a number: 24
Enter a number: 17
Example 2:
Develop a program accept two numbers and find largest number and print.
include<stdio.h>
include<conio.h> main( )
if( a>b )
else
Output:
Run 1:
30
30 is largest number
174
Using of one if-else statement in another if-else statement is called as nested if-else control
statement.
When a series of decisions are involved, we may have to use more than one if-
Syntax:
if ( Test Condition1)
{
if ( Test Condition2)
Statement -1;
else
Statement -2;
else
if ( Test Condition3)
Statement -3;
}
else
Statement -4;
If Test Condition-1 is true then enter into outer if block, and it checks Test Condition-2 if it is
true then Statement-1 executed if it is false then else block executed i.e Statement-2.
If Test Condition -1 is false then it skips the outer if block and it goes to else block and Test
Condition-3 checks if it is true then Statement-3 executed, else Statement-4 executed.
Example 1:
Program to select and print the largest of the three float numbers using nested “if-else”
statements.
include<stdio.h>
include<conio.h> main( )
{
float a,b,c;
printf(“Enter Three Values:”); scanf(“%f%f%f ”, &a, &b, &c); printf(“\n Largest Value is:”) ;
if(a>b)
if(a>c)
printf(“ %f ”, c);
else
if (b>c)
printf(“ %f ”, c);
getch( );
Output:
Run 1:
3.87
Run 2:
78.34
145.86
Run 3:
8.0
2.0
This is another way of putting if „s together when multiple decisions are involved.
A multipath decision is a chain of if ‟s in which the statement associated with each else is an
if.
Syntax:
else
When all the „n‟ conditions become false, then the final else containing the default statement
will be executed.
Flow Chart:
ENTRY
TRUE
Conditi
on -1
FALSE
Statement-1
TRUE FALSE
Conditi
Statement-2
TRUE
FALSE
Conditi
Statement-3
TRUE
FALSE
Conditi
Statement-n
Default
Statement-X
Next
Write a program to read three numbers and find the largest one by using “else-if” ladder.
include<stdio.h>
include<conio.h>
main( )
int a, b, c clrscr ( ) ;
st
printf(“Enter 1 number:”); scanf(“%d”, &a);
nd
printf(“Enter 2 number:”); scanf(“%d”, &b);
rd
printf(“Enter 3 number:”); scanf(“%d”, &c);
Output:
Run-1:
st
Enter 1 number: 52
nd
Enter 2 number: 74
rd
Enter 3 number: 90
Run-2:
st
Enter 1 number: 81
nd
Enter 2 number: 237
rd
Enter 3 number: 65
The selection is based upon the current value of an expression which is included within the
switch statement.
The switch statement requires only one argument of int or char data type, which is checked
with number of case options.
The switch statement evaluates expression and then looks for its value among the case
constants.
If the value matches with case constant, then that particular case statement is executed.
In switch each case block should end with break statement, i.e.
Syntax:
switch(variable or expression)
(or)
Statement-1;
break;
(or)
Statement-2;
break;
_
_
__
__
(or)
Statement-n;
break;
Statement;
The entire case structure following switch( ) should be enclosed with pair of curly braces { }.
If the case structure contains multiple statements, they need not be enclosed within pair of
curly braces.
When one of the cases satisfies, the statements following it are executed.
Flow Chart:
Switch variable
True
Body of
constant
False
Switch variable
True
Body of
constant
False
Body of
Exit
include<stdio.h>
include<conio.h>
main( )
printf(“\n \t = = = = = = = = = =”);
switch(ch)
case
1:
c = a+b ;
break;
case
2:
c=a-b;
break;
case
3:
c = a* b ;
break;
case
4:
c = a / b;
break;
case 5:
c = a % b;
break;
case
6:
if (a > b)
else if (b > a)
break;
case
7:
exit( );
break;
default:
getch ( );
Output:
========
MENU
========
[1] ADDITION
[5] REMAINDER
==============
Write a program to display the traffic control signal lights based on the following.
If user entered some other character then print THERE IS NO SIGNAL POINT.
include<stdio.h>
include<conio.h>
main( )
char L;
clrscr( );
scanf(“%c”, &L);
switch(L)
case „R‟:
case „Y‟:
case „G‟:
getch( );
Output:
Run-1:
Enter your Choice(R,r,G,g,Y,y): g
Run-1:
Write a program to convert years into (1) Minutes (2) Hours (3) Days (4) Months (5) Seconds. Using switch ( )
Statements.
include<stdio.h>
include<conio.h>
main( )
clrscr( ) ;
printf(“\n [1] MINUTES \n [2] HOURS \n [3] DAYS \n [4] MONTHS \n [5] SECONDS \n
[6] EXIT \n Enter your Choice:”);
mon = yrs * 12; ds = mon * 30; hrs = ds * 24; min = hrs * 60; sec = min * 60;
switch(ch)
break;
getch ( ) :
Loop: A loop is defined as a block of statements which are repeatedly executed for certain
number of times.
The loop variable should be assigned with a starting and final value.
Each time the updated value is checked by the loop itself.
Increment / Decrement is the numerical value added or subtracted to the variable in each
round of the loop.
Syntax:
Statement-1;
Statement-2;
The initialization sets a loop to an initial value. This statement is executed only once.
The test condition is a relational expression that determines the number of iterations desired
or it determines when to exit from the loop.
When the condition becomes false the control of the program exits from the body of for loop
and executes next statements after the body of the loop.
The updation(increment or decrement operations) decides how to make changes in the loop.
The body of the loop may contain either a single statement or multiple statements.
Syntax
Output
Remarks
(i) for (; ; )
Infinite to loop
No arguments
Infinite loop
decreased.
(iii) for (a=0; a<=10; a++)
Displays value
printf(“%d”, a)
from 1 to 10
Displays value
printf(„%d”,a);
from 10 to 0
Print the first five numbers starting from one together with their squares. #include<stdio.h>
#include<conio.h> main( )
int i; clrscr( ) ;
Output :
Program to display from 1 to 15 using for loop and i=i+1.
include<stdio.h>
include<conio.h> main( )
int i; clrscr( );
}
Output :
7
8
10
11
12
13
14
15
i.e. one for statement within another for statement is allowed in C. (or „C‟ allows multiple
for loops in the nested forms).
In nested for loops one or more for statements are included in the body of the loop.
Syntax:
Body of loop;
The outer loop controls the rows while the inner loop controls the columns.
-----------------------------------------
{
for (column =1;column<=colmax; ++ column)
printf( “\n”);
------------------------------------
include<stdio.h>
include<conio.h>
void main( )
int a, b, sub;
clrscr( );
for(b=1;b<=2;b++)
sub = a – b;
getch( );
Output:
a=3
b =1
a-b =2
a=3
b =2
a-b =1
a=2
b =1
a-b =1
a=2
b =2
a-b =0
a=1
b =1
a-b =0
a=1
b =2
a-b =-1
Programs on
“for” LOOP:
Print the first 5 numbers starting from one together with their squares and cubes.
include<stdio.h>
include<conio.h>
main( )
int i;
clrscr( ) ;
getch( );
Output:
include<stdio.h>
include<conio.h>
main ( )
scanf( “ %d %d %d %d %d %d”, &a, &b, &c, &d, &e); printf( “ \ n Numbers in Ascending
Order is :”)
Sum = a + b + c + d + e;
if(i = = a || i = =b || i = = c || i = = d || i = = e)
getch();
Output:
4 5 7 8
**
***
****
include<stdio.h>
include<conio.h> main ( )
int x, i, j ;
printf(“How many lines stars (*) should be print f? :”); scanf(“%d”, &x);
printf( “*”);
printf( “ \n”);
getch( );
Output:
**
***
****
12
123
1234
4321
321
include<stdio.h>
include<conio.h> main( )
printf(“ \n”);
getch( );
Output:
Enter value of X : 4
12
123
1234
(2) The “ while ” loop:
Syntax:
Updaion Expression
The test condition is evaluated and if the condition is true, then the body of the loop is
executed.
The execution process is repeated until the test condition becomes false and the control is
transferred out of the loop.
On exit, the program continues with the statement immediately after the body of the loop.
The braces are needed only if the body contains two or more statements.
It‟s a good practice to use braces even if the body has only one statement.
=========
Sum = 0; \ * Initialization * / n = 1;
while(n<=10) \* Testing * /
{
Sum = Sum + n * n;
n = n+1; \* Incrementing * /
==========
Program to add 10 consecutive numbers starting from 1. Use the while loop.
# include<stdio.h>
# include<conio.h>
main( )
clrscr( ) ;
while(a<=10)
Ouput:
Program to calculate factorial of a given number use while loop.
include<stdio.h>
include<conio.h> main ( )
while(n>=1)
{
fact = fact*n; n - - ;
Output :
/* logic 5 * 4 * 3 * 2 * 1 = 120 */
Page 64
“Programming with C” course material
The do-while loop will execute at least one time even if the condition is false initially.
Syntax:
Initialization Expression; do
---------------------------
------------
I=1;
/ * initializing * /
Sum=0;
do
Sum = Sum + I;
I = I +2; / * increment * /
-------------------------------------------------
include<stdio.h>
include<conio.h>
main( )
printf( “Enter the number for testing (prime or not”); scanf(“%d”, &n);
do
if(n%x = = 0)
x++;
}
Output:
include<stdio.h>
include<conio.h>
main( )
int a, fact = 1;
clrscr( );
do
fact = fact * a; a - -;
Output:
i.e., the break statement is used to terminate loops or to exit from a switch.
Example:
break;
break;
break;
default: printf(“Error”);
Notice that each group of statements ends with a break statement, (in order) to transfer
control out of the switch statement.
The last group does not require a break statement; since control will automatically be
transferred out of the switch statement after the last group has been executed.
The continue statement is used to bypass the remainder of the current pass through a loop.
Instead, the remaining loop statements are skipped and the computation proceeds directly to
the next pass through the loop.
The continue statement can be included within a while, a do-while, a for statement.
The continue statement tells the compiler “Skip the following Statements and continue with
the next Iteration”.
In „while‟ and „do‟ loops continue causes the control to go directly to the test – condition
and then to continue the iteration process.
In the case of „for‟ loop, the updation section of the loop is executed before test-condition, is
evaluated.
--------
if ( - - - - - - -)
continue;
--------------------
--------------------
}
do
--------------------
if ( - - - - - -
continue;
-------------------
-------------------
} while(test – condition);
(3)
{
----------
if( - - - - - -
-)
continue;
-------------------
-------------------
}
Program to show the use of continue statement
printf(“you have entered a negative number”); continue ; /* skip the remaining part of loop */
sum + = num;
Run 1:
Enter an integer: 7
Enter an integer: 3
Enter an integer: 10
Enter an integer: 15
Enter an integer: 30
Enter an integer: 10
Enter an integer: 15
Enter an integer: 30
* Create an infinite for loop. Check each value of the for loop. If the value is even, display it
other wise continue the iterations. Print “Even” numbers from 1 to 21. Use break statement to
terminate the program.
# include<stdio.h>
Department of CSE, GIT, GU Page 70
“Programming with C” course material
int i = 1; clrscr( ) ;
else if( i % 2 = = 0)
continue;
else
{
i++ ; continue;
getch( );
Output:
= = = = = = = = = = = = = = = = = = = = = = == = = =
2 4 6 8 10 12 14 16 18
C supports the “goto‟ statement to branch unconditionally from one point to another in the
program.
Although it may not be essential to use the “goto” statement in a highly structured language
like „C‟, there may be occasions when the use of goto is necessary.
The goto requires a label in order to identify the place where the branch is to be made.
The label is placed immediately before the statement where the control is to be transferred.
The label can be any where in the program either before or after the goto label statement.
goto label;
label:
-------------
Statement;
-------------
------------
-------------
------------
label:
------------
-------------
------------
Statement;
goto label;
Forward Jump
Backward Jump
is met, the flow of control will jump to the statement immediately following the label
If the “label:” is before the statement “goto label;” a loop will be formed and some statements
will be executed repeatedly. Such a jump is known as a „backward jump‟.
If the “label:” is placed after the “goto label;” some statements will be skipped and the jump
is known as a “forward jump”.
* Write a program to detect the entered number as to whether it is even or odd. Use goto
statement.
include<stdio.h>
include<conio.h>
int x; clrscr( );
else
odd:
Output:
The approach or method that is used to solve a specific problem is known as an Algorithm.
A set of pseudo code or broken English steps written sequentially to solve a problem is termed
as on algorithm.
Any documentation that clearly holds the procedure of problem solving, including pictorial
representations are termed as algorithms.
Example:
Step 1:
start
Page 73
“Programming with C” course material
Step 2: - - -
Step 3: - - -
Step 4: stop
FLOW CHART:
The most common method of describing an algorithm is through the use of flowcharts.
All the operations to the performed and all the paths of processing to be followed while
solving problem are indicated in a flow chart.
I/O Operations
Beginning
Ending
Conditional
Flow Line
statement to
be tested
Conditional
statement to
be tested
Predefined process
or module/
Connector
Loops
Repeat
under
Example (1):
# include<stdio.h> main( )
clrscr( );
/* A message is displayed on the monitor indicating the action to be taken by the user */
printf( “ \n a = %d \t b = %d ”, a,b);
Flow Chart:
Start
Input
Sum = a + b
Stop
Example (2):
include<stdio.h>
include<math.h> main( )
clrscr( ) ;
rd
printf( “such that sum of any 2 sides is greater than 3 side \n”); scanf(“ %f %f %f ”, &a, &b,
&c);
\t b = %f \t c=%f ”, a , b , c);
s = (a+b+c)/2;
/* computing value of
s */
/* computing area */
Start
Flow Chart:
Input a,b,c
S= (a+b+c) /2
Area = s(s a) * (s b)(s c)
Example (3):
# include<stdio.h>
# include<conio.h>
main( )
clrscr( ) ;
printf(“ \n a = %d \t b= %d ”, a,b);
temp = a;
a=b;
b = temp; /* swapping contents of a & b */
Flow Chart:
Start
a=b
Input values
b=temp
a&b
Output the
of a & b with
values of a & b
suitable message
with suitable
Temp=a
Stop
Page 77
“Programming with C” course material
Introduction :
Functions are subprograms which are used to compute a value or perform a task. They cannot
be run independently and are always called by the main ( ) function or by some other
function.
User–designed functions
Library or built-in functions are used to perform standard operations eg: squareroot of a
number sqrt(x), absolute value fabs(x), scanf( ), printf( ), and so on. These functions are
available along with the compiler and are used along with the required header files such as
math.h, stdio. h, string.h and so on at the beginning of the program.
User defined functions are self–contained blocks of statements which are written by the user
to compute a value or to perform a task. They can be called by the main() function repeatedly
as per the requirement.
USES OF FUNCTIONS :
Functions are very much useful when a block of statements has to be written/executed again
and again.
Functions are useful when the program size is too large or complex.Functions are called to
perform each task sequentially from the main program. It is like a top-down modular
programming technique to solve a problem
Functions are also used to reduce the difficulties during debugging a program
In C language, functions are declared to compute and return the value of specific data type to
the calling program. Functions can also written to perform a task. It may return many values
indirectly to the calling program and these are referred to as void functions.
FUNCTION DECLARATION :
--------------------
--------------------
Where type is the data type of the value return by the function and arguments expected.
arg1, arg2…. argn are the arguments which are variables which will receive values form the
calling program, name is the name of function by which the function is called by the calling
program.
There is a local declaration of variables. These variables are referred as local variables, are
used only inside the function. The statement block consists of a set of statements and built-in
functions which are executed when the function is called. The result is returned to the calling
program through a return statement that normally appears at the end of a function block. This
function block starts and ends with braces { }.
Function main() :
main() is the starting function for any C program. Execution commences from the first
statement in the main () function
It returns int value to the environment that called the program. Usually zero is returned for
normal termination of the main(). Non zero is returned to convey abnormal termination
Only the function body varies from programmer to programmer main (). Function heard
follows the common syntax by either having no parameter or only two standard parameters.
The program execution ends when the closing brace of the in main is reached.
FUNCTION PROTOTYPE :
When a C program is compiled, the compiler does not check for data type mismatch of actual
arguments in the function call and the formal arguments in the function declaration. To enable
the compiler to check the same, a function prototype declaration is used in the main program.
Passing of values between the main program and the function takes place through arguments.
The arguments listed in the function calling statements are referred to as actual arguments.
These actual values are passed to a function to compute a value or to perform a task.
The arguments used tin the function declaration are referred as formal arguments. They are
simply formal variables that accept or receive the values supplied by the calling function.
Note: The number of actual and formal arguments and their data types should match.
The function call sends two integer values 10 and 5 to the function
The function computers the product x and y assigns the result to the local variable p, and then
returns the value 25 to the main() where it is assigned to y again..
A function has a statement block which is called by the main( ) or any other function.
When the data type in a function declaration is omitted the function will return a value of the
type integer.
The data type of the formal argument may be declared in the next line which follows the
function declaration statement.
The parameter list declares the variables that will receive the data sent by the calling
program.
They serve as input data to the function to carry out the specified task. Since they represent
actual input values, they are often referred to as formal parameters.
FUNCTION CALLS:
A function can be called by simply using the function name followed by a list of actual
parameters (or arguments)
main()
{ int y ;
p= x * y ;
return(p);
When the compiler encounters a function call the control is transferred to the function mul(),
this function is then executed line by line as described and the value of p is returned when the
return statement is encountered. This value is assigned to y.
Examples:
float quadratic ( int a , (n+b, )n+c) {………} double power 9double x, int n) {……….} float mul
(float x, float y) {………..}
The declaration of parameter variables cannot be combined int sum (int a,b) is invalid.
A function need not always receive values form the calling program. In such cases, functions
have no formal parameters,
To indicate that the parameter list is empty we use the keyword void between parenthesis as
void printline(void)
This function neither receives any input values nor returns back any value.
Many compilers accept an empty set of parenthesis without specifying anything as void
printline ( )
Note:
The parameter names do not need to be the same in the prototype declaration and the function
definition.
The types must match the types of parameters in the function definition in number and order.
The return type is optional, when the function returns int type data.
When the declared type do not match with the types on the function definition compiler will
produce an error.
A function can accept more than one parameter. The parameters are separated by commas.
For example, consider the following program having a function maxfunc() that accepts three
parameters and computes their maximum.
int max ;
max = i ;
else if (j> = k)
max = j;
return max;
void main ( )
int m, a,b,c;
m= maxjunc (a,b,c);
Run:
Input 3 numbers: 4
Department of CSE, GIT, GU Page 83
“Programming with C” course material
The maximum is 6
The main function calls the function maxfunc(). Three integer variables passed to it are
separated by commas. The return value is assigned to m and is displayed. Since maxfunc()
comes before the function main separate function and function definition are unnecessary.
The variables m,a,b and c are declared in main. They can be used only in the function main.
An attempt to use them in maxfunc() causes a compile time error. Similarly, the variables
max,i,j and k (i,j,k being the parameters which the function accepts) belong to the maxfunc().
These variables cannot be accessed in main. The region of the program where an identifier
can be accessed is called the “Scope of the identifier”. Thus the scope of „a‟ is the function
main, while the scope of i is the function maxfunc().
The variables with the same name can exist in both main and maxfunc().
We used the functions such as printf and scanf which are already written, compiled and
placed in the C-library and are called library functions.
Functions which can be defined by the user are called user defined functions.
Passing arguments
Return statement
Function call
Parts of function :
A function declaration can appear outside all the other functions. In this case all functions
know about the other function declarations and can call this function. Functions can also be
declared within other functions. In this case only the function within which the declaration is
present will know about it.
Ex:
void main()
int i;
Parts of a function
void main( )
{
void func1(); function declaration
…………….
…………….
…………….
…………….
void func1()
……………
……………
}
Department of CSE, GIT, GU Page 85
“Programming with C” course material
Function declaration:
The number and the type of arguments that must be supplied in a call to the function.
When a function call is encountered, the compiler checks the function call with its
declaration. So that correct argument types are used. A function declaration has the following
syntax:
return type specifies the data type of the value in the return statement. A function can return
any data type , if there is no return value, the keyword void is placed before the function
name. The function declaration terminates with a semicolon.
Function definition:
The function definition is similar to the function declaration but does not have the semicolon.
The first line of the function definition is called a function declarator. This is followed by the
function body. It is composed of the statements that make up the function, delimited by
braces. The declarator and declaration must use the same function name, number of
arguments, arguments types, and the return type. No function definition is allowed with in a
function definition.
Ex:
void main(void)
A function can contain any number of statements.The statements are enclosed with in curly
braces { and }. The function definition may include declarations of variables and declaration
of other functions. Note that the return statement need not enclose the return value with in
parenthesis.
Elimination of function declaration:
The programmer can place function declarations anywhere in the program. If the functions
are defined before they are called, then the declarations are unnecessary.
Ex:
#include <stdio.h>
return a>b ? a: b;
void main ()
Functions in C may or may not return values. If a function does not return a value the return
type in the function definition and declaration is specified as void. Otherwise, the return type
is specified as a valid data type.
main()
}
The function squareint is called and the return value is assigned to the variable sq. the control
is returned to the printf statement after the statements with in the function definition of
squareint are executed.
FUNCTION PARAMETERS:
Function parameters are the means of communication between the calling and the the called
function. They can be classified into formal parameters and actual parameters. The formal
parameters are the parameters given in the function declaration and function definition. The
actual parameters, often known as arguments, are specified in the function call.
Ex:
return a+b;
void main(void)
Department of CSE, GIT, GU
Page 88
“Programming with C” course material
int x,y,z;
z = sum (x,y);
Statement/Statements ;
return; /* optional since it is at the end of the in anyway and the in has no ref value */
The definition of a function that returns a value of type . Type name has the following syntax:
Typename Functionname (parameterlist)
Statement/Statements ;
return value; /* return keyword must be used. And it must be followed by a value
Even in case of functions having return values multiple return statements can exist. Parameter
Function Call :
A function call is specified by the function name followed by the values of the parameters
enclosed with in parenthesis, terminated by a semi colon (;).
return x * x;
There are two ways in which we can pass arguments to the function:
Call by value
Call by reference.
Call by value :
In this type value of actual arguments are passed to the formal arguments and the operation is
done on the formal arguments. Any changes made in the formal arguments does not effect the
actual arguments because formal arguments are photocopy of actual arguments. Hence when
the function is called by the call by value method, it does not effect the actual contents of the
actual arguments. Changes made in the formal arguments are local to the block of called
function. Once control returns back to the calling function the changes made vanish.
clrscr();
change(x,y) ;
return 0;
change(int a, int b)
b=k;
In the above program, the variables a and b defined in function definition are known as
formal parameters or dummy parameters or place holders. The variables x and y are actual
parameters, they specify the values that are passed to the function change x and y are
arguments in the function change x and y arguments in the function call.
The number of arguments in the function call and the function declarator must be the same.
The date type of each of the arguments in the function call should be the same as the
corresponding parameter in the function declaration statement.
The names of the arguments in the function call and the names of parameters in the function
definition can be same or different.
Category of functions : A function, depending on whether arguments are present or not and
whether a value is returned or not may belong to one of the following categories.
-when a function has no arguments, it does not receive any data from the calling function
-when a function does not return a value, the calling function does not receive any data from
the called function.
-There is no data transfer between the calling function and the called function.
The main function has no control over the way the functions receive input data.
we shall modify the definitions of both the called functions to include arguments as follow.
void printline(char ch)
The calling function can now send values to there arguments using function calls containing
appropriate arguments
For example the function call value (500, 0.12, 5) would send the values 500,0.12 & 5 to the
function void value (float p float r, int n) and assigns 500 to p, 0.12 to r and 5 to n values 500,
0.12 and 5 are the actual arguments, which become the values of the formal arguments inside
the called function. The actual and formal arguments should match in number, type and order.
The values of actual arguments are assigned to the formal arguments on a one to one basis,
starting with the first argument.
The function value in previous program receives data from the calling function through
arguments. But does not send back any value.
Sometimes, different programs may require different output formats for displays of results.
There short comings can be overcome by handling over the result of a function to its calling
function where the returned value can be used as required by the program
A self contained and independent function should behave like a „black box‟ that receives a
predefined form of input and output a desired value
Such functions will have two way data communications between them
clrscr();
getch( );
if(k = = 1)
return(1);
else
When the program is executed, the user has to enter value of n and r. The function is called to
find factorials of n, r, and (n-r). The value for ncr is obtained and printed as shown below
Recursion :
A function calling itself again and again to compute a value is known as recursive function or
recursion function or recursion. Normally a function is called by the main program or by
some other function but in recursion the same function is called by itself repeatedly.
Recursion is useful for branching process. Recursion helps to create short code that would
otherwise be impossible .
Program: Write a recursive fuction to find the factorized of a given integer. Use it to find ncr
= n1 r1 (n-r);
1.Write a function to add two matrices of order m x n. also write main program which can
road the values of the matrices and print the resultant matrix.
include ,stdio‟h>
include <con:o.n>
main ( )
{
void matadd( ); clrscr();
printf(“ in how many rows and (columns?”)‟ scanf(“ %d % d; & m, & n);
matadd(); /* call function * printf(“in resultant matrix is /n “); for (i=d; i<m; i+ +)
getch ( );
When this program is executed, the user has to enter the order of matrix m and n and the
values of the matrices. A sample input and out put of the program is
-2
-5
Resultant matrix is
-1
2.Write a function in C to find the GCD of two integers. 13 Using the function, write a
program to find the GCD of 3 integers
include <stdio.h>
include <coni0.h>
main()
printf(“ in Enter three integers : “); scanf (“%d %d ; & a, & b, & c); d1 = gcd(a,b);
d2 = gcd (a,c)
else
else
printf („in greatest common divisior is %d”, gcd (d1,d3)); printf (“ in in press any key to
continue… “);
nr= x; dr = y;
When the program is executed, the user has to enter the three integers. The function is called
to find the common divisor in (a,c), (A,C) and (b,c). if the GCD obtained in these three calls
are equal then the GCD will be displayed. Otherwise the function is called to find the
common divisor in (d1,d3) or (d1,d2) to print the greatest common divisor
o.p:
3.Write a C program which calls a function reverse ( ) which excepts a string and displays its
reverse.
The string is read in the main program and the function called with this string as an argument
to print the reverse of the string
include < stdio‟h>
main ()
char s((20);
clrscr();
getch ( );
int i,j;
j++;
}
When this program is executed, the user has to enter a string and the reverse of string will be
printed .
o/p:
Objective Questions
[c]
Page 98
“Programming with C” course material
(d) none
2.
[b]
(a) iteration
(b) recursion
(d) none
3.
Declaration of a function name along with the type and optional dummy arguments at the
[c]
(c) prototype
5. Variables declares inside the body of a function or main program are reserved as
[a]
(a) return x
(b) return 0
Page 99
“Programming with C” course material
9. The meaning of keyword void before the function name means [a]
any value
Call by reference :
In this type instead of passing values, addresses are passed. Function operates on addresses
rather than values. Here the formal arguments are pointers to the actual arguments. In this
type , formal arguments point to the actual argument. Hence changes made in the arguments
are permanent.
main ( )
clrscr();
int * k; *k = *a; *a = * b; *b = * K;
In change ( ) x = 4 y = 5
ARRAYS
The fundamental data types, namely char, int, float, double are used to store only one value at
any given time.
Hence these fundamental data types can handle limited amounts of data.
In some cases we need to handle large volume of data in terms of reading, processing and
printing.
To process such large amounts of data, we need a powerful data type that would facilitate
efficient storing, accessing and manipulation of data items.
„C‟ supports a derived data type known as array that can be used for such applications.
Arrays:
data
type.
It is simply grouping of like type data such as list of numbers, list of names
etc.
Array:
Or
Types of Arrays:
* We can use arrays to represent not only simple lists of values but also tables of data in two
or three or more dimensions.
Multidimensional arrays
Like any other variables, arrays must be declared before they are used. The general form of
array declaration is
Syntax:
<datatype> <array_name>[sizeofarray];
The datatype specifies the type of element that will be contained in the array, such as int,
float, or char.
The size indicates the maximum number of elements that can be stored inside the array.
Examples:
float height[50];
Declares the height to be an array containing 50 real elements. Any subscripts 0 to 49 are
valid.
int group[10];
Declares the group as an array to contain a maximum of 10 integer constants.
char name[10];
Declares the name as a character array (string) variable that can hold a maximum of
10 characters.
To represent a set of five numbers, say (35, 40, 20, 57, 19) by an array variable
“number”.
int number[5];
number [0]
number [1]
number [2]
The values to the array elements can be assigned as
number[0] = 35;
number[1] = 40;
number[2] = 20;
number[3] = 57;
number[4] = 19;
35
number[0]
40
number[1]
20
number[2]
57
number[3]
number[4] 19
Valid Statements :
a = number[0] + 10;
value[6] = number[i] * 3;
Example-1: Write a program to print bytes reserved for various types of data and space
required for storing them in memory using array.
include<stdio.h>
include<conio.h> main ( )
printf(“the type „int‟ requires %d bytes”, sizeof(int)); pirntf(“ \n The type „char‟ requires %d
bytes”, sizeof(char)); printf(“ \n The type „float‟ requires %d bytes”, sizeof(float));
printf(“ \n %d memory locations are reserved for ten „int‟ elements”, sizeof(a)); printf (“ \n
%d memory locations are reserved for ten „char‟ elements”,sizeof(c)); printf (“ \n %d
memory locations are reserved for ten „float‟ elements”,sizeof(b)); getch( );
Output:
20 memory locations are reserved for ten „int‟ elements 10 memory locations are reserved for ten
„char‟ elements
Example-2: Write a program using a single subscripted variable to read and display the array
elements.
include<stdio.h>
include<conio.h> main( )
int i ;
float x[10];
{
scanf(“ %f ”, &x[i]);
getch( );
}
Output:
1.1
2.2
3.3.
4.4
5.5
6.6
7.7
8.8
9.9
10.10
Page 105
“Programming with C” course material
1.1 2.2 3.3. 4.4 5.5 6.6 7.7 8.8 9.9 10.10
char 1 byte
int 2 bytes
float 4 bytes
long 4 bytes
double 8 bytes
At compile time
At run time.
We can initialize the elements of arrays in the same way as the ordinary variables when they
are declared.
Example:
i.e., we will declare the variable number as an array of size 3 and will assign zero to each
element.
If the number of values in the list is less than the number of elements, then only that many
elements will be initialized.
Department of CSE, GIT, GU Page 106
“Programming with C” course material
In such cases, the compiler allocates enough space for all initialized elements. Ex:
This will declare the counter array to contain four elements with initial values 1.
This declares the name to be an array of five characters initialized with the string
Compile time initialization may be partial. i.e., the number of initializers may be less than the
declared size. In such cases the remaining elements are initialized to zero, if the array type is
numeric.And NULL if the type is char.
Will initialize the first two elements to 10 & 20 respectively and the remaining elements to
zero.
Similarly
will initialize the first element to „B‟ and the remaining four to NULL.
If we have more initializers than the declared size, the compiler will produce an error.
-----
-----
if (i<50)
Department of CSE, GIT, GU Page 107
“Programming with C” course material
else
-----------
Here the first 50 elements of the array “sum” are initialized to zero.
Ex:
int x[3];
This will initialize array elements with the values entered through the key board.
Hence by using NULL character compiler detects the end of the character array.
Example-1:Write a program to display character array with their address.
include<stdio.h>
clrscr( ) ;
Output:
4054
4055
4056
4057
4058
Example-2: Program to find out the largest and smallest element in an array.
int i,n;
large = a[ i ];
small = a[ i ];
printf(“\n Largest element in vector is %8.2f \n”, large); printf(“ \n smallest element in vector
is %8.2f \n”, small); getch( );
Output:
Size of vector : 7
Vector elements
34.00 – 9.00 12.00 10.00 - 6.00 0.00 36.00 Largest element in vector is 36.00
Example-3:
include<stdio.h>
include<conio.h>
main( )
{
int i,j,k,n;
if(a[ i ] > a[ j ])
temp = a[ i ]; a[ i ] = a[ j ]; a[ j ] = temp;
printf(“\n vector elements in ascending order : \n”); for( i=0; i<n; i++)
Output:
Size of Vector : 8
Vector elements are
91.00
20.00
1.00
7.00
34.00
11.00
-2.00
6.00
-2.00
1.00
6.00
7.00
11.00
20.00
34.00
91.00
There could be situations where a table of values will have to be stored. Consider a student
table with marks in 3 subjects.
Student
Mat
Phy
Chem.
Student # 1
89
77
84
Student # 2
98
89
80
Student # 3
75
70
82
Student # 4
60
75
80
Student # 5
84
80
75
The above table contains a total of 15 values.
Here V denotes the entire matrix Vij refers to the value in “ i ”th row and “ j ”th column.
EXAMPLE:
Definition:
A list of items can be given one variable name using two subscripts and such a variable is
called a two – subscripted variable or a two – dimensional array.
int V[5][3];
column -0
column-1
column -2
[0] [0]
[0] [1]
[0]
[2]
Row. 0
89
77
84
[1] [0]
[1] [1]
[1]
[2]
Row. 1
98
89
80
[2]
[0]
[2] [1]
[2]
[2]
Row. 2
75
70
82
[3]
[0]
[3] [1]
[3]
[2]
Row. 3
60
75
80
[4] [0]
[4] [1]
[4]
[2]
Row. 4
84
80
75
Initializing Two- Dimensional Arrays:
Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
This initializes the elements of first row to zero and the second row to one. This
initialization is done row by row.
we can also initialize a two – dimensional array in the form of a matrix as shown.
int table[2][3] = {
{0,0,0},
{1,1,1}
};
Commas are required after each brace that closes of a row, except in case of last row.
If the values are missing in an initializer, they are automatically set to zero. Ex: int table [2]
[3] = {
{1,1},
{2}
};
Page 113
“Programming with C” course material
This will initialize the first two elements of the first row to one,
The first element of the second row to two and all other elements to zero.
When all the elements are to be initialized to zero, the following short-cut method may be
used.
The first element of each row is explicitly initialized to zero while the other elements are
automatically initialized to zero.
int m[3][5] = { 0, 0 };
include<stdio.h>
include<conio.h>
void main( )
int i,j;
Output:
Elements of an Array
6
Department of CSE, GIT, GU
Page 114
“Programming with C” course material
7 8 9
Write a program to display 2-Dimensional array elements together with their addresses.
include<stdio.h>
int i,j;
clrscr( );
printf(“col-0
col -1
col-2
\n”);
prinf(“--------
--------
------- \ n”);
printf(“Row 0\t”) for( i=0; i<3; i++)
getch( );
Output:
Col – 0
col – 1
col -2
Row 0
1 [4052]
2[4054]
3[4056]
Row 1
4 [4058]
5[4060]
6[4062]
Page 115
“Programming with C” course material
(3) Program to read the matrix of the order upto 10 x 10 elements and display
include<stdio.h>
printf(“\n Enter Matrix Order upto (10 x 10) A :”); scanf(“ %d %d ”, &row, &col);
printf(“ %d ”, a[ i ][ j ]);
printf(“\n”);
getch( );
Output :
4
The matrix is
(4) Program read the elements of the matrix of the order upto 10 x 10 & transpose its
elements.
include<stdio.h>
printf(“ \n Enter order of matrix upto (10 x 10) A:”); scanf(“ %d %d ”, &row, &col);
printf(“\n Enter Elements of matrix A: \n”); for( i=0; i < row; i++)
/* transposing logic simply copying one matrix elements to another in reverse order */
{
for( j=0; j<col; j++) printf(“%d”, b[ i ][ j ]);
printf (“ \ n”);
getch( ); }
Output:
5
8
Program to perform addition and subtraction of two matrices. Whose orders are upto
10 x 10.
include<stdio.h>
include<conio.h>
main(
int
clrscr( );
Page 117
“Programming with C” course material
}
printf(“n Matrix Subtraction/Difference \n”); for( i=0; i < r1; i++)
getch( );
Output:
5
0
Matrix Addition
13
14
12
16
Matrix Subtraction
Page 118
“Programming with C” course material
-4
(6) Write a C program to multiply A matrix of order mxn with B matrix of order nxl.
Solution: Consider two matrices A and B of order 2 x 2. Multiply them to get the
resultant matrix C.
2
26
2
4
14
0
4
5
16
20
include<stdio.h>
include<conio.h>
include<math.h> main( )
scanf(“%d”, &a[ i ][ j ]); printf(“\n Enter order of B matrix:”); scanf(„%d %d”, &n,
&l);
c[ i ][ j ] = 0;
c[ i ][ j ] = c[ i ][ j ] +a[ i ][ k ] * b[ k ][ j ];
/* loop to print resultant matrix */ printf(“ \n Resultant matrix is \n”); for( i=0; i<m; i+
+)
getch ( ) ;
Explanation:
When this program is executed, the user has to first enter the order (min) of
matrix and its values and its values. The innermost loop
c[ i ][ j ] = c[ i ][ j ] + a[ i ][ k ] * b[ k ][ j ];
This is repeated in the outer loops to get the other elements in the resultant matrix.
Output:
Enter A matrix
-2
Enter B matrix
-5
Resultant matrix is
14
-20
Write a C program to find the trace of a given square matrix of order mxm.
Solution
We know that the trace of a matrix is defined as the sum of the leading
diagonal
elements.
Ex:
3
1
A 4
6
include<stdio.h>
include<conio.h> main( )
printf (“\n Enter order of the square matrix :”) ; scanf (“%d”, &m);
/* loop to read values of A matrix * / printf (“ \n Enter the matrix \n”); for( i=0; i<m;i+
+)
sum = sum + a[ i ][ i ];
When this program is executed, the user has to enter the order m & values of the given
matrix.
The index variable of loop i is used for row & column subscripts to represent the
diagonal elements.
Output :
-1
A list of items can be given one variable name using more than two subscripts and such a
variable is called Multi – dimensional array.
A list of items can be given one variable name using three subscripts and such a variable is
called Three – dimensional array.
Declaration of Three-Dimensional Arrays :
Syntax:
The datatype specifies the type of elements that will be contained in the array, such as int,
float, or char.
This initializes the elements of first two dimensional(matrix) first row to zero‟s and the
second row to one‟s and second matrix elements are first row to six‟s and the second row to
seven‟s.
we can also initialize a two – dimensional array in the form of a matrix as shown.
int table[2][3] = {
{0,0,0},
{1,1,1}
},
{6,6,6},
{7,7,7}
};
Department of CSE, GIT, GU Page 122
“Programming with C” course material
STRING MANIPULATIONS IN C
The control character „\0‟ which represents a null character is placed automatically at
the end of any string used.
strlen( ) function
strcpy( ) function
strcat( ) function
strcmp( ) function
int n;
This will return the length of the string 9 which is assigned to an integer variable n.
Note that the null charcter „\0‟ available at the end of a string is not counted.
char city[15];
strcpy(city, “BANGALORE”) ;
This will assign the string “BANGALORE” to the character variable city. * Note that
character value like
are
Ex:
Page 123
“Programming with C” course material
city
pin
strcat
;
This will join the two strings and store the result in city as “BANGALORE – 560001”.
Note that the resulting string is always stored in the left side string variable.
strcmp( ) Function:
value
of the strings
being compared.
This will return an integer value „- 10‟ which is the difference in the ASCII
values of
* Note that the integer value obtained as the difference may be assigned to an
integer
variable as follows:
int
n;
n=
strcmp(city, town);
We use scanf ( ) function to read strings which do not have any white spaces. Ex:
scanf(“ %s ”, city );
When this statement is executed, the user has to enter the city name
(eg “NEWDELHI”) without any white space (i.e not like “NEW DELHI”).
The white space in the string will terminate the reading and only “NEW” is assigned
to city.
To read a string with white spaces gets( ) function or a loop can be used as.
gets(city);
do … while loop
= 0;
do
while(ch ! = „ \n ‟) ;
i - - ; city[ i ] = „\0‟;
The copy or assign a single character to a string variable, the assignment can be
written as given below;
city[ i ] = „N‟;
Department of CSE, GIT, GU Page 124
“Programming with C” course material
When a string contains more than one character, the assignment is written as strcpy
(city, “NEW DELHI”);
atoi( ) Function:
atoi( ) function is a C library function which is used to convert a string of digits to the
integer value.
n = atoi(st);
This will assign the integer value 24175 to the integer variable n.
(1) Write a C program to count the occurrence of a particular character in the given
string.
Solution:
Program:
include<stdio.h>
include<conio.h>
include<string.h> main( )
count = 0;
When this program is executed, the user has to enter the string and the character to be
counted in the given string.
Output:
Solution
Program
include<stdio.h>
include<conio.h>
include<string.h> main( )
/* loop to count the vowels in the string * / for( i=0; i<strlen(st); i++)
switch(st [i ])
case „A‟: case „E‟: case „I‟: case „O‟: case „U‟: case „a‟: case „e‟: case „i‟: case
„o‟: case „u‟:
When this program is executed, the user has to enter the sentence.
Note that gets( ) function is used to read the sentence because the stirng has
white
Page 126
“Programming with C” course material
Note that a count++ statement is given only once to execute it for the cases in the
switch statement.
Output:
(3) Write a C program to test whether a given string is palindrome string. explain the
working of program.
Solution: Consider the string „LIRIL” when it is reversed, it reads again as “LIRIL”.
Any string of this kind is called a palindrome string. Few other palindrome strings
are
include<stdio.h>
include<conio.h>
include<string.h> main( )
{
char st[20], rst[20]; int i,j;
clrscr( );
j--;
else
St =
HYD E RAB AD
To reverse this string, the original string is copied from the last position & written as
i 01 23 4 5 6 7 8
rst =
ABA
H
The two strings are compared using a strcmp ( ) function which will return a 0 when
the original string and the reversed string are identical.
Output:
Alternative Method:
This program can also be written to compare the first character of the string with the
last, second with the second last and so on up to the middle of the string as shown.
0123 456 7 8
HYD E RAB AD
If all the characters are identical, then the string is a palindrome string.
(4) Write a C program to compare two strings which are given as input through
keyboard and print the alphabetically greater string.
Solution
The alphabetically greater string is the one whose ASCII value of the first letter is
greater than that of the second string.
St1 = “ALPHA”
St2 = “BEETA”
St2 is greater than st1 because the ASCII value of „B‟ in “BETA” is greater than that
of „A‟ in „ALPHA‟.
Note that when the first letters of the two strings are identical, the second letters of
the strings are compared.
include<stdio.h>
include<conio.h>
include<stirng.h> main( )
When this program is executed, the user has to enter the two strings.
Note that strcmp( ) function returns a positive value when string 1 is greater & a
negative value when string 2 is greater.
Output:
(5) Write a C program to read an array of names and to sort them in alphabetical order
(dictionary).
Solution:
Consider a list of names stored in a 2-Dimensional character array. Each
row
Names
6
7
A
K
N
I
N
Compare the name in the first row with the Second, then with the third name and so
on… till the smallest name ( & name starting with letter „A‟) moves to the first place.
Names
0
N
1
Now compose the second name with the third then with the fourth name & so on..
till the alphabetically second smallest name none to the second place.
Names
1
S
This procedure is repeated till the names are arranges in alphabetical order shown
below.
N
D
I
K
Step involved in arranging names in alphabetical order are given below. Step 1 : Read
n
Step 3 : Loop to arrange the names by comparison Step 4: Loop to print the arranged
list.
Step 5 : Stop
include<stdio.h>
include<conio.h>
include<string.h> main( )
clrscr( ):
When this program is executed, the user has to first enter the total no of names
Output:
SHERIN
SONIKA ARUN
ARUN
DEEPAK
SHERIN
SONIKA
Write a C program to convert a line in the lower case text to upper case.
Solution
a - 97 b – 98 …………………… z – 122
* Note that the difference between the lower and upper case letters (ie. – 32) is used
for conversion.
include<stdio.h>
include<conio.h>
include<string.h> main( )
/* loop to convert lower case alphabet to upper case * / for( i=0; i<strlen(st); i++)
OUTPUT:
Enter a sentence:
Logical thinking is a must to learn programming The converted upper case string is
(7) Write a C program to count no of lines, words and characters in a given text.
Solution:
A while loop is used to read the text. The character „$‟ is used to terminate the
reading of text.
Program
include<stdio.h>
include<string.h>
include<conio.h> main( )
{
char txt[250], ch, st[30]; int ins, wds, chs, i; clrscr( ) ;
st[ i ] = „\0‟ ;
while(txt[ i ]!=‟$‟)
switch(txt[ i ])
wds ++;
Department of CSE, GIT, GU Page 132
“Programming with C” course material
i++;
printf(“\n\n no of char (incl.blanks) = %d”, chs); printf(“\n No. of words = %d”, wds);
Output:
No of lines = 3.
Some „C‟ compilers will accept the following string handling functions which are
available in header files string.h and ctype.h
Functions:
m = -4
s1 will be “NewDel”.
* Note that the value „1‟ or positive integer will be returned when a condition is
true, and value „0‟ will be returned when condition is false.
Function:
islower(„n‟) 1
isalpha(„K‟) 1 isalpha(„+‟) 0
isalnum(„8‟) 1 isalnum(„y‟) 1
isalnum(„-‟) 0
Ex:
isdigit(„6‟)
isdigit(„a‟) 0
(vi) isxdigit( ) : To test if a character is a Hexa decimal number (0-9, A-F and a-f are
Hexa decimal digits)
Ex:
tolower(„A‟) a
toupper(„a‟) A.
POINTERS
INTRODUCTION:
DECLARATION:
To differentiate ordinary variables from pointer variable, the pointer variable should
Pointer variables must be declared with its type in the program as ordinary variables.
A variable can be declared as a pointer variable and it points to starting byte address of
SYNTAX:
Ex:
int * p, v;
float *x;
nd
In the 2 declaration x is a pointer variable of floating point data type.
2) Pointer variables are initialized by p= &v, it indicates p holds the starting address
of
integervariable v.
int v=20,*p;
20 1000
This address is stored in p. Now p holds address of v now *p gives the value stored at
the address pointer by p i.e *p=20.
IMPORTANT POINTS:
A pointer variable can be assigned to another pointer variable, if both are pointing to
the same data type.
A pointer variable cannot be multiplied or divided by a constant. Ex: p*3 or p/3 where
p is a pointer variable
One pointer variable can be subtracted torn another provided both winters points to
Elements on same away.
C allows us to add integers to or subtract integers from pointers. Ex: p1+4, p2-2, p1-p2
If both p1, p2 are pointers to same way then p2-p1 gives the number of
p++ & p- -
Page 136
“Programming with C” course material
Disadvantages:
Unless pointer is defined and initialized properly use of pointers may lead to
disastrous situations.
Program:
main ( )
P1=p2=p3=&x;
printf (“%d”,*p1);
printf (“%d”,*p3);
printf (“%d”, x);
Output : 10 10 10 10 10
Void Pointers :
We can declare a pointer to be of any data type void and can assign a void pointer to
any other type.
printf(“%d”,*p);
It given error because the pointer p is of type void and cannot hold any value. So we
have to type cast the pointer variable from one type to other type.
Output is 27
Output : Value is 27
In call by reference what ever changes are made to formal arguments of the function
definition will affect the actual arguments in calling function.
Pointer arguments are use full in functions, because they allow accessing the original
data in the calling program.
Ex1: void swap (int *, int *); main ( )
int t;
Output: 20 10
Ex 2:
main ( )
int i=0;
i++;
}
Output:
before copy
after copy
Pointer can be used with array for efficient programming. The name of an array itself
indicates the stating address of an array or address of first element of an array. That
means array name is the pointer to starting address or first elements of the array. If A
is an array then address of first element can be expressed as &A[0] or A.The compiler
defines array name as a constant pointer to the first element.
int i, a[10],n;
temp = a[ j ]; a[ j ] = a[ i ]; a[ i ] = temp;
Output :
Pointers are very useful in accessing character arrays. The character strings can be
assigned with a character pointer.
Ex:
array version
pointer version
#include<stdio.h>
#include<conio.h>
main()
int i;
printf (“ %c “, *p);
p++;
include <stdio.h>
k = slen (name);
int n;
for (n=0; (*s) != „\0‟; n++) s++;
return (n) ;
Pointer Arithmetic:
An integer operand can be used with a pointer to move it to a point / refer to some
other address in the memory.
65494
Assume that it is allotted the memory address 65494 increment value by 1 as follows .
mptr ++;
or
++ mptr;
or
mptr + =1 ;
++ and - - operators are used to increment, decrement a ptr and commonly used to
move the ptr to next location. Now the pointer will refer to the next location in the
memory with address 64596.
C language automatically adds the size of int type (2 bytes) to move the ptr to next
memory location.
mptr = mtpr + 1
65494 + 1 * 2
Similarly an integer can be added or subtract to move the pointer to any location in
RAM. But the resultant address is dependent on the size of data type of ptr.
The step in which the ptr is increased or reduced is called scale factor.Scale factor is
nothing but the size of data type used in a computer.
double = 8 and so on
xp = xp + 5;
63498 + 5*4
63498+20
63518
When 2 pointers points to the same array, one pointer variable can be subtracted from
another.
when two pointers points to the objects of save data types, they can be compared using
relational .
Data in the array is of the same composition in native a fan as type is concerned. In real life
we need to have different data types for ex. To maintain the employee information. We should
have information such as name, age, qualification, salary etc. here to maintain the information
of employee dissimilar data types required. Name & qualification are char data type age is
integer, & salary is float. All these data types cannot be expressed in a single away. One may
think to declare different always for each data type. Hence, always cannot be useful her for
tackling such mixed data types, a special feature is provided by C, known as Structure.
Structure is a collection of heterogeneous type of data i.e. different types of data. The various
individual components, in a structure can be accessed is processed separately. A structure is a
collection of variables referenced under a name, providing a convenient means of keeping
related information. A structure declaration forms a template that may be used to create
structure objects.
Structure
Arrays
1.
1.
2.
2.
i.e. index.
The point on which array & structures can be similar is that both array & structure must be
definite number of components.
Features of Structures:-
To copy elements of one array to another array of same data type elements are copied one by
one. It is not possible to copy elements at a time. Where as in structure it is possible to copy the
contents of all structure elements of different data types to another structure var of its type using
assignment (=) operator. It is possible because structure elements are stored in successive
memory locations. Nesting of structures is possible.
It is also possible to create structure pointers. We can also create a pointer. Pointing to structure
elements.
For this we require „ ‟ operator.
Declaration of structure :-Struct Struct_type
};
The declaration defines the structure but this process does not allocate memory. The memory
allocation takes only when var.r declared
Example:-
Bk 1
Bk 2
Struct book
Book [30]
{
Book [30]
Char book [30];
Pages
Pages
Price
Price
};
Initialization:-
All the members of structure are related to variable bk1 structure – var. member i.e. bk1.book
WAP to define & initialize a structure & its variables
main ( )
{
Strict book
float price;
};
:%d “,bk1.pages);
:%f “,bk1.price);
Out put:
Book name : C ++
No of pages : 300
We can take any data type for declaring structure members like int, float, char etc. In the
same way wee can also take object of one structure as member in another structure.
struct s1
Type var1;
Type var2;
};
struct s2
Type v3;
Strict s1 v4;
Strict s2 v5;
};
struct s2 p;
V3
V4
Van 1
Van 2
V5
Van 1
Van 2
=> WAP to enter the records of no of students & then display them using nested structure
int day;
int month;
int year;
};
Struct student
};
int i, n;
for(i=0;i<=n-1; i++)
printf (“Student name :”); sf(“ %s”,bio[i].name); printf (“Roll no :”) ; sf (“ %d “, bio
[i].rollno); pf (“date of birth”); pf (“\n Day”);
printf (“\n Student name : % s”, bio [i].name); printf (“\n Roll no : % d “, bio [i] . rollno);
printf (“\n Date of birth “);
Array of structures:-
A structure is simple to define if there are only one or two element, but incase there are too
many objects needed for a structure, for ex. A structure designed to show the data of each
student of the class, then in that case, the away will be introduced. A structure declaration
using array to define object is given below.
Stuct student
Int rollno;
Char sex;
};
Student data[50];
Ex: -
struct employee
};
{ 250, „m‟,10000} };
If incase, the structure of object or any element of struct are not initialized, the compiler will
automatically assigned zero to the fields of that particular record.
Data [0] sal=0; data [1].sal=0; data [2]. Sal=0; =>WAP to initialize the array of structure
members & display void main ()
int i;
Struct student
{
};
clrscr ();
Arrays can be used within the structure along with the member declaration. In other words, a
member of a structure can be an array type also.
struct emp
int sal;
char add[50];
};
Structures &pointers:-
So far we have seen that pointer is a variable that hold the memory address of other var. of
basic data type such as integer, float, char etc. A pointer can also be used in a program to hold
the address of heterogeneous type of var .i.e. structure var. pointer along with structure are
used to make linked lists, binary trees etc.
Ex:-
strtuct data
char n[10]
---
---
};
*ptr is a ptr var. Which holds the address of the structure named data? The ptr is declared
same as any object of a struct. Now, this ptr struct var can be accessed & processed by one of
the following given two methods.
Ex:-
void main ()
struct data
(*ptr) . a =100;
(*ptr) . b =20.9;
(*ptr). C =‟m‟;
}
The pointer to struct is expressed using a dashed line followed by (>) sign.
void main ()
struct data
ptr a = 100;
ptr b = 20.9;
ptr c = „m‟ ;
-----
-----
};
Department of CSE, GIT, GU Page 151
“Programming with C” course material
Uses of structures:-
Structures are useful in database management i.e. to main to data about employees, but use of
structures much beyond data base management. They can be used for.
Checking the memory size of the computer finding out the list of equipment attached to the
computer.
Formatting a floppy.
ex :
void main ()
struct student
};
Note :-
1). All the change made in the away of struct. Inside the called function. Will be visible in the
calling function .
2). If the size of a struct is very large then it is not efficient to pass the whole struct. To
function.
It is better to sent the address of the structure which will improve the execution speed.
Passing individual members to a function. Become cumbersome when there are many
members & the relationship b/w the members is also last so we can pass the whole structure
as an argument
As any other van. Structure .van is return the retuned value can be assigned to a structure of
the appropriate time.
As we pass away to a function away of Structure. Can also be passed to a function where each
ele. of away is of Structure type.
Union:-
Union is a data type in „C‟ which allows an ruelay of more than none Var in the same
memory arc i.e. using the memory space for different van at same place.
Syntax:-
union uni-name
type Var 1;
type Var 2;
All var inside an union share storage space. The compiler will allocate sufficient storage for
the union var to accommodate the largest element in the union .Other element of the union use
the same space (as it is using same space) it is different from structures.
union name
{
char name [40];
char id [20];
} id *ptr 2;
structure
char
name [25]
Int
idno;
float
sal;
} emp;
union
char
name [25]
Page 154
“Programming with C” course material
Only one member of a union can be accessed at a time i.e. because at every instance only one
of the union var. will have a meaningful value, only that var is read.
Operations an unions:-
Unions have all the features provided y a Structure which are a conveyance of memory
sharing properties of a union. This is evident by the following operations union which are
legal.
The address of the union var. can be extracted by using address of operator.
Scope of a Union:
void main ( )
union
int i;
char c;
float f;
O/p:-
/* compiler dependent* /
Fields in structure:
Syntax:-
structure <tag>
};
Ex:
structure with_bits
};
void main ( )
Union
int i ;
};
i = 0;/*second =0 */
Programs:
WAP to pass structure elements to function print ( ) & print the elements.
WAP to declare pointer to structure & display the contents of the structure.
Objective Questions:
a.
dot ( . )
operator.
b.
operator.
both
none.
Sum of size of all the members + the paddira bytes that may be provided by the compiler
None.
Sum of size of all the members + the paddira bytes that may be provided by the compiler
None.
different
same
cannot say
file
away
structure
none
FILES
A file is a place on disk where group of related data are stored. C supports a number of
functions that have the ability to perform basic file operations, which include:
Naming a file
FILE TYPES:
DOS treats files in two different ways viz., as binary or text files. Almost all UNIX
Systems do not make any distinction between the two. If a file is specified as the
binary type, the file I/O functions do not interpret the contents of the file when they
read from or write to the· file. But, if the file is specified as the text type the I/O
functions interpret the contents of the file. The basic differences in these two types of
files are:
ASCII 0xla is considered an end-of-file character by the file I/O function when
reading from a text file and they assume that the end of the file has
been reached.
In case of DOS a new file is stored as the sequence 0*0d 0*0a on the disk in case of text
files. UNIX stores \n as 0* 0a both on disk and in memory.
FILE Operations:
1. Opening a File:
C communicates with files using a new data type called a file pointer. This type is
defined within stdio. h, and written as FILE *. A file pointer called output_file is
declared in a statement like e
FILE *output_file;
If we want to store data in a file into the secondary memory, we must specify certain
things about the file to the operating system. They include the filename, data structure,
purpose.
The general format of the function used for opening a file is FILE *fp;
fp = fopen("filename", "mode");
The first statement declares the variable fp as a pointer to the data type FILE. As stated
earlier, File is a structure that is defined in the I/O Library. The second statement
opens the file named filename and assigns an identifier to the FILE type pointer fp.
This pointer, which contains all the information about the file, is subsequently used as
a communication link between the system and the program.
The second statement also specifies the purpose of opening the file. The mode does
this job.
r open the file for read only. w open the file for writing only.
a+ open for append; open for update at the end of the file
In these statements the pI and p2 are created and assigned to open the files data and
results respectively the file data is opened for reading and result is opened for writing.
In case the results file already exists, its contents are deleted and the files are
opened as a new file. If the data file does not exist error will occur.
The input output library supports the function to close a file; it is in the following
format.
f close(file -'pointer);
A file must be closed as soon as all operations on it have been completed. This would
close the file associated with the file pointer.
FILE *p 1 *p2;
……
……
fclose(p1); fclose(p2)
The above program opens two files and closes them after all operations on them are
completed, once a file is closed its file pointer can be reversed on other file.
Department of CSE, GIT, GU Page 160
“Programming with C” course material
Reading a character from a file and writing a character into a file ( getc () and
putc ()' functions)
The getc and putc functions are analogous to getchar and putchar functions and handle
one character at a time. The putc function writes the character contained in character
variable c to the file associated with the pointer fp1. ex putc(c,fpl); similarly getc
function is used to read a character from a file that has been open in read mode.
c=getc(fp2).
The program shown below displays use of a file operations. The data enter through the
keyboard and the program- writes it. Character by character, to the file input. The end
of the data is indicated by entering an EOF character, which is control-z. the file input
is closed at this signal.
Sample program for using getc and putc functions*/.: #include< stdio.h >
void mainO
FILE *fl;
printf("%c",c ); fclose(fl );
}
4. Reading a integer from a file and writing a integer into a file ( getw() and
putw() functions)
These are integer-oriented functions. They are similar to get c and putc functions and
are used to read and write integer values. These functions would be useful when we
deal with only integer data. The general forms of getw and putw are:
putw(integer,fp ); getw(fp);
/*Example program for using getw and putw functions * / #include< stdio.h > void
main( )
break;
putw (number,fl );
fclose(fl);
fclose(f2);
fclose(f3);
The fprintf and fscanf functions are identical to printf and scanf functions except that
they work on files. The first argument of theses functions is a file pointer which
specifies the file to be used. The general form of fprintf is
Where fp id a file pointer associated with a file that has been opened for writing. The
control string is fiJe output specifications list may include variable, constant and
string.
Here name is an array variable of type char and age is an int variable The general
format of fscanf is
fscanf(fp,"controlstring" ,list);
This statement would cause the reading of items in the control string.
Example:
Like scanf, fscanf also returns the number of items that are successfully read.
I*Program to handle mixed data types*/ #include< stdio.h >
main()
{
fclose (fp);
fgetc() function is similar to getc() function. It also reads a character and increases the
file pointer position. If any error or end of the file is reached it returned EOF.
fputc() function writes the character to the file shown by the file pointer. It also
increases the file pointer position.
Sample program to write text to a file using fputc() and read the text from the
same file using fgetc()
fgets() function reads string from a file pointed by file pointer. It also copies the string
to a memory location referred by an array.
fputs() function is useful when we want to write a string into the opened file .
.-
Sample program to write string to a file using fputs() and read the string from
the same file using fgets()
FILE *fp;
putchar(text[i]);
i++;
fclose(fp ); getch();
typedef struct { char name [30] ; char address [60] ; int account ;
The first parameter to fwrite is the pointer to the base of the array of our customers.
The second parameter is the size of each block to save. We can use sizeof to find out
the size of the structure. The third parameter is the number of customer records to
store, in this case 100 and the -final parameter is the file which we have opened. Note
that if we change the number of items in the customer structure this code will still
work, because the amount of data saved changes as well.
The opposite of fwrite is fread. This works in exactly the same way, but fetches data
from the file and puts it into memory:
If you want to check that things worked, these functions return the number of items
that they transferred successfully:
if( fread (Hull_Branch, sizeof( customer), 100, Hull_Data) < 100) { printf ( "Not all
data has been read!\n\n" ) ; }
{
char name[20]; int age; }stud[5];
void main()
for(i=O;i<n;i++ )
whileG<n)
fclose(fp );
while(j<n)
} fclose(fp ); }
The file I/O routines all work in the same way; unless the user takes explicit steps to
change the file position indicator, files will be read and written sequentially. A read
followed by a write followed by a read (if the file was opened in a mode to permit
that) will cause the second read to start immediately following the end of the data just
written. (Remember that stdio insists on the user inserting a buffer-flushing operation
between each element of a read-write-read cycle.) To control this, the Random Access
functions allow control over the implied read/write position in the file. The file
position indicator is moved without the need for a read or a write, and indicates the
byte to be the subject of the next operation on the file.
Three types of function exist which allow the file position indicator to be. examined or
changed. Their declarations and description follow.
#include <stdio.h>
/* set file position indicator to zero * / void rewind (FILE *stream); /* set file position
indicator */
ftell returns the current value (measured in characters) of the file position indicator if
stream refers to a binary file. For a text file, a 'magic' number is returned, which may
only be used on a subsequent call to fseek to reposition to the current file position
indicator. On failure, -1 L is returned and ermo is set.
rewind sets the current file position indicator to the start of the file indicated by stream.
The file's error indicator is reset by a call of rewind. No value is returned.
Fseek allows the file position indicator for stream to be set to an arbitrary value (for
binary files), or for text files, only to a position obtained from ftell, as follows:
In the general case the file position indicator is set to offset bytes (characters) from a
point in the file determined by the value of ptrname. Offset may be negative. The
values of ptmame may be SEEK_SET, which sets the file position indicator relative to
the beginning of the file, SEEK_CUR, which sets the file position indicator relative to
its current value, and SEEK_END, which sets the file position indicator relative to the
end of the file. The latter is not necessarily guaranteed to work properly on binary
streams.
For text files, offset must either be zero or a value returned from a previous call to ftell
for the same stream, and the value ofptrname must be. SEEK_SET.
Fseek clears the end of file indicator for the given stream and erases the memory of
any ungetc. It works for both input and output.
Note that.for ftell and fseek it must be possible to encode the value of the file position
indicator into a long. This may not work for very long files, so the Standard introduces
fgetpos and fsetpos which have been specified in a way that removes the problem.
fgetpos stores the current file position indicator for stream in the object pointed to by
pos. The value stored is 'magic' and only used to return to the specified position for the
same stream using fsetpos. fsetpos works as described above, also clearing the
stream's end-of-file indicator and forgetting the effects of any ungetc operations. For
both functions, on suc,cess, zero is returned; on failure, non-zero is returned and errno
is set.
[#include <stdio.h>
int main()
FILE * f;
fclose(f); return 0;
Hello India
Sample program to print the current position of the file pointer in the file using ftell()
function:
FILE *fp;
while(!feof(fp ))
}
fclose(fp );
10 Error handling
It is possible that an en-or may occur during I/O operations on a file. Typical en-or
situations include:
Device overflow
Trying to perform an operation on a file when the file is opened for another type of
operation. he standard I/O functions maintain two indicators with each open stream to
show the end-of file and en-or status of the stream. These can be interrogated and set
by the following functions: .
.
Department of CSE, GIT, GU Page 169
“Programming with C” course material
#include <stdio.h>
clearer clears the error and EOF indicators for the stream.
feof: returns non-zero if the stream's EOF indicator is set, zero otherwise. Ferror: returns
non-zero if the stream's error indicator is set, zero otherwise.
Perror: prints a single-line error message on the program's standard output, prefixed
by the string pointed to by s, with a colon and a space appended. The error message is
determined by the value of ermo and is intended to give some explanation of the
condition causing the error.
main()
/* Result */
Describe the use and limitations of the functions getc and putc?
Write a program to write contents of one file in reverse into another file?
Write a program to read the contents of three files and find the largest file?
Bits:
1.
Which one of the following function is used for sorting information in a disk file [
d]
a) Scanf()
b ) fscanf ()
c )printf ()
d)fprintf()
2.
a) 2
b) 1
c) -1
d) 0
3.
Which of the following function is used to set the record pointer at the beginning of
the file
[c]
a) Putc()
b) getw()
c) rewind()
d) gets()
4.
Which of the following mode opeqs a binary file in write mode [d]
a) W+
b)Y wb+
c) w
d) wb
5.
Which of the following functions used to write an entire block of data to a file [d]
a) Fputs
b). fgets
c) fscanf
d) fwrite
6.
The fscanf() function reads data from [a]
a) File
b) keyboard
7.
a) Null
b) -1
c) 1
d) none
Page 171
“Programming with C” course material
a) 1
b)2
c)3
d)4
a) ftell
b) rewind
c) fput
d) none
b) data error
c) end of file d) file closing error
a) a
b) r c) a+b
d) none
b)feof(fp)
c) feof(fp,list)
d) none
a) Arrays
b) structures
c) pointers
d) files
a) 2
b) 3
c) 1
d) none
15.
Which of the standard file pointer is used for standard auxillary device [b]
a) Stdpm
b)stdaux
c) stdio
d) stdconio
16.
Which of the following function is used to read each member of the structure in
the file[c]
a) Gets
b) puts
c) fscanf
d) fprintf
17.
a) a
b)w
c)w+
d)a+
18.
The function that is not used for random access to file [d]
a) Ftell
b) rewind
c) fseek
d)fprintf
19.
The C library that contains the prototype statement for the file operation [b]
a) Proto.h
b) file.h
c) stdio.h
d) stdlib.h
Write a program to read last few characters of the file using fseek () Statement.
Printf (“/n contents of file \n”); while ((ch=fgetc(fp))!=EOF) Printf (“%c”, ch);
Printf (“/n How many characters including spaces would you like to skip?:”); while ((ch =
fgetc(fg))
o/p: How many characters including spaces would you like to skip? : 5 Lat characters of the
file
WORLD
Department of CSE, GIT, GU Page 173