C Programming Notes
C Programming Notes
UNIT I
Introduction to Programming in C
Introduction to C
C is a programming language developed at AT & T’s Bell Laborites of USA in 1970.
It was designed and written by a man named Dennis Ritchie. In the late seventies C began
to replace the more familiar languages of that time like PL/I, ALGOL etc. No one pushed
C. it wasn’t made the official Bell Labs language. Thus, without any advertisement C’s
reputation spread and its pool of users grew. Ritchie seems to have been rather surprised
that so many programmers preferred C to older languages like FORTRAN or PL/I or the
newer ones like Pascal and APL.
Possibly why C seems so popular is because it is reliable, simple and easy to use. Out of
the dozens of languages available, the prize of purity is often given to PASCAL.
C is a general-purpose language which has been closely associated with the UNIX
operating system for which it was developed - since the system and most of the programs
that run it are written in C. COBOL was being used for commercial applications,
FORTRAN for Engineering and Scientific Applications and so on. At this stage people
started thinking that instead of learning and using so many languages, each for a different
purpose, why not use only one language. Which can program all possible applications.
Therefore, an international committee came out with a language called ALGOL 60.
However, ALGOL 60 never really became popular because it seemed too abstract, too
general. To reduce this abstractness and generality, a new language called combined
Programming Language (CPL) was developed at Cambridge University. CPL was an
attempt to bring ALGOL 60 down to earth. However, CPL turned out to be so big, having
so many features, that it was hard to learn and difficult to implement.
the English (or other) language. But a computer does not understand high-level language.
It only understands program written in 0's and 1's in binary, called the machine code. A
program written in high-level language is called a source code. We need to convert the
source code into machine code and this is accomplished by compilers and interpreters.
Hence, a compiler or an interpreter is a program that converts program written in highlevel
language into machine code understood by the computer.
Compiler
Scans the entire program and translates it as a whole into machine code. It takes
large amount of time to analyze the source code but the overall execution time is
comparatively faster. Generates intermediate object code which further requires linking,
hence requires more memory. It generates the error message only after scanning the whole
program. Hence debugging is comparatively hard. Programming language like C, C++ use
compilers.
Interpreter
Translates program one statement at a time. It takes less amount of time to analyze
the source code but the overall execution time is slower. No intermediate object code is
generated, hence are memory efficient. Continues translating the program until the first
error is met, in which case it stops. Hence debugging is easy. Programming language like
Python, Ruby use interpreters.
2
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
Algorithm should be most effective among many different ways to solve a problem.
An algorithm shouldn't have computer code. Instead, the algorithm should be written in
such a way that, it can be used in similar programming languages.
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 6: Stop
Write an algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Step 4: If a>b
If a>c
3
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
Else
Else
If b>c
Else
Step 5: Stop
4
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
Flowchart are not related to any programming language. Hence they can be implemented
in any programming language.
Flowchart are easy to understand. The data flow of the program can be easily understood
by flowcharts and errors in it can be easily recovered.
When we need to incorporate some more facilities within program, then it is easy to
incorporate them through flowchart.
1) Documentation Section
2) Header Section [link section]
3) Definition Section
4) Global Declaration
5) Main Section
6) Sub Program Section
5
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
1) Documentation Section
We can write title of program in that section using comments line there are
two types of comment line
In this section we can use the Header file such as # ‘stdio.h’ & ‘conio.h’ ,
string.h, such as Header file are used to give c linking support to the functions
used in c program.
stdio.h stands for slandered I/O file. Which support to standard I/O function as
printf() & scanf().
Similarly conio.h is stand for console I/O hidder file which support to console
I/O functions such as clrscr(); & getch().
3) Definition Section
There are some variables that are used in more than one function such
variables are called global variable they are declared in the global declaration
section that in outside of all function.
5) Main() Section
Every C program have only one main() function is start with ({ ) & close
with ( } ) main function have main two part i.e declaration part & execution
part.
a) Declaration part:-
6
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
In sub program section we can use user defined function. User defined
function are function which are defined by user.
Simple C Program
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“Wel come C programming”);
getch();
}
Algorithm:-
1.Start
2.Print statement “cocsit”
3.stop
7
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
Flowchart:-
STAR
PRINT
STATEMENT
“cocsit”
Program:-
STOP
/* Write A Program to display the name of college.*/
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“*****out/put****”);
printf(“\nHello cocsit");
getch();
}
*****out/put****
Hello cocsit
1.6 C Tokens
Uppercase -
A B C --------------------- Z.
8
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
Lowercase -
a b C --------- Z
Digits:- 0 2 3 4 5 6 7 8 9
9
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
White spacious
The ‘C’ compiler ignores white space unless they are a part of string constant white
space may be used to separate words, white space include blank space, horizontal tab.
Horizontal tab - \t
New line - \n
By using this character set we can create program, function name, variable name.
‘C’ uses certain combination of characters such as, /b,/n,/t. to represent special condition
such as back space, new line & horizontal tab these characters combination are known as
escape sequence.
Identifers
• Identifiers are names that are given to various program elements such as variables,
function & array name. there are certain rules we should be follow while running
& identifiers are
• Identifier consists of letters & digits in any order except the first character should
be letter
• Both uppercase & lowercase letters are permitted although lowercase letter are
commonly used.
• Uppercase & lowercase letters are not interchangeable [an uppercase letters is not
equivalent to corresponding lowercase letter
• The underscore [_] character can be included & it is considered as a letter.
• An identifiers name up to 8 characters many compilers allow an identifiers name
up to 31 characters.
• Following names are valid identifiers x, xyz, sum, nau, basic_sal.
First character must be latters.
10
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
C Keywords
Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a
new meaning to the keyword, which is not allowed by the computer.
There are 32 keywords used in C all keywords must be written in lower case.
Some compilers may also include some or all of the following keywords.
Variables
A variables is data name that may be used to store the data value these variables name are
giving to location in the memory of computer where we are storing the data there are some
rules available for creation and deceleration of variables.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“Enter the number”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“The addition is %d”,c);
11
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
getch();
}
Types of variables
In C, a quantity which may change during program execution is called a variable. Variable
names are names given to locations in the memory of computer where different constants
are stored. This location can contains integer, real or character constants. This is because a
constant stored in a location with a particular type of variable name can hold only that type
of constant. Ex:- a constant stored in a memory location with an integer variable name must
be an integer constant. One stored in location with a real variable name must be a real
constant and the one stored in location with a character variable name must be a character
constant.
Rules for Constructing Variable Name.
float a;
char code;-
Data type
C language is rich in data type like other languages ‘C’ language has also it’s own data
types data types are used to define or declare the type [data type] of particular variable,
constant, function etc.
In C language there are three classes of data types.
1) Primary data type.
2) Derived data type.
3) User-defined data types.
Data type are always written in small letters each data types has it’s own feature depending
upon a condition the particular data types is used in the name of data type we cannot use in
valid space.
Size Format
Data Type Range Size in Bit in
Byte String
12
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
13
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
C Data Types
- structure - array
- union Built in type - function
- pointer
1) Primary Data Type:- it is also known as standard of or built in data type all
compiler support fundamental data type. Primary data type is divided into 3 type.
int [integer]:-
Integer are defined by keyword ‘int’ integer are store for no we cannot store decimal point
no in that data type integer occupies one word of storage i.e 2 bytes or 16 bits.
The range of integer data type is -32768 to 32767 ‘C’ has support to classes of integer
storage namely int shor int & long int variable than they increases the range of value
as will as size of it. 32 bit word length can store an integer ranging from
2,147,483,648to 2147483647.
#include<stdio.h>
#include<conio.h>
void main()
{ int a,b,c;
a=10;
b=20;
c=a+b;
printf(“\n A addition of two number is %d”,c);
getch();
14
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
}
float [Float]
The real no are known as floating value. These no contain functions part. This is defined
by keyword ‘float’ float value requires 4 bytes or 32 beats. The range of float is 3.4e-38 to
3.4e38.
#include<stdio.h>
#include<conio.h>
{ float a,b,c;
clrscr();
a=3.2;
b=1.5;
c=a+b;
printf(“\n Addition of two number %f”,c);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{ int sub1=40,sub2=50,sub3=60,sum;
float avg;
clrscr();
sum=sub1+sub2+sub3;
printf(“\n Addition of three subject is %d”,sum);
avg=sum/3;
printf(“\n average of three subject is %f”,avg);
getch();
}
15
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
character (char)
Generally those data types are used when we have to storage a single character or string to
variable. It requires 1 byte or 8 beats to store in memory. It is defined by keyword as ‘char’
the range of char is -128 to 127.
Ex:-char name;
name=’a’;
char name[15]=”Bhosle”;
Double
It is very similar to float data type the major difference between float & double data type is
size & range of the double data type is always greater than float data type size of double
data type is 64 beats, 8 bytes range of double data type is 1.7e-308 to 1.7e +308 .
Void Type
The Void type has no value. This is usually used to specify the type of functions. The type
of a function is said to be void when it does not return any value to the calling function. It
can also play the role of a generic type, meaning that it can represent any of the other
standard types.
These data type are defined by using keyword ‘typedef’ it takes following format.
The example will demonstrate the use of user defined data type.
#include<stdio.h>
#include<conio.h>
typedef int mark
void main()
{ mark sub1,sub2,sub3,sum,avg;
16
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
here marks indicate integer data type but sub1, sub2,sub3 indirectly marks referees to
standard data type int.
Some time these derived data type are also called user defined data type which is derived
from fundamental data type. The derived data type are
Escape Sequences
These are the special characters starting with ‘\’ which makes the computer to line out of
the normal sequence.
Computer has some default sequences e.g computer always prints data in a line unless we
ask the computer to create a new line etc. the following are the escape sequences.
Constant Meaning Constant Meaning
\n New line \r Carriage return
\t Horizontal tab \0 Null
\v Vertical tab \’ Single quote
\a Alert (bell) \” Double quote
\b Back space \? Question mark
\f Form feed \\ Back slash
scanf(“%d”,&b);
c=a;
a=b;
b=c;
printf(“\n After swap A=%d”,a);
printf(“\n After swap B=%d”,b);
getch();
}
*****out/put****
Enter the First number 23
Enter the Second Number 55
After swap A= 55
After swap B= 23
//Write a program to swap two value by using third variable
#include<stdio.h>
#include<conio.h>
void main() {
int a,b;
clrscr();
printf(“\nEnter the First number’);
scanf(“%d”,&a);
printf(“\nEnter the Second Number”);
scanf(“%d”,&b);
a=a+b;
b=a-b;
a-b-b;
printf(“\n After swap A=%d”,a);
printf(“\n After swap B=%d”,b);
getch();
}
*****out/put****
Enter the First number 23
Enter the Second Number 55
After swap A= 55
After swap B= 23
clrscr();
printf(“Enter the number");
scanf("%d",&no);
a1=no%10;
no=no/10;
a2=no%10;
no=no/10;
a3=no;
rev=100*a1+10*a2+a3;
printf(“Revers number is %d",rev);
getch();
}
*****out/put****
Enter the number 123
Entered number is 321
Operators :-
An operators is a symbol which tells the computer to perform mathematic or
logical operation C supports following 8 types of operators
1) Arithmetic operators
2) Relational operators
3) Logical operators
4) Assignment operators
5) Increment & Decrement operators
6) Conditional operators
7) Bit-wise operators
8) Special operators
1) Arithmetic operators
C Language supports all arithmetic operators this operators provides same function
as in other languages this operators can operate on any built in data type in C
following list gives the arithmetic operators with meaning.
+,-,*,%
Integer division ignores frication parts in the result c doesn’t support an operators
for exponential
A+B
A and B is operands
19
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
#include<stdio.h>
#include<conio.h>
void main()
{ int a;
float b,c;
clrscr();
printf(“\nEnter the two number");
scanf("%d%f",&a,&b);
c=a+b;
printf(“Addition of two number is %f",c);
getch();
}
2) Relational operators
If we want to compare two values then Relational operators are used C supports six
Relational operators
1 >
2 >=
3 <
4 <=
5 ==
6 !=
The simple format of Relational operators as follows
#include<stdio.h>
#include<conio.h>
void main()
{ clrscr();
printf(“\nCondition : Return Values \n”);
printf(“\n10!=10 : %5d”,10!=10);
printf(“\n10==10 : %5d”,10==10);
printf(“\n10>=10 : %5d”,10>=10);
printf(“\n10<=10 : %5d”,10<=10);
printf(“\n10!=9 : %5d”,10!=9);
getch();
}
20
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
3) logical operators
4) Assignment Operators
The assignment operators are used to assign values or result of the expression to
variables C support for the assignment operators that is
21
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
ex:-a=10;
In the prefix operators the values of variables is Increment and Decrement First
and then assigned to the expression
Prefix operators
++a ;
--a ;
a=3 ;
y=++a
y=4
postfix operators
a post fix operators first assign the values to variables on left side and then
increment the operand
a=5;
y=a++;
y=6 ;
6) Conditional operators
Conditional operators
Expirations ? expression2 : expression3
?:
a=3; b=4;
x=(a<b)? a:b;
//write a program to find out the given number greater or not by using
conditional operators.
#include<stdio.h>
#include<conio.h>
void main() {
int a,b;
printf(“Enter two number”);
scanf(“%d%d”,&a,&b);
getch();
}
in above expression a is less then b if this condition is true then value of a will be
to assign to the expression and if given condition is false then value of b it will be assign
to the expression
7) Bit-wise operators
There operators are used for manipulation of data at bit level we can use these
operators for testing the bits, sift right and left we can’t apply the bit wise operators with
float and double following list gives the operators and there meaning
This operator move bit patterns either to the left or to the right. The shift operators
are represented by Left shift << and Right shift >>.
<< Left
10
0 0 0 0 1 0 1 0
0 0 1 0 1 0 0 0
>>Right
10
0 0 0 0 1 0 1 0
0 0 0 0 1 0
8) Special operators
Comma operators this operator is used to link or connect the related expression
Values(a=3,b=4,x=a+b)
x=7
3 is assign to variables a
4 will be assign to b
after that x=7 addition of two numbers
#include<stdio.h>
#include<conio.h>
void main()
23
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
{
clrscr();
printf(“ Subtraction = %d\n Addition =%d”,5-3,5+6);
getch();
}
Introduction
Reading the data from the input devices and displaying the results on the screen, are the
two main tasks of any program. To perform these tasks user friendly C has a number of
input and output functions. When a program needs data, it takes the data through the input
functions and sends results obtained through the output functions. The input/output
functions are the link between the user and the VDU.
There are number of I/O functions in C based on the data types. The input/output functions
are classified in to two types
4) Formatted functions
5) Unformatted function.
24
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
The formatted input/output functions read and write all types of data values. They
require conversion symbol to identify the data type. They can be used for both reading
and writing of all data values. The formatted functions return the values after execution.
The return value is equal to the number of variables successfully read/ written.
1.8 Unformatted function:-
The formatted input/output functions only work with the character data type. There
is no need to convert the data. In case values of other data types are passed to these
functions, they are treated as the character data. The unformatted function also return
values, but the return value of unformatted function is always the same.
Formatted Function:-
printf():-
This function is used to display result on the screen it can be used to display any
combination of numerical value as will as char or string. It requires conversion symbol and
variable names to print the data. The conversion symbol and variable names should be same
in number.
Syntax:-
Ex:-
void main()
{ int a=3;
float b=5;
char c=’b’;
printf(“%d %f %c”,a,b,c);
}
25
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
scanf():-
The input data or information can be enter to the computer through a standard input
device by using scanf() function. This function can be used to enter any combination of
numerical value, single char, or strings this function return the number of data item that
have been successful we can declare the scanf() function as follow.
Ex:- scanf(“%d”,&a);
Ex:-
#include<stdio.h>
#include<conio.h>
void main()
{ int a,b,c;
clrscr();
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“%d”,c);
getch();
}
26
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
getchar(); Function:-
Single character can be entered into the computer using ‘c’ library function getchar(); the
get character function is a part of standard I/O function. It written a single character from
a standard input device [keyboard] the function does not require any argument a pair of
empty parentheses must follow the word getchar(). The getchar take following form
Variable name=getchar();
Variable name is a valid C name that has been declared as char type. When this
statement is encountered, the computer waits until a key is pressed and then assign this
character as a value to getchar function. Since getchar is used on the right-hand side of an
assignment statement,
Syntax:-
Char name;
Name=getchar();
Ex:-
void main()
{
char c;
clrscr();
c=getchar();
putchar(c);
getch();
}
putchar(); Function:-
This function prints one character on the screen at a time which is read by the standard
input device such as keyboard.
Syntax:-
putchar(name);
Ex:-
void main()
{
char c;
clrscr();
27
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
c=getchar();
putchar(c);
getch();
}
puts() function:-
This function is used to display the string or collection of character to the output
device such as monitor.
Syntax:-
char name[20];
puts(name);
Ex:-
#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
clrscr();
printf(“\nEnter the name”);
gets(name);
printf(“My name is %s”,name);
getch();
}
gets() function:-
This function is used to accepting any string or collection of character from input device
such as keyboard.
Syntax:-
char name[20];
name=gets();
Ex:-
#include<stdio.h>
#include<conio.h>
void main()
28
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
{
char name[20];
clrscr();
printf(“\nEnter the name”);
gets(name);
printf(“\n My name is “);
puts(name);
getch();
}
UNIT II
Controlling Statement
Introduction
The statements in a program are executed line by line similarly in the way we read
a text book. The method to read a textbook is straight forward, which starts from first
line to the end of line and from top to bottom.
Similarly, in the program the statements are read and executed sequentially lineby-
line unto the end of program. In some time, we may select one of the options from the
available options by testing some condition. Depending on the problem, the flow of the
program is fixed.
29
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
if (test expression)
{ body of if statement;
}
Next statement x;
The body of if may have one statement or group of statement where each statement
is separated by semicolon. If the test expression is true, the true statement block will be
executed otherwise computer will skip the block of statement and the execution will
jump to the next statement immediately after the end of if statement.
30
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
Start
True
Text
Expression?
Statement X
End
if ( a>b)
{
printf(%d\n”,a);
}
void main()
{
int a,b;
printf(“\nEnter the Number a & b”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“A is grater number”);
if(b>a)
printf(“B is grater number”);
getch();
}
31
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
if (condition)
{
Body of true statement block;
} else
{
Body of false statement block;
}
Ex:-
if (a>b)
{
printf(“\n A is grater then B”);
}
else
{
printf(“\nA is less then B”);
32
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
}
This statement provides the alternates in both the situations, if condition is true the
body of if is executed if condition is false the body of else is executed.
Here computer can not proceed without executing either body of if or body of else.
if(year%4==0)
33
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
{
printf(“The given year is leap year”);
}
else
{
printf(“The given year is not leap year”);
}getch();
}
Syntax:-
if(Condition 1)
{
if(Condition 2)
{
Body of True Statement Block
}
else
{
Body of False Statement Block
}
}
else
{
if(Condition 3)
{
Body of True Statement Block
}
else
{
Body of False Statement Block
}
34
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
35
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
In that first check the condition. If the given condition1 is true then again check the
condition 2 if the given condition 2 is true then execute the true statement block and control
transfer to statement x. if the given condition 2 is false then without executing the true
statement block execute the false statement block of condition 2 and control transfer to
statement x. if given condition 1 is false then control transfer to else statement again check
the condition 3 if the condition 3 is true then execute the true statement and control transfer
36
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
to statement x. if the given condition 3 is false then execute the false statement block and
control transfer to statement x.
When this structure gets executed and as soon as any one of the statement gets
executed, immediately the chain breaks & computer goes next statement. There are many
possible forms of nesting. It always depends on our problem.
Write a program that display the class obtained by student if percentage of the student
is input through the keyboard.
#include<stdio.h>
void main()
{ float per;
printf(“\nEnter the percentage : “);
scanf(“%f”,&per);
if(per<=0 || per>100)
{
printf(“Invalid input”);
exit(0);
}
if(per<40)
printf(“Fail”);
else {
if(per<50)
printf(“Pass”);
else
{
if(per<60)
printf(“Second class”);
else
printf(“First class”);
}
}
}
37
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
Write a program find out entered key is upper case or lower case.
#include<stdio.h>
#include<conio.h>
void main() {
char x;
clrscr();
printf(“\nEnter any char");
scanf("%c",&x);
if((x>=65&&x<=90)||(x>=97&&x<=122))
{
if(x>=65&&x<=90)
printf(“it is an upper case alphabet");
else
printf(“It is lower case alphabet");
}
else
printf(“It is not alphabet");
getch();
}
#include<stdio.h>
#include<conio.h>
void main ()
{ int num;
printf(“\nenter any number");
scanf("%d",&num);
if(num>0)
{
printf(“given number is positive");
}
else{
if(num<0)
{
printf(“given num is negative");
} else
printf(“Zero");
}
getch();
38
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
There is a negative side to the program. Even if the first condition turns out to be true, still
all other condition are checked. This will increase the time of execution of the program.
This can be avoided using the else if clause.
When multiple decision are taken then else if is used when we used else if ladder, can else
is associated with if.
Syntax
if(Condition 1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
else if(condition n)
statement n;
else
39
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
void main() {
float per;
printf(“Enter the value”);
scanf(“%f”,&per);
if(per>80)
{
printf(“grade is merit”);
}
else if(per>70) {
printf(“Distinction”);
}
else if(per>60) {
printf(“Grade A”);
}
else if(per>50) {
printf(“Grade is B”);
}
else if(per>=35) {
printf(“Grade is C”);
}
else {
printf(“Failed”);
}
printf(“try try but don’t cry, one day you will success”);
getch();
}
40
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
#include<stdio.h>
#include<conio.h>
void main()
{ int n1,n2,n3,n4,n5,larg,small;
clrscr();
printf(“\nEnter the number");
scanf("%d%d%d%d%d",&n1,&n2,&n3,&n4,&n5);
larg=n1;
if(n1>larg) larg=n1;
if(n2>larg) larg=n2;
if(n3>larg) larg=n3;
if(n4>larg) larg=n4;
if(n5>larg) larg=n5;
printf(“\nthe largest number within five number is %d",larg);
small=n1;
if(n1<small) small=n1;
if(n2<small) small=n2;
if(n3<small) small=n3;
if(n4<small) small=n4;
if(n5<small) small=n5;
printf(“\nthe smallest number within five number is %d",small);
getch();
}
2.1.5 Switch statement
By using switch statement, which have multiple collection but (alternative increases)
complexity increase and program become easy to read and debug. Switch statement is
multi-case statement. The keyword switch statement value of condition match with label .
41
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
Syntax :
switch(expression){
case 1 :
statement(s);
break;
case 2 :
statement(s);
break;
case n :
statement(s);
break;
default :
statement(s);
}
42
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
condition is doesn’t match with label of case (1) than it checks condition value is match
with label of case (2). If that value is match than execute statement block of case (2) and
control transfer to statement x and so on---
We have to remember that, case labels are single character constants.
Write a program that reads a number between 1 to 7 and display the day name
main() {
int day;
printf(“Enter a number between 1 to 7 \n”);
scanf(“%d”,&day);
switch(day)
{
case 1:printf(“Monday\n”);
break;
case 2:printf(“Tuesday\n”);
break;
case 3:printf(“Wednesday\n”);
break;
case 4:printf(“Thursday\n”);
break;
case 5:printf(“Friday\n”);
break;
case 6:printf(“Saturday\n”);
break;
case 7:printf(“Sunday\n”);
break;
default:printf(“Monday\n”);
}
switch(n) {
case 1: c=a+b;
printf(“\naddition of two number is%f”,c);
break;
case 2: c=a-b;
printf(“\subtraction of two number is%f”,c);
break;
case 3 : c=a*b;
printf(“\multiplication of two number is%f”,c);
break;
case 4: c=a/b;
printf(“\division of two number is%f”,c);
break;
default:
printf(“\nentered choice incorrect”);
}
printf(“\nDo you want to continue”);
printf(“\nEnter 6 yes 7: no”);
scanf(“%d”,&p);
swatch(p) {
case 6:
goto xyz;
break;
case 7:exit();
}
getch();
}
switch( c ){
case 1:printf(“1”);
break;
default: printf(“0”);
}
return(0);
}
Answer: 1
• while loop
• do-while loop
• for loop
• break statement, continue statement, goto statement
In this loop, first condition is checked, if the condition is true, than it executes the
body of loop. Again the condition is checked, if the condition is true, it execute body of
loop . So on , this processes continues until the given condition become false. Once
condition become false, than it transfer control to statement x without executing the body
of loop
46
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
In this loop, first body of loop is executed, then the condition is checked. If the condition
is true, than it execute body of loop. Again condition is checked, if it is true the body of
execute. So on this process continue until the given condition become false. Once condition
become false. It control transfer to statement x without executing the body of loop.
In exit control loop, the condition may true or false, at least once the body of loop is
executed
Ex : do-while
For loop
This statement is used when calculations are to be carried out between initial and
final value with step. The for loop condition consist of three actions namely initialization,
testing and incrementing/ decrementing. Each action should be separated by semicolon(;)
also this loop statement is used when number of execution time is known in advance.
Syntax-
for(initial value ; condition ; increment/decrement)
{
body of for loop;
}
In this loop the initial value, condition, increment/decrement is specified in the same
line. Here computer starts with the initial value, checks the condition. If the condition is
true computer executes the body and automatically goes up, it takes the increment or
decrement automatically and it continues. Remember, if the body of for continue a single
statement, no need of brackets. But if there are more than one statement in the body then
they must be enclosed between brackets.
47
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
Here every thing is specified in the same line and hence we can tell the number of
repetitions it can take. When we know the number of repetitions in advance than we should
go for the for loop.
Start
Flow Chart
Initialization
False
Conditio
n
True Stop
Body of loop
Increment
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
{ printf(“%d”,i); }
getch()
}
While loop
48
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
the while loop is one of the entry control loop. In this loop the condition is given at the top.
First the check condition and if the condition is true then execute body of loop. The body
of while may have one statement or more than one statement, if there is a single statement
no need of brackets’{‘’}’. If there are more one statement then brackets are compulsory.
Again the check condition and if it is true then execute body of loop this process still
continues of condition become false if condition become false does not execute the body
of loop and control goes to statement x. This loop should be used when condition is more
important.
Syntax:
while(conditio n)
{
Body true statement block;
}
Start
Initialize
Text False
Condition
True End
Body of loop
Increment
flow chart for while loop
49
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
void main()
{
int i=2;
clrscr();
while(i<=100)
{
printf(“%d\n”,i);
i=i+2;
}
getch();
}
Do while
There is a minor difference between the working of while and do-while loops this
difference is the place where the condition is tested. The while tests the condition before
executing any of the statements within the while loop. The do-while tests the condition
after having executed the statements within the loop.
Syntax:-
do
{
Body of the loop
}
while(test-condition);
Since the test condition is execute at the bottom of the loop, the do –while construct
provides an exit controlled loop and therefore the body of the loop is always executed
at least once.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,k,m;
clrscr();
scanf("%d",&k);
n=1;
do
50
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
{
m=pow(n,2);
printf(“%d\n",m);
n++;
} while(m<=(pow(k,2)));
getch();
}
//display 5,10,15----
#include<stdio.h>
#include<conio.h>
void main()
{ int n,k;
clrscr();
scanf("%d",&k);
n=5;
while(n<=k)
{
printf(“%d\n",n);
n=n+5;
}
getch();
}
//display 7,14,21----
#include<stdio.h>
#include<conio.h>
void main()
{
int n=7;
clrscr();
while(n<=70)
{
printf(“%d\n",n);
n=n+7;
}
getch();
}
//display 10,20,30----
#include<stdio.h>
51
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
#include<conio.h>
void main()
{ int n,k;
clrscr();
scanf("%d",&k);
n=10;
while(n<=k)
{
printf(“%d\n",n);
n=n+10;
}
getch();
}
//display 1,2,4,7,11----
#include<stdio.h>
#include<conio.h>
void main()
{
int n,k,d;
clrscr();
scanf("%d",&k);
n=1;
d=1;
while(n<=k)
{
printf(“%d\n",n);
n=n+d;
d=d+1;
}
getch();
}
//display 1,2,4,8----
#include<stdio.h>
#include<conio.h>
void main()
{ int n,k;
clrscr();
scanf("%d",&k);
n=1;
52
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
while(n<=k)
{
printf(“%d\n",n);
n=n*2;
}
getch();
}
//sum of 1 to 10 number
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,sum=0;
clrscr();
while(i<=10)
{
printf(“%d\n",i);
sum=sum+i;
i++
}
printf(“sum of I to 10 number%d”,sum);
getch();
}
//multiplication table
#include<stdio.h>
#include<conio.h>
void main()
{
53
Dr.Sasikala P
Nrupathunga University
Department of Computer Science
int i=0,j,sum=0;
clrscr();
while(i<=10)
{
j=1;
while(j<=10)
{
printf(“%d\t",i*j);
j++ ;
sum+=i;
}
printf(“\n”);
i++;
}
getch();
}
54
Dr.Sasikala P
Nrupathunga University
Department of computer science
While Do—while
Computer executes the body if and Computer executes the body at least
only if condition is true. once even if condition is false
This should be used when condition This should be used when the process
is more important. is important.
This loop is also refered as entry This loop is also refered as exit
controlled loop. controlled loop.
while(n<=10) do{
{ printf(“%d\n”,n); printf(“%d\n”,n);
n++; n++;
} }while(n<=100);
void main()
{
int i=1;
clrscr();
do
{
printf(“%d\n”,i);
i=i++;
} while(i<=100);
getch();
}
//display 5,10,15----
55 Dr. Sasikala . P
Nrupathunga University
Department of computer science
#include<stdio.h>
#include<conio.h>
void main()
{
int n,k;
clrscr();
scanf("%d",&k);
n=5;
do
{
printf(“%d\n",n);
n=n+5;
} while(n<=k);
getch();
}
//display 7,14,21----
#include<stdio.h>
#include<conio.h>
void main()
{
int n=7;
clrscr();
do
{
printf(“%d\n",n);
n=n+7;
} while(n<=70);
getch();
}
//display 10,20,30----
#include<stdio.h>
#include<conio.h>
void main()
{
int n,k;
clrscr();
scanf("%d",&k);
n=10;
do
{
printf(“%d\n",n);
56 Dr. Sasikala . P
Nrupathunga University
Department of computer science
n=n+10;
} while(n<=k);
getch();
}
//display 1,2,4,7,11----
#include<stdio.h>
#include<conio.h>
void main()
{
int n,k,d;
clrscr();
scanf("%d",&k);
n=1;
d=1;
do
{
printf(“%d\n",n);
n=n+d;
d=d+1;
} while(n<=k);
getch();
}
//display 1,2,4,8----
#include<stdio.h>
#include<conio.h>
void main()
{
int n,k;
clrscr();
scanf("%d",&k);
n=1; do
{
printf(“%d\n",n);
n=n*2;
} while(n<=k);
getch();
}
57 Dr. Sasikala . P
Nrupathunga University
Department of computer science
//display 1,2,4,8----
#include<stdio.h>
#include<conio.h>
void main()
{
int n,km;
clrscr();
scanf("%d",&k);
n=1;
do
{
m=pow(n,2);
printf(“%d\n",m);
n++;
} while(m<=(pow(k,2)));
getch();
}
//multiplaction table
#include<stdio.h>
#include<conio.h>
void main()
{ int i=1,j;
clrscr();
while(i<=5)
{
j=1;
while(j<=5)
{
printf(“%d\t",i*j);
j++;
}
printf(“\n\n");
i++;
}
getch();
}
58 Dr. Sasikala . P
Nrupathunga University
Department of computer science
Output:
*
**
***
****
Break Statement
The break statement is used for two different purpose it can be used to terminated a case in the
switch statement that is to terminate the given loop immediately and it by pass the normal loop
condition test.
we often come across situations where we want to jump out of a loop instantly, without wetting to
get back to the conditional test, the keyword break allows us to do this. when break is encountered
inside any loop, control automatically passes to the first statement after the loop. A break is usually
associated.
Ex:-
switch()
59 Dr. Sasikala . P
Nrupathunga University
Department of computer science
{
case 1:
break;
case 2:
break;
default:
}
ex:- void main()
{
int i;
for(i=1;i<=10;i++)
{ if(i==5)
{ break;
}
printf(“%d\t”,i);
}
getch();
}
Continue Statement:-
This statement is used to when execution of further statement. This stops execution of next
statement ?& transfer control to the start of loop for further execution of loop. This statement
should be used only within the loop.
void main()
{
int i;
for(i=1;i<=10;i++)
{ if(i==5)
{ continue;
}
printf(“\n%d”,i);
getch();
}
In the above ex. 'i' is initialized to 1 then it will check (i==5) if it is true it will execute printf()
statement. After execution I is incremented by 1 & again executes printf() statement. This process
continues till the condition i<=10 becomes true.
60 Dr. Sasikala . P
Nrupathunga University
Department of computer science
Goto Statement:
This statement transfers the control from one statement to other statement in the program which
may not be in the sequence. The general form of the goto statement is
goto label;
-------- ------
label:statement
towards jump
label: statement
____________
--------- ---------
goto label;
backward jump
where goto requires a level in order to identify the place where the branch is to be made
label. It is an valid variable name & must be followed by a (:) the program either before or
after the goto label statement as shown below.
Forward jump:
If the label is placed after goto label statement will be skipped such a jump is known as
forward jump.
Backward jump:
If the label is before the goto statement a loop will form & some statement will be executed
repeatedly such a jump is known as backward jump.
61 Dr. Sasikala . P
Nrupathunga University
Department of computer science
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main ()
{ int a,b;
clrscr();
xyz:printf(“enter the number");
scanf("%d",&a);
if(a%2==0)
{
printf(“given num is even ");
}
else
{ printf(“\nthe given num is odd");
} printf(“\nif you want to
continue");
printf(“\n Enter 6 to yes 7 to no");
scanf("%d",&b);
if(b==6)
goto xyz;
if(b==7)
exit(0);
getch();
}
62 Dr. Sasikala . P
Nrupathunga University
Department of computer science
UNIT III
Function in C
Introduction function in C
Functions are a useful way of referring to blocks of code, allowing the code to be called
many times. Functions take some input information (the input parameters), do something with that
information and then return a result (the return value). We are familiar with the predefined
functions, such as gets(), puts(), getch( ), printf( ) and scanf( ). We call them Library Function or
Built-In Functions. It is possible to define your own functions in C. Being able to do this allows
powerful programs to be developed in a modular manner that makes the development and
debugging stages significantly easier than would otherwise be the case.
The basic philosophy of function is divide and conquer by which a complicated tasks are
successively divided into simpler and more manageable tasks which can be easily handled. A
program can be divided into smaller subprograms that can be developed and tested successfully.
A function is a complete and independent program which is used (or invoked) by the main
program or other subprograms. A subprogram receives values called arguments from a calling
program, performs calculations and returns the results to the calling program.
Need For User-Defined Function
Every program must have main function to indicate where the program has to begin its
execution. While it is possible to code any program utilizing only main function, it leads to a
number of problems. The program many become too large and complex and as a result the task of
debugging, testing, and maintaining become difficult. If a program is divided into functional parts,
then each part may be independently coded and later combined into a single unit, these
independently coded programs are called subprograms that are much easier to understand, debug,
and test.
We already know that C support the use of library functions and use defined functions. The
library functions are used to carry out a number of commonly used operations or calculations. The
user-defined functions are written by the programmer to carry out various individual tasks.
There are many advantages in using functions in a program they are:
63 Dr. Sasikala . P
Nrupathunga University
Department of computer science
1. It facilitates top down modular programming. In this programming style, the high level
logic of the overall problem is solved first while the details of each lower level functions
is addressed later.
2. The length of the source program can be reduced by using functions at appropriate
places.
This factor is critical with microcomputers where memory space is limited.
3. It is easy to locate.
4. A function may be used by many other programs this means that a c programmer can
build his own function.
5. A program can be used to avoid rewriting the same sequence of code at two or more
locations in a program.
6. Programming teams does a large percentage of programming. If the program is divided
into subprograms, each subprogram can be written by one or two team members of the
team rather than having the whole team to work on the complex program.
Main Program
B1 B2
64 Dr. Sasikala . P
Nrupathunga University
Department of computer science
Defining Functions
A function is defined as follows:
Type
Functions return a value. The type of this value (int, float, char etc) has to be specified. All
of the standard C types met so far may be used as a function type. Sometimes a return value is not
required, for example if the function prints an error message and then returns, in which case a
return type of void should be used.
function name
This is a label that is used to refer to the function from other code blocks. The rules for
valid names are the same as those for variables.
Parameter list
Values are passed to a function via its parameter list. This is a comma separated list of the
values that the function takes. Each item in the list has a type specification. The parameter list can
be blank, i.e. the function takes no parameters, in this case the keyword void should be used instead
of a list (as is the case with "int main(void)". The names used for the parameters can be different
from those used in the block of code that calls the function.
Code block
The code block contains the operations that constitute the function. The parameters
declared in the parameter list can be used as standard variables within this block. Temporary
variables may also be declared for use within the block. Unless the function has a return type of
void then the function needs to return a value of the correct type. This is done via the return
command (see below).
A simple example
#include <stdio.h>
#include <stdlib.h>
float product(float x, float y)
65 Dr. Sasikala . P
Nrupathunga University
Department of computer science
Out Put:-
Enter any three numbers 10 20 30
Sum = 60
68 Dr. Sasikala . P
Nrupathunga University
Department of computer science
Return Types
As pointed out earlier, a function may or may not send back any value to the calling
function. If it does, it is done through the return statement. While it is possible to pass to the
called function any number of values, the called function can only return one value per call, at
the most.
The return statement can take one of the
following forms. return; or
return(expression);
the first, the ‘plain’ return does not return any value, it acts much as the closing brace of the
function. When a return is encountered, the control is immediately passed back to the calling
function. An example of the use of a simple return is as follows.
if(error) Return;
The second form of return with an expression returns the value of the expression.
Ex:-
int mul(int x, int y)
{
int p;
p=x*y;
return(p);
}
Returns the value of p which is the product of the values of x and y. the last two statements
can be combined into one statement as follows.
return(x*y);
A function may have more than one return statements. This situation arises when the value
returned is based on certain conditions ex
if(x<=0)
return(0);
else
return(1);
69
Dr. Sasikala. P
Nrupathunga University
Department of computer science
No argument
Function1() Function2()
{ {
----------- -----------
----------- -----------
----------- -----------
No return value }
}
}
void starline()
{
int a;
for (a=1;a<60;a++)
printf(“%c”,’*’);
printf(“\n”);
}
71
Dr. Sasikala. P
Nrupathunga University
Department of computer science
main()
{ function1(a1,a2,a3……an)
}
function1(f1,f2,f3….fn);
{ function body;
}
here a1,a2,a3 are actual arguments and f1,f2,f3 are formal
arguments.
72
Dr. Sasikala. P
Nrupathunga University
Department of computer science
3. The calling statement is executed normally and return value is thus assigned to the calling
function.
73
Dr. Sasikala. P
Nrupathunga University
Department of computer science
function statement;
}
The type specifier tells the compiler, the type of data the function is to return.
2. The called function must be declared at the start of the body in the calling function, like
any other variable. This is to tell the calling function the type of data the function is
actually returning. The program given below illustrates the transfer of a floating-point
value between functions done in a multiple function program.
float add(float,float);
double sub(double,double);
main()
{
float x,y;
x=12.345;
y=9.82;
printf(“%f\n” add(x,y));
printf(“%lf\n”sub(x,y);
}
float add(float a, float b)
{ return(a+b);
}
double sub(double p, double q)
{ return(p-q);
}
74
Dr. Sasikala. P
Nrupathunga University
Department of computer science
Function1() No argument
{ Fun2()
----------- {
A=Fun2() -----------
------------ -----------
} Return(a)
With return value }
Nesting of functions:
C permits nesting of two functions freely. There is no limit how deeply functions can be
nested. Suppose a function a can call function b and function b can call function c and so on.
Consider the following program:
75
Dr. Sasikala. P
Nrupathunga University
Department of computer science
int a,b,c;
scanf(“%d%d”,&a,&b);
add(a,b);
}
void add(int x, int y)
{
int z;
z=x+y;
printf(“\nAdd=%d”,z);
sub(x,y);
}
void sub(int p, int q)
{
int z;
z=p-q;
printf(“\nSub=%d”,z);
}
} the above program calculates the ratio a/b-c; and prints the result. We have the following
three functions: main(), ratio() and difference() main reads the value of a,b,c and calls the function
ratio to calculate the value a/b-c) this ratio cannot be evaluated if(b-c) is zero. Therefore ratio calls
another function difference to test whether the difference(b-c) is zero or not.
Recursion
In C it is possible for a function to call itself, a process known as recursion. A function that
calls itself is said to be recursive. A recursive function requires a call to itself and a test to see if
some stop condition has been met bringing to an end the recursion.
76
Dr. Sasikala. P
Nrupathunga University
Department of computer science
int fact=1;
if (n>=1)
for (i=1;i<=n;i++)
fact=fact*i;
return fact;
}
The use of unsigned int in order to ensure that only positive integers are used. Another
way of calculating a factorial comes out of realizing that: i.e. n factorial is n times (n-1) factorial.
main( )
{
int a, fact ;
printf ( "\nEnter any
number " ) ; scanf ( "%d",
&a ) ; fact = rec ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
rec ( int x )
{
int f ;
if ( x == 1 )
return ( 1 ) ;
else
f = x * rec ( x - 1 ) ;
return ( f ) ;
}
Notest
1. This line terminates the recursion process.
2. This is the recursive call to factorial
3. This function has two return statements. This is allowed in C
Recursion is not just for moderately obscure mathematical functions. It turns out that many
problems when considered properly can be written in terms of recursion. The reading/writing of
lists from/to a file can readily be implemented in a recursive manner. Another example is the
Towers of Hanoi problem that was very popular as a toy in Victorian times.
UNIT IV
77
Dr. Sasikala. P
Nrupathunga University
Department of computer science
Ex-int a[2]
For understanding the arrays properly, let us consider the following program:
main( )
{ int x ;
x=5;
x = 10 ;
printf ( "\nx = %d", x ) ;
}
This program will print the value of x as 10. Why so? Because when a value 10 is assigned to x, the
earlier value of x, i.e. 5, is lost. Thus, ordinary variables are capable of holding only one value at a
time. There are situations in which we would want to store more than one value at a time in a single
variable.
Suppose we wish to arrange the percentage marks obtained by 100 students in ascending order. In such
a case we have two options to store these marks in memory:
Construct 100 variables to store percentage marks obtained by 100 different students, i.e. each variable
containing one student’s marks.
Construct one variable (called array or subscripted variable) capable of storing or holding all the
hundred values.
A simple reason for this is, it would be much easier to handle one variable than handling 100
different variables. There are certain logics that cannot be store without use of an array. An array
is a collective name given to a group of ‘similar quantities’. These similar quantities could be
percentage marks of 100 students, or salaries of 300 employees, or ages of 50 employees. What is
important is that the quantities must be ‘similar’. Each member in the group is referred to by its
position in the group.
Ex: per = { 48, 88, 34, 23, 96 }
78
Dr. Sasikala. P
Nrupathunga University
Department of computer science
In C the fourth number is referred as per[3]. This is because in C the counting of elements begins
with 0 and not with 1. Thus, in this example per[3] refers to 23 and per[4] refers to 96. In
general, the notation would be per[i], where, i can take a value 0, 1, 2, 3, or 4, depending on the
position of the element being referred. Here per is the subscripted variable (array), whereas i is
its subscript.
Thus, an array is a collection of similar elements. These similar elements could be all ints, or all
floats, or all chars, etc. Usually, the array of characters is called a ‘string’, whereas an array of ints
or floats is called simply an array. Remember that all elements of any given array must be of the
same type. i.e. we cannot have an array of 10 numbers, of which 5 are ints and 5 are floats.
void main ( )
{ int avg, sum = 0 ;
int i ;
int marks[30] ;
/* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{ printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ;
/* store data in array */
}
Here, int specifies the type of the variable, just as it does with ordinary variables and the word
marks specifies the name of the variable. The [5] however is new. The number 5 tells how many
elements of the type int will be in our array. This number is often called the ‘dimension’ of the
array. The bracket ( [ ] ) tells the compiler that we are dealing with an array.
79
Dr. Sasikala. P
Nrupathunga University
Department of computer science
One-Dimensional Arrays:-
A list of items can be given one variable name using only one subscript and such a variable is
called a single-subscripted variable of a one-dimensional array.
For ex- if we want to represent a set of five numbers, say(33,55,66,77,88)by an array variable
number, then we may declare the variable number as follow
33 marks[0]
55 marks[1]
66 marks[2]
77 marks[3]
marks[4]
88
Type variable-name[size];
The type specifies the type of element that will be contained in the array, such as int, float, or
char and the size indicates the maximum number of elements that can be stored inside the array.
Ex-float height[50];
Declares the height to be an array containing 50 real elements. Any subscripts o to 49 are valid.
80
Dr. Sasikala. P
Nrupathunga University
Department of computer science
The c language treats character strings simply as arrays of characters. The size in a character
string represents the maximum number of characters that the string can hold.
Char n[12];
Here declare the variable n as a character array variable that can hold a maximum of 10
characters. Suppose we read the following string constant into the string variable name.
“Bhosle Smita”
Each character of the string is treated as an element of the array name and is stored in the memory
as follow.
n[0] n[1] n[2] n[3] n[4] n[5] n[6] n[7] n[8] n[9] n[10] n[11] n[12]
‘B’ ‘h’ ‘o’ ‘s’ ‘l’ ‘e’ ‘’ ‘S’ ‘m’ ‘I’ ‘t’ ‘a’ ‘\0’
When the compiler sees a character string. It terminates it with an additional null character. The
element n[12] holds the null character ‘\0’. When declaring character arrays, we must allow one
extra element space for the null terminator. Initialization of one – Dimensional Arrays
After an array is declared, its elements must be initialized. Otherwise, then will contain garbage
value. An array can be initialized at either of the following stages.
We can initialize the elements of arrays in the same way as the ordinary variables when they are
declared.
Syntax:
float total[5]={0.0,15.75,-10};
Here initialize the first three elements to 0.0, 15.75 and -10 and the remaining two elements to
zero.
We also declare the array as variant. In that no need to enter the size of array.
Ex int a[]={1,3,4};
81
Dr. Sasikala. P
Nrupathunga University
Department of computer science
that is called the variant in that we can store the number of element. Similar, We can also declare
the character array but we must end the string with ‘\0’ ex-char
name[]={‘b’,’h’,’o’,’s’,’l’,’e’,’\0’}’
An array is a collection of similar elements. The first element in the array is numbered 0, so the
last element is 1 less than the size of the array. An array is also known as a subscripted variable.
Before using an array its type and dimension must be declared.
82
Dr. Sasikala. P
Nrupathunga University
Department of computer science
However big an array its elements are always stored in contiguous memory locations. This is a
very important point which we would discuss in more detail later on.
/*Write a program to Display Given No using array */
#include<stdio.h>
#include<conio.h>
void main() {
int a[10],i;
clrscr();
printf(“\n\n\nEnter The 10 Element");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
printf(“\n\nDisplay all Entred num ");
for(i=0;i<=9;i++)
{
printf(“\n%d",a[i]);
}
getch(); }
Two – Dimensional Arrays
So far we have discussed the array variables that can store a list of values. There could be situations
where a table of values will have to be stored. A two dimensional array can be used to represent of
rows and columns and is also known as a matrix. The matrix in mathematics is a two dimensional
array. Ex- rows and column. The element of two dimensional array is indicated by the row and
column number in which it is located. The element of matrix is written as a[i][j] where I stands for
row and j stands for column.
Syntax:
Data type array name[row_size][column_size];
Like one-dimensional array, two- dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
83
Dr. Sasikala. P
Nrupathunga University
Department of computer science
Initializes the element of the first row to zero and the second row to one. The initialization is
done row by row. The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}};
By surrounding the elements of the each row by braces. We can also initialize a two-dimensional
array in the form of a matrix as shown below.
int table[2][3]={
{0,0,0},
{1,1,1}
};
Entering values to Two-Dimensional array using scanf function.
The value can be entered to a 2-d array using scanf function in the nested for statement where the
outer loop generates the row number and inner loop generate column number.
Examples:-
int a[3][3];
for(i=0;i<=2;i++){
for(j=0;j<=2;j++) {
scanf(“%d”,&a[i][j]);
}
}
Where a is two dimensional arrays the I is an different from 0 to 2 and j is different from 0 to 2.
Hence matrix of 3*3 orders is read by this statement.
The value can be read to a 2-d array using printf function in the nested for statement where the
outer loop generates the row number and inner loop generate column number.
Examples:-
int a[3][3];
for(i=0;i<=2;i++)
{ for(j=0;j<=2;j++)
{ printf(“%d”,a[i][j]);
84
Dr. Sasikala. P
Nrupathunga University
Department of computer science
}
}
for(i=0;i<3;i++){
for(j=0;j<3;j++)
matsum[i][j] = mat1[i][j] + mat2[i][j];
}
85
Dr. Sasikala. P
Nrupathunga University
Department of computer science
printf(“\n");
}
printf(“\n The values in Addition of Two Matrices are :\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++) {
printf(“\t [%d][%d] = %d ",i,j,matsum[i][j]); }
printf(“\n");
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,k;
clrscr();
printf(“\n\n\nEnter The 10 Element");
for(i=0;i<10;i++) {
scanf("%d",&a[i]);
}
for(i=0;i<9;i++)
{
for(j=i+1;j<=9;j++)
{
if(a[i]>a[j])
{
k=a[i];
a[i]=a[j];
a[j]=k;
}
}
}
printf(“\n\nDisplay all Entred num in ascending")En
for(i=0;i<=9;i++)
printf(“\n%d",a[i]);
getch();
}
86
Dr. Sasikala. P
Nrupathunga University
Department of computer science
#include<stdio.h>
#include<conio.h>
void main()
{ int a[2][2],b[2][2],c[2][2];
int i,j,n;
clrscr();
for(i=0;i<2;i++)
for(j=0;j<2;j++)
c[i][j]=a[i][j]-b[i][j];
String:-
A string is a sequence of characters that is treated as a single data item. We have used string in a
number of examples in the past. Any group of characters defined between double quotation
marks is a string constant.
C does not support string as a data type. However, it allows us to represent string as character
arrays. In c therefore, a string variable is any valid c variable name and is always declared as an
array of character. The general form of declaration of string variable is.
char string_name[size];
87
Dr. Sasikala. P
Nrupathunga University
Department of computer science
ex
main() {
char name[6]=”Bhosle”;
clrscr();
for(i=0;i<=6;i++)
printf(“My name is %s”,name[i]);
getch();
}
Reading String:-
The familiar input function scanf can be used with %s format specification to read in a string of
characters.
char address[10];
scanf(“%s”,address);
The problem with the scanf function is that it terminates its input on the first white space it finds. A
white space includes blanks, tabs and new lines.
Ex New York
Then only the string “New” will be read into the array address, since the blank space after the word
‘New’ will terminate the reading of string. The scanf function automatically terminates the string that
88
Dr. Sasikala. P
Nrupathunga University
Department of computer science
is read with a null character and therefore the character array should be large then the string. In that
the ampersand (&) is not required before the variable name.
Writing String:-
We have used extensively the printf function with %s format to print strings to the screen. The format
%s can be used to display an array of characters that is terminated by the null character.
Ex:- printf(“%s”,name);
Can be used to display the entire contents of the array name.
main()
{
int c,d;
char string[]=”C programming”;
printf(“\n\n”);
for(c=0;c<=11;c++)
{
d=c+1;
printf(“|%-12.*s|\n”,string);
}
for(c=11;c>=0;c--)
{
d=c+1;
printf(“|%-12.*s|\n”,d,string);
}
printf(“------------------------“);
}
getch();
}
Standard Library String Function.
89
Dr. Sasikala. P
Nrupathunga University
Department of computer science
The c library support a large number of string handling functions that can be used to carry out
many of the string manipulation discussed so far.
strcat function:-
The strcat function join two string together. It takes the following form
strcat(string1,string2)
Sstring1 and string 2 are character arrays, when the function strcat is executed, string2 is
appended to string1. It does so by removing the null character at the end of string1 and placing
string2 from there. The string at string2 remains unchanged.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char source[]="Bhosle";
char target[20]="Hello";
clrscr();
strcat(target,source);
printf(“\n\t\t---------OUTPUT----------\n");
printf(“\n\n \t\tTarget String:=%s",target);
getch();
}
Strlen
This function count numbers of character present in the string it means. it return length of the
string consider following example to understand the use of strlen function.
Integer variable=strlen(string);
Ex:- strlen function
Calculate the length of the string which return integer value. That value is assign to integer
variable.
90
Dr. Sasikala. P
Nrupathunga University
Department of computer science
#include<stdio.h>
#include<conio.h>
#include<string.h> void
main()
{ char a[20]; int
n; clrscr();
printf(“ \n\n\t Enter the string : ");
scanf("%s",&a);
n=strlen(a);
printf(“\n\n\tThe length of given string : %d ",n);
n=strupr(a);
printf(“ \n\n\t String in UPPER case : %s",a);
getch();
}
Strcpy
This string library function is used to copy one string into another string.
Syntax:-
Strcpy(source string, target string)
#include<stdio.h>
#include<conio.h>
#include<string.h> void
main()
{ char a[6]="Bhosle";
char b[6];
clrscr();
printf(“string= %s",a);
strcpy(b,a);
printf(“string %s",b);
getch();
}
Strcmp
This function compare to different thing & finds out whether given string are some or
different the two strings are compared char offend by character until there is mismatch or end of
one of string reached it is two string are identical (same) then the function return a 0 value but if
they are not same then it returns numeric difference between the ASCII value of first non
matching pains of character.
91
Dr. Sasikala. P
Nrupathunga University
Department of computer science
#include<stdio.h>
#include<conio.h>
#include<string.h> void
main()
{
char ab[10],ar[10];
clrscr();
printf(“\n\t\t---------OUTPUT----------\n");
strcpy(ar,ab);
if(strcmp(ab,strrev(ar))==0)
{
printf(“\n \t\tThis is Palendrome String");
}
else
{
printf(“\n\t\tThis is Not Palendrome string");
}
getch();
}
Strupper
This function is used to convert the string lower case letter into upper case letter. If given string is
already in the upper case letter it remains as it is.
Ex:
void main()
{
char name[15]=”smita”;
strupper(name);
printf(“name= %s”,name);
getch();}
}
92
Dr. Sasikala. P
Nrupathunga University
Department of computer science
Strlwr
This function is used to convert the string upper case letter into lower case letter. If given string is
already in the lower case letter it remains as it is.
Ex:
void main()
{
char name[15]=”smita”;
strlwr(name);
printf(“name= %s”,name);
getch();
}
Strrev
This function reverse the given string and stores it at the same place.
main()
{
static char college[6]=”COCSIT”;
strrev(college);
printf(“Name of the College is %s”,college);
getch();
}
Structure Definitions
A structure definition creates a format that may be used to declare the structure variable. Let
us consider an example that a process of structure definition and the creation of structure
variable. Syntax:-
struct tag_name
{
Data_type member1;
Data_type member2;
------------------------
------------------------
};
Consider a book database consisting a book_name, author, page_no, and price. We can define
a structure to hold this information as.
struct book_bank
{
93
Dr. Sasikala. P
Nrupathunga University
Department of computer science
char title[10];
char author[15];
int page;
float price;
}
The keywords struct declares the a structures to hold the details of four fields namely title,
author, pages, and price. These fields are called as structure elements or members. Each member
may be belong to a different type of data book_bank is the name of structure and is called as
structure tag. The tag name may be used subsequently to declares the variables that have the tag’s
structure.
Note that the above declaration has not declared any variables. It simply describes a format
called template to represent a information as shown below.
struct book_name
{
title array of 10 characters.
author array of 15 character.
pages integer.
price float.
}
We can declare the structure variable using the tag name anywhere in the program.
In defining a structure you may note the following syntax.
-The template is terminated with a semicolon (;)
-While the entire declaration is considered as a statement, each member is declared
independently -for its name and type in a separate statement inside the template. -The
tag name can be used to declare structure variable of its type, later in the program.
After defining a structure format we can declare variable of that type. A structure variable
declaration is similar to the declaration of variable of any other data types. It includes the
following elements.
1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by commas.
4. A terminating semicolon.
struct book_bank
{
char title[10];
char author[15];
94
Dr. Sasikala. P
Nrupathunga University
Department of computer science
int pages;
float price;
}book1,book2,boo3;
Or
struct book_bank book1,book2,book3;
The book1, book2, book3 is the structure variable representing three books, but does not
includes the tage name for later use in declarations. Normally, structure definition appears at the
begging of the programming file, before any variables or functions are defined. They may also
appear before the main, along with macro definition, such as #define. In such cases, the
definition is global and can be used by other functions as well.
Structure Initialization:
Like any other data type, a structure variable can be initialized however a structure must be
declared as static if it is to be initialized inside a function. Ex
main()
{
static struct
{
int weight;
float height;
}student={60,180.65};
--------------
--------------
}
It assign the value 60 to student.weight and 180.65 to stud.height. there is one-to-one
corresponding between the members and their initializing values.
A many type of variables is possible in initialization a structure. The following statements
initialize two structure variables. In this it is essential to use tag name.
main()
{
95
Dr. Sasikala. P
Nrupathunga University
Department of computer science
struct st_record
{
int weight;
float height;
};
struct st_record student1={60,180.75};
struct st_record student2={53,170.60};
-------------
-------------
}
Another method to initialize a structure variable outside the function as shown follow.
struct stud_record
{
int weight;
float height;
}student1={60,180,75};
main()
{
struct stud_record student 2={53,170.60};
-------------------------
-------------------------
}
C langue does not permits the initialization of individual structure members within the template.
The initialization must be done only in the declaration of actual variables.
Introduction to Union:
Unions are a concept borrowed from structure and therefore follow the same syntax as
structures. However, there is major distinction between them in terms of storage. In structures,
each member has its own storage location, whereas all the members of a union use the same
location. This implies that, although a union may contain many members of different types, it can
handle only one member at a time. Like structures, a union can be declared using the keyword
union as follows1.
union item
{
int m;
float x;
char c;
}code;
96
Dr. Sasikala. P
Nrupathunga University
Department of computer science
This declares a variable code of type union item. The union contains three members, each
with a different data type. However, we can use only one of them at a time. This is due to the fact
that only one location is allocated for a union variable.
Storage of 4 bytes
1000 1001 1002 1004
The compiler allocates a piece of storage that is large enough to hold the largest variable type
in the union. In the declaration above, the member x requires 4 bytes which is the largest among
the members.
To access a union member, we can use the same syntax that we use for structure members.
code.m
code.x
code.c
are all valid membe variables. During accessing , we should make sure that we are accessing the
member whose value is currently stored.
Code.m=455;
Code.x=456.66;
Printf(“%d”,code.m);
In effect, an union creates a storage location that can be used by any one of its members at a
time. When a different member is assigned a new value. Ex:- main()
{
union index
{
int a;
float b;
char c;
};
union index e;
e.a=30;
printf(“%d”,e,a);
e.b=44.55;
printf(“%d”,e.b);
e.c=’A’;
printf(“%c”,e.c);
getch();
}
97
Dr. Sasikala. P