C Book
C Book
C Book
PL Binary
Programmer Translator Computer Software
Trnaslators:
A translator is a system software which converts programming language
code into binary format.
Translators are 3 types:
1. Compiler
2. Interpreter
3. Assembler
Compiler: - It is a system software which converts programming language
code into binary format in a single step except those lines are having error.
1
C-LANGUAGE
2
C-LANGUAGE
On the 8th of December 2011, latest version of C is released with the name
called C11.
C11 introduced several language features:
1. Anonymous structures.
2. Improved Unicode support.
3. Bounds checked functions.
4. Generic Macros
Applications of C
C programming language can be used for different types of applications
like:
- System software development that is operating systems and
compiler. Unix operating system is developed by using “C”.
- Graphic related applications like PC and Mobile games.
- Application software development.
- Any kind of mathematical expressions can be evaluated,
3
C-LANGUAGE
4) Key words cannot be used for any other purpose like variable
names (or) function names.
Key words: -
There are 32 key words in “C”.
auto, break, case, char, const, continue, default, do, double , else, enum,
extern, float, for, goto, if, int, long, register, return, short, signed, size of,
static, struct, switch, type def, union, unsigned, void, volatile, while
Preprocessor directives:-
These are used to pass the instructions to the compilers. This is
always begin with a hash(#) sign. Two most frequently used directives are
#include and #define.
4
C-LANGUAGE
#include<stdio.h>
stdio.h stands for Standard Input and Output header file.
Ex: printf(),scanf()….
#include<math.h>
Ex: sqrt(),pow(),sin()
#include<string.h>
Ex: strlen(), strcmp()
ii) #define:- This is used to modify programs by declaring and defining a
word as representing a constant value.
#define A 10
#define PI 3.14
The pre compiler substitute the value of 3.14 whenever “PI” is appears.
main():- Every “C” program should contain at least one function i.e
main(). Every program execution starts at main function. Every
program should contain only one main().
Declaration of variables:-
Variable:- Variable is used to refer the memory location where a
particular value is to be stored.
Rules for defining variables:-
1) Every variable starts with alphabet.
2) Commas(,) or blank spaces are not allowed. It allows only a
special character i.e,underscore(_).
3) Variables are case sensitive.
4) Variables names cannot be same as keywords.
5) Max. length of variable is 32 characters.
Data type:-
A data type decides the amount of memory allocated to a variable to
store a particular type of data.
“C” has five basic data types. They are char, int, float, double, void.
5
C-LANGUAGE
Rules for int data type :- An int data type must have at least one digit it
accepts only whole numbers. It does not have a decimal point.
Ex: int a;
a=10;
a=10.5 //10.
Rules for float data type:- It accepts both whole numbers and fractional
numbers.
Ex: float a;
a=10;
a=10.5;
Format specifies:-
Char %c
int %d
float %f
long int %ld
double %lf
string %s
Escape sequences:-
\n next line
\t tab space
\0 null value
Comments in ‘C’:
Comments in C begin with /*……………………. */.
These are ignored by the C compiler.
6
C-LANGUAGE
Syntax :-
putchar(character); or
putchar(variable name);
Ex: putchar(‘A’); or ch=B
putchar(ch);
#include<stdio.h>
main()
{
char ch;
ch=’R’;
putchar(ch);
putchar(‘*’);
}
#include<stdio.h>
main()
{
char ch;
int a;
long int b;
float c;
double d;
clrscr();
ch='A';
a=55;
b=45000;
c=4.5;
d=123.444;
7
C-LANGUAGE
getchar():- It reads a character from the keyboard and waits for carriage
return.
Syntax:- variable=getchar();
Eg:- ch=getchar();
#include<stdio.h>
main()
{
char ch;
clrscr();
puts("Enter a character:\t");
ch=getchar();
printf("characters is %c\t",ch);
getch();
}
getche():- It is used to read a character from the keyboard and does not
waits for carriage return.
Syntax:- variable=getche();
Ex: ch=getche();
#include<stdio.h>
main()
{
char ch;
clrscr();
puts("Enter a character:\t");
ch=getche();
printf("characters is %c\t",ch);
getch();
}
gets():- It reads a string from the keyboard.
Syntax:- gets(variable);
Ex: gets(s);
8
C-LANGUAGE
#include<stdio.h>
main()
{
char s[30];
clrscr();
puts("Enter a name:\t");
gets(s);
printf("name is %s\t\t",s);
getch();
}
#include<stdio.h>
main()
{
char ch,s[20];
int a;
long int b;
float c;
double d;
clrscr();
printf("Enter a character");
scanf("%c",&ch);
printf("Enter a integer value");
scanf("%d",&a);
printf("Enter a long integer");
scanf("%ld",&b);
printf("Enter a float value");
scanf("%f",&c);
printf("Enter a double");
scanf("%lf",&d);
printf("Enter a string");
scanf("%s",&s);
getch();
}
9
C-LANGUAGE
10
C-LANGUAGE
{
float a,s;
clrscr();
printf("Enter a number \t");
scanf("%f",&a);
s=sqrt(a);
printf("square is %f",s);
getch();
}
Exercises:
1) Calculate the simple interest.
2) Accept two numbers and swap them using third variable.
3) Accept roll number, name and three subjects of marks of student
and calculate the total, average and display roll number, name,
three subject of marks, total and average.
4) Accept two numbers and display the sum and average.
5) Accept n Kilometers and convert to meters.
6) Accept n meters and convert to kilometers.
11
C-LANGUAGE
SELECTION STATEMENTS
These are also called decision making statements.
By using them, we can create conditional oriented block.
When we are working with selection statements, if condition is true
then block is executed, if condition is false then corresponding block
will be ignored.
a. if condition.
b. switch statement.
c. conditional operators.
d. goto statement.
if condition:-
simple if:-
syntax:-
if<condition>
{
statement(s);
}
#include<stdio.h>
main()
{
int empno,salary;
char name[25];
clrscr();
printf("enter employee number”);
scanf("%d”,&empno);
printf(“Enter employee name:”);
scanf(“%s”,&name);
printf(“Enter salary:”);
scanf(“%d”,&salary);
if(salary>5000)
{
12
C-LANGUAGE
salary=salary+500;
}
printf(“Salary=%d”,salary);
getch();
}
if-else statement:--
syntax:-
if<condition>
{
statement(s);
}
else
{
statement(s);
}
13
C-LANGUAGE
statements 3;
}
else
{
statement 4;
}
nested if
syntax:
if(condition1)
{
if(condition2)
{
statements1;
}
else
{
statements2;
}
}
else
if(condition3)
{
statements3;
}
else
{
statements4;
14
C-LANGUAGE
15
C-LANGUAGE
16
C-LANGUAGE
Exercises
1) Accept a character and display the character is capital letter or small
letter or digit or other special symbol.
2) Accept a character and display the character is vowel of consonant.
3) Accept a year and check the year is leap year or not.
4) Accept roll no, name and three subjects of marks and calculate the
total, average, result and class display the student details.
17
C-LANGUAGE
CONDITIONAL OPERATORS
Conditional operators are used to execute a condition in a single
line. This also called as ternary operation.
Syntax:
variable=(condition)? value if true: value if false.
Exercises:
1) Accept four numbers and display the biggest number (using
ternary operation)
18
C-LANGUAGE
SWITCH STATEMENT
Switch Statement:- switch statement is multi decision statement. It is
similar to if-else-if statement.
syntax:-
switch(expression)
{
case<constant 1>
statements;
break;
case<constant 2>
statements;
break;
case<constant 3>
statements;
break;
default:
statements;
}
19
C-LANGUAGE
printf("INVALID CITY");
}
getch();
}
(OR)
#include<stdio.h>
main()
{
char ch;
20
C-LANGUAGE
clrscr();
printf("Enter a character");
scanf("%c",&ch);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("VOWEL");
break;
default:
printf("CONSONENT");
}
getch();
}
Exercises:
2) Accept two numbers and display the 1 for sum, 2 for subtraction, 3
for multiplication and 4 for division and 5 for exit.(using switch
statement for particular operation)
21
C-LANGUAGE
LOOPS
LOOPS:- loops are used to execute set of statements more then once
until to reach the given condition is true.
Basic purpose of loop is code repetition.
In implementation when the repetitions are required then recommended to
go for loops.
22
C-LANGUAGE
23
C-LANGUAGE
n=n/10;
}
printf(“Reverse no=%d”,r);
getch();
}
24
C-LANGUAGE
}
printf("GCD of %d and %d is %d",m,n,y);
}
Exercises:
1) Display “n” numbers in reverse order.
2) Accept a number and display sum of digits.
3) Accept a number and display sum of even digits and sum of odd
digits.
4) Accept a number and display the number is palindrome or not.
(Reverse number is given number)
5) Accept a number and display the number is prime number or not.
A number is divisible by one and itself.
25
C-LANGUAGE
for loop:-
syntax:-
for(initialization; condition; iteration)
{
statements;
}
When we are working with for loop, always execution process will
start from initialization.
Initialization part will be executed only once when we are passing
the control within the body first time.
After execution of initialization part, control will pass to condition, if
condition evaluated is true, then control will pass to statement block.
After execution of statement block, control will pass to iteration, from
iteration once again it will pass back to condition.
Always repetition will come between condition, statement block and
itetation only.
When we are working with for loop, everything is optional but
mandatory to place 2 semicolons.
while() error
for(;;) valid
When the condition part is not given in for loop, then it repeats
infinite times.
When we are working with for loop, it repeats in anti clock direction.
The difference between while loop and for loop is in while loop
initialization declare the before beginning of the loop. Condition
declared in the loop and change of condition declared in body of the
loop.
26
C-LANGUAGE
int n,i;
clrscr();
printf("Enter a range");
scanf("%d",&n);
for(i=1;i<=n;i=i+2)
printf("%d\t ",i);
getch();
}
27
C-LANGUAGE
printf(“%d\t”,i);
getch();
}
28
C-LANGUAGE
int i,n,s;
clrscr();
printf("Enter n value");
scanf("%d",&n);
for(i=1;i<=20;i++)
{
s=i*n;
printf("%d * %d = %d\n",i,n,s);
}
getch();
}
Nested Loops
It is a procedure of constructing a loop within an existing loop body.
When the repetitions are required then go for loops, if complete loop
body required to repeat n number of times then go for nested loop.
In C programming language, we can place upto 255 nested blocks.
When we are working with nested loops, always execution is started
from outer loop condition.
When the outer loop condition is true, then control will pass to outer
loop body.
In order to execute the outer loop body, if any loop occur those are
called inner loops.
When the inner loop occurs, then check inner loop condition.
If inner loop condition is true then control will pass within the inner
loop body and until the inner loop condition become false. When
inner loop condition is false then control will pass to outer loop and
again check the condition.
29
C-LANGUAGE
getch();
}
30
C-LANGUAGE
2 2
3 3 3
4 4 4 4
5 5 5 5 5
#include<stdio.h>
main()
{
int i,j,k;
clrscr();
for(i=1;i<=5;i++)
{
printf("\n");
for(k=1;k<=5-i;k++)
printf(“ “);
for(j=1;j<=i;j++)
printf("%3d",i);
}
getch();
}
Pascal triangle.
1
1 1
31
C-LANGUAGE
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
#include<stdio.h>
main()
{
int q,n,x,bin,r;
clrscr();
printf("Enter how many rows:");
scanf("%d",&n);
for(q=0;q<n;q++)
{
for(r=40-3*q;r>=0;r--)
printf(" ");
for(x=0;x<=q;x++)
{
if(x==0 || q==0)
bin=1;
else
bin=bin*(q-x+1)/x;
printf("%3d ",bin);
}
printf("\n");
}
getch();
}
Exercises:
1) Display the following series.
5 55 555 5555
2) Accept a number and display the number is prime number or not.
3) write the Fibonacci series program for end value.
1) Display the following series 1 2 2 4 8 32 …….
2) Display the following series
1 2 8 48 384 …………
3) display the following series 0 1 3 6 10 15 21 …………n, given
number .
4) Display the following series
x x2 x3 x4…….
8) Display the following series
1/x 1/x2 1/x3 1/x4 …………..
9)Accept “n” number and display the smallest number.
7) To display big , small values of “n” numbers.
8) Accept a number and display the number is perfect number or not.
Sum of factors equal to given number.
32
C-LANGUAGE
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
1
1 *
1 * 3
1 * 3 *
1 * 3 * 5
1
* *
1 2 3
* * * *
1 2 3 4 5
33
C-LANGUAGE
1234
12345
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
34
C-LANGUAGE
DO WHILE LOOP
Syntax:-
do
{
statements;
}
while(condition);
In implementation when we required to repeat the statement block
atleast once then go for while loop.
When we are working with do-while loop, post checking process
occurs that is after execution of statement block, condition part is
executed.
When we are working with do-while loop, it repeats in clock
direction.
According to syntax, semicolon must be required at the end of the
body.
It is similar to while loop. The main difference between “while” loop
and “do while” loop is in “while” loop first checks the condition then
executes the loop. In do while loop first execute the statements and
then checks the condition.
Do while loop execute at least one time.
Accept two numbers and display the sum until user enter the choice
is Y.
#include<stdio.h>
main()
{
int a,b,s;
char ch;
clrscr();
35
C-LANGUAGE
do
{
printf("Enter two numbers:");
scanf("%d %d",&a,&b);
s=a+b;
printf("Sum=%d\n",s);
Accept a number and display in reveres order until user enter the
choice is y.
#include<stdio.h>
main()
{
int a,b,s;
char ch;
clrscr();
do
{
s=0;
printf("Enter a numbers:");
scanf("%d",&a);
while(a>0)
{
b=a%10;
s=b+(s*10);
a=a/10;
}
printf(“Reverse number=%d\n”,s);
printf("Check another numbers(Y/N)?");
fflush(stdin);
scanf("%c",&ch);
}
while(ch=='Y' || ch=='y');
getch();
}
36
C-LANGUAGE
37
C-LANGUAGE
output: 2 4 6 8 32 34 36 38 40
When the continue statement is executing within the loop body then
control will pass back to the condition without executing remaining
statements.
GOTO STATEMENT
goto is a keyword, by using this we can pass the control anywhere
within the program.
goto keyword always required an identifier called label.
Any valid identifier followed by colon is called label.
Generally goto statement is called unstructured programming
statement because it breaks the role of structured programming
language.
In implementation, we required to take the repetition process without
using loop then recommended to go for goto statement.
Syntax:-
<label>:
statement;
goto<label>;
Ex:
#include<stdio.h>
main()
{
printf("A");
printf("B");
goto ict;
printf("Welcome");
ict:
printf("C");
printf("D");
getch();
}
38
C-LANGUAGE
i=i+1;
goto ict;
}
getch();
}
Exercises:
39
C-LANGUAGE
ARRAYS
An array is a derived datatype in C which is constructed from
fundamental data type of C programming language.
An array is a collection of similar types of data elements in a single
entity.
In implementation when we require ‘n’ no. of values of same data
type, then recommended to create an array.
When we are working with arrays always static memory allocation
will happen that is compile time memory management.
When we are working with arrays always memory is constructed in
continuous memory location that’s why possible to access the data
randomly.
When we are working with arrays all values will share same name
with unique identification value called “index”.
Always array index must be required to start with ‘0’ and ends with
size-1.
When we are working with arrays we required to use array subscript
operator is [ ].
Always array subscript operator requires ‘1’ argument of type
unsigned integer constant, whose value is always ‘>0’ only.
Declaration of array :-
Syntax:-
datatype arrayname[size or subscript or boundary];
Ex:- int a[5];
Properties of Array:
Size no. of elements, sizeof no.of bytes.
1. int a[5];
Size 5
sizeof(a) 10 bytes
2. int a[5];
int a[0]
int a[1]
int a[2]
int a[3]
int a[4]
40
C-LANGUAGE
Types of arrays:-
There are three types of arrays available in “c” language.
Single dimensional array:- Variable can have only one subscript is called
single dimensional arrays.
Ex:- int a[5]
41
C-LANGUAGE
5. int arr[2][3]={10,20,30,40,50,60};
10arr[0][0] 20arr[0][1] 30arr[0][2]
40arr[1][0] 50arr[1][1] 60arr[1][2]
By using above initialization process, we required to initialize all
elements in sequence only that is selected no. of elements cannot
be initialized.
6. int arr[3][3]={
{10},
{20,30},
{40,50,60}
};
arr[0][0]=10 arr[0][1]=0 arr[0][2]=0
arr[1][0]=20 arr[1][1]=30 arr[1][2]=0
arr[2][0]=40 arr[2][1]=50 arr[2][2]=60
In initialization of 2D array, it specific no. of elements are not
initialized then remaining all elements are initialized with zero.
42
C-LANGUAGE
43
C-LANGUAGE
main()
{
int i,j,a[50],n,temp;
clrscr();
printf("Enter how many elements:");
scanf("%d",&n);
printf("Enter %d Values:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("The elements in ascending order is:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}
Exercises:
1) Enter 5 elements into an array and display in reverse order.
2) Accept n elements into an array and display that elements.
3) Accept n elements into an array and display in reverse order
4) Accept n elements into an array and display sum of elements and
average of elements.
5) Accept “n” elements into an array and display big and smallest
numbers of the array.
6) Accept n elements and display descending order.
7) Accept n numbers of students to display the student details.
44
C-LANGUAGE
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
printf("\nMatrix is:\n");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
getch();
}
Shortcut keys:-
Ctrl+kb beginning of the block.
Ctrl+kk end of the block.
Ctrl+kc copy of the block.
Ctrl+kv move the block.
Ctrl+kh hide the block.
Ctrl+y delete the entire line.
45
C-LANGUAGE
{
printf("\n");
for(j=0;j<m;j++)
printf("%d\t",a[j][i]);
}
getch();
}
46
C-LANGUAGE
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
printf("\nMatrix is:\n");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
det=a[0][0]*a[1][1]-a[0][1]*a[1][0];
if(det==0)
printf("INVERSE IS NOT POSSIBLE");
else
{
det=1/det;
b[0][0]=a[1][1];
b[1][1]=a[0][0];
b[0][1]=-a[0][1];
b[1][0]=-a[1][0];
printf("\nThe inverse of matrix is:\n");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%.2f\t",det*b[i][j]);
}
}
getch();
}
47
C-LANGUAGE
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
}
printf("\nMatrix A is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
}
printf("\nMatrix B is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",b[i][j]);
}
printf("\nResult Matrix is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t",c[i][j]);
}
}
getch();
}
48
C-LANGUAGE
49
C-LANGUAGE
Exercises:
1) Display m*n matrix.
2) Accept m*n matrix and display the sum of diagonal elements.
3) Accept two m*n matrix and display the subtraction of matrix.
50
C-LANGUAGE
STRINGS
Character array or group of characters or collection of characters
are called strings.
In implementation when we are manipulating multiple characters
then recommended to go for strings.
Within the ' ' any constant is called character constant, within the " "
any content is called string constant.
Character constant always returns an integer value that is ASCII
value of a character.
String constant always returns base address of a string.
Syntax:-
char variable [size];
Ex:- char name[25];
Reading Strings:-
The “scanf ” function can be used with “%s” format specification to
read the string.
Ex:- scanf(“%s”,&name);
The problem with scanf function is that it terminates we can
enter the space.
gets:-It is used to accept string from the keyboard until we can press
enter.
gets(name);
String Functions:-
(1) Strlen: -This function is used to count the number of character in a
string.
Syntax: - n=strlen(string)
Accept a string and display the length of the string using string
function.
#include<stdio.h>
#include<string.h>
main()
{
char str[50];
51
C-LANGUAGE
int l;
clrscr();
printf("Enter a string:");
gets(str);
l=strlen(str);
printf("String length=%d",l);
getch();
}
Accept a string and display the length of the string without using
string function.
#include<stdio.h>
main()
{
char str[50];
int l=0,i;
clrscr();
printf("Enter a string:");
gets(str);
for(i=0;str[i]!='\0';i++)
l++;
printf("String length=%d",l);
getch();
}
52
C-LANGUAGE
main()
{
char s1[50],s2[50];
int i;
clrscr();
printf("Enter a string:");
gets(s1);
for(i=0;s1[i]!='\0';i++)
s2[i]=s1[i];
s2[i]='\0';
printf("String 1=%s\n",s1);
printf("String 2=%s",s2);
getch();
}
Strcat :- This function is to combine the two strings. This process is called
as concatenation.
Syntax:- strcat(string1,string2);
53
C-LANGUAGE
for(i=0;s1[i]!='\0';i++)
s3[i]=s1[i];
s3[i]=' ';
for(j=0;s2[j]!='\0';j++)
s3[i+j+1]=s2[j];
s3[i+j+1]='\0';
printf("Result String =%s\n",s3);
getch();
}
Strcmp:-This function is used to compare the two strings are equal or not.
If two strings are equal then this function returns the value is zero.
If two strings are not equal, it returns numeric difference between
the ASCII values of non-matching characters.
Syntax:- i=strcmp(string1, string2);
54
C-LANGUAGE
55
C-LANGUAGE
l=strlen(s1);
for(i=l-1;i>=0;i--)
{
s2[j]=s1[i];
j++;
}
s2[j]='\0';
printf("Reverse String =%s\n",s2);
getch();
}
Exercises:
1)Accept a name and display number of vowels and consonants in that
strings
2) Accept a string and display the string is palindrome or not
3) Accept a string and count the number of words in that string
4) Accept n strings and display in ascending order.
56
C-LANGUAGE
FUNCTIONS
Self contained block of one or more statements which is designed for a
particular task is known as function.
Advantages: -
1. Module approach: - By using functions we can develop the application
in module format that is procedure oriented language concept.
2. Reusability: - By using functions we can create reusability blocks that
is develop once and use multiple times.
3. Easy to Debug: - By using functions, we can easily debug the program.
4. Code maintenance: - When we are developing the application by using
functions, then it is easy to maintain code for future enhancements.
Syntax of Function:-
returntype functionname (arguments list)
{
declaration of local variables;
Statements;
return statement;
}
According to syntax, specifying the return type, parameters and return
statements are optional.
All the rules of variable declarations are applicable to function name also
57
C-LANGUAGE
About main(): -
main is an identifier in the program which indicates startup point of
an application.
main is a user defined functions with pre-defined signature for
Linker.
A Linker is a assembly language program which always decides
startup point of the program is main.
It is possible to develop a program without using main function also.
In this case compilation is success but linking is failure.
Multiple main functions are not possible.
When we are developing .lib/.obj files for other projects then doesn’t
required to include main function.
A C program is a combination of pre-defined and user defined
functions, compilation process starts from top to bottom and
execution process starts on main() and ends with main() only.
Rules of functions :-
C program is a collection of one or more functions .
A function “gets” called when the function name is followed by “;”.
Ex:- c=sum(a,b);
58
C-LANGUAGE
message()
{
printf(“Data Info tech computers\n”);
}
The order in which the function are defined in a program and the order
in which they get called need not necessary to be same.
Ex:-
#include<stdio.h>
main()
{
clrscr();
printline();
message();
printline();
getch();
}
message()
{
printf(“Data Info tech computers\n”);
}
printline()
{
printf(“--------------------------------------\n”);
}
59
C-LANGUAGE
show();
getch();
}
message()
{
printf(“Data Info tech computers\n”);
}
show()
{
printf("Hello");
message();
}
Function categories:-
These are three types.
1) Function with no of arguments and no return values.
2) Function with arguments but no return values.
60
C-LANGUAGE
Area of rectangle
#include<stdio.h>
main()
{
int l,b;
clrscr();
printf("Enter length and breadth:");
scanf("%d %d",&l,&b);
area(l,b);
getch();
}
area(int l,int b)
{
int a;
a=l*b;
printf("Rectangle Area =%d",a);
}
61
C-LANGUAGE
program, two way data communication between the calling and called and
functions.
Area of rectangle
#include<stdio.h>
main()
{
int l,b,a;
clrscr();
printf("Enter length and breadth:");
scanf("%d %d",&l,&b);
a=area(l,b);
printf("Rectangle Area =%d",a);
getch();
}
area(int l,int b)
{
int t;
t=l*b;
return(t);
}
Exercises:
1) Accept three numbers and display the biggest number.
a) Using no arguments and no return values.
b) Passing arguments but no return values.
c) Passing arguments and return values.
2) Accept a number and display in reverse order.
a) Passing no arguments and no return values.
b) Passing arguments but no return values.
c) Passing arguments and return values.
62
C-LANGUAGE
63
C-LANGUAGE
RECURSION:-
Recursion is a process by which a function calls itself repeatedly
until specified condition has been satisfied.
Many iterative (loops) programs can be written in this form.
Advantages:
By using recursion process only, function calling information will be
maintained in program.
By using recursion process stack evalution takes place.
With the help of recursion only – infix, postfix, prefix notations are
evaluated.
By using recursion process only trees and graphs are implemented.
Drawbacks:
It is a very slow process due to stack overlapping.
Recursion based programs can create stack overflow.
Recursion based functions can create infinity loop.
64
C-LANGUAGE
printf("Sum of digits=%d",s);
getch();
}
sum(int x)
{
if(x==0)
return(0);
else
return((x%10)+sum(x/10));
}
65
C-LANGUAGE
}
display(int a[],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
Exercises:
1) Accept “n” numbers into an array and display the biggest number.
2) Accept n numbers and display in ascending order.
66
C-LANGUAGE
Exercises:
1) Display sum of two matrix
2) Matrix multiplication
67
C-LANGUAGE
STORAGE CLASSES
Variable in “c” different behaviour from most of the other languages.
In “C” there are different ways to characterize variables by data type and
storage class.
Storage class of C will provide following information to the compiler:
1. Storage area of variable.
2. Scope of a variable that is in which block that variable is visible.
3. Life time of a variable that is how long that variable will be there in
active mode.
4. Default value of a variable if it is not initialized.
output:- 3 2 1
68
C-LANGUAGE
External variables:- External variables are both alive and active though
out the entire program. These are also known as global variable. External
variables are declared outside a function.External variables are stored in
memory.External variables default value is zero(“0”).
Syntax:- extern datatype variable;
extern int a;
output: 0 1 2
Static variables:- The value of static variables persists until the end of
the programm. A static variables may be either internal or external
depending on the place of declaration. The default value of static variables
is zero. Static variables are stored in static memory.
Internal static variables are those, which are declared inside a
function. The scope of internal static variable extend up to the end of the
function in which they are defined. Therefore, internal static variables are
similar to auto variables, except that they remain in existence(alive)
throughout the remainder of the program.
An external static variable is declared outside of all functions and is
available to all the functions in that program. The difference between a
static external variable and simple external variable is that the static
variable is available only with in the file where it is defined while the simple
external variable can be accessed by other files.
69
C-LANGUAGE
main()
{
increment();
increment();
increment();
getch();
}
increment() increment()
{ {
static int a=1; auto int a=1;
printf(“%d\t”,a); printf(“%d\t”,a);
a++; a++;
} }
output: 1 2 3 output: 1 1 1
Register Variables:-
It is a special kind of variables which stores in CPU registers.
The basic advantage of register variable is it is faster than normal
variables.
In implementation, when we are accessing a variable throught the
program n number of times then go for register variable.
Limitations:
Register memory is limited so it is not possible to create n number of
register variables.
On register variables we can’t apply pointers because register
variables doesn’t allow to access address.
70
C-LANGUAGE
POINTERS
Find the address of the variable
#include<stdio.h>
main()
{
int a;
clrscr();
printf("Enter a number \t");
scanf("%d",&a);
printf("\nValue of a =%d",a);
printf("\nAddress of a =%u",&a);
printf("\nValue of a =%d",*(&a));
getch();
}
The “&” is the address operator in “C”. the other pointer operator available
in “C” in *. It is called value at address operator as indirection operator.
Advantages of pointer:
1. Data Access: - C programming language is a procedure oriented
language that is applications are developed by using functions.
From one function to another function, when we are required to access the
data, pointer is required.
2. Memory Management: - By using pointers only, dynamic memory
allocation is possible.
3. Database/Datastrucrtures: - Any kind of data structures required to
develop by using pointers only, if data structures are not available then
database is not possible to create.
4. Performance: - By using pointers, we can increase the execution of
the program.
71
C-LANGUAGE
a=10;
b=20;
p=&a;
q=&b;
printf("Value of a=%d\n",a);
printf("Address of a=%u\n",&a);
printf("Value of a = %u\n",*p);
printf("Address of p=%u\n",p);
printf("Value of b=%d\n",b);
printf("\Address of b= %u\n",&b);
printf("Value of b = %u\n",*q);
printf("Address of q = %u",q);
getch();
}
Pointer rules:
Rule1:
Address+number=address(next specified address)
Address-number=address( Previous address)
Address++=next address
Address- -=previous address
++Address=next address
--Address=previous address
Ex:
int i1,i2;
int *p1,*p2;
p1=&i1;
p2=&i2;
p1+p2; Error
p1+1; Next address
++p1; Next address
p1++; next address
p2-1; Previous address
p2--; Previous address
--p2; Previous address
Rule2:
Address-address=number of elements/size difference
int *p1=(int*)100;
int *p2=(int*)200;
p2-p1=50
Rule3:
Address+address= illegal p1+p2
Address+address= illegal p1*p2
Address+address= illegal p1/p2
Address+address= illegal p1%p2
72
C-LANGUAGE
Rule 4:
We can use relational operators and and conditional operators between
two pointers. (<, >, <=, >=, ==, !=, ? :)
Address>address p1>p2 True/false
Pointer to pointer:
It is a procedure of holding the pointer address into another pointer
variable.
In a C programming language, pointer to pointer relations can be
applied upto 12 stages.
When we are increment pointer pointer relations then performance
will be decreased.
Ex:
Int i;
int *ptr;
int **pptr;
int ***ppptr;
ptr=&i;
pptr=&ptr;
ppptr=&pptr;
void pointer:
Generic pointer of ‘C’ and ‘C++’ is called void pointer.
Generic pointer means it can access and manipulate any kind of
data properly.
Size of void pointer is 2 bytes.
73
C-LANGUAGE
Ex:
#include<stdio.h>
main()
{
int i;
float f;
char ch;
int *iptr;
float *fptr;
char *cptr;
clrscr();
iptr=&i;
i=10;
printf("%d %d\n",i,*iptr);
fptr=&f;
f=12.6;
printf("%f %f\n",i,*fptr);
cptr=&ch;
ch='A';
printf("%c %c\n",ch,*cptr);
getch();
}
In the above program, in place of constructing 3 types of pointers, we
can create a single pointer variable which can access and manipulate any
kind of variable properly that is void pointer required to use.
Ex:
#include<stdio.h>
main()
{
int i;
float f;
char ch;
void *ptr;
clrscr();
ptr=&i;
i=10;
printf("%d %d\n",i,*(int*)ptr);
ptr=&f;
74
C-LANGUAGE
f=12.6;
printf("%f %f\n",i,*(float*)fptr);
ptr=&ch;
ch='A';
printf("%c %c\n",ch,*(char*)cptr);
getch();
}
Exercises:
1) Accept three numbers and display the biggest number using
pointers.
2) Accept a number and display in reverse order.
75
C-LANGUAGE
2) Call by address.
Call By Value:-
When we are calling a function by passing a value type data then it
is called call by value.
In call by value, both actual arguments and formal arguments are
value type variables only.
In call by value, if any modifications are occur on formal arguments
then those modifications doesn’t pass to actual arguments.
Ex: printf(), sqrt()…
Call By Address:-
When we are passing address type data to a function then it is
called call by address.
In call by address, actual arguments are address type and formal
arguments are pointer type.
In call by address, if any modifications occurred on formal
arguments then those changes will pass to actual arguments.
Ex: scanf(), strcpy()….
Accept two numbers and swap them (using call by value method).
#include<stdio.h>
main()
{
int a,b;
clrscr();
printf("Enter TWO numbers\n");
scanf("%d%d",&a,&b);
printf("Before Swapping\n");
printf("a=%d \t b=%d",a,b);
swap(a,b);
getch();
}
swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf("\nAfter Swapping\n");
printf("\na=%d \t b=%d",x,y);
}
76
C-LANGUAGE
int a,b;
clrscr();
printf("Enter TWO numbers\n");
scanf("%d%d",&a,&b);
printf("Before Swapping\n");
printf("a=%d \t b=%d",a,b);
swap(&a,&b);
printf("\nAfter Swapping\n");
printf("\na=%d \t b=%d",*x,*y);
getch();
}
Exercises:
1) Accept two numbers and display the sum.
2) Accept three numbers and display the biggest number.
3) Accept a number and display in reverse order.
77
C-LANGUAGE
78
C-LANGUAGE
{
printf("a[%d] %u %d\n",i,p,*p);
sum=sum+*p;
p++;
}
printf("Sum of elements = %d",sum);
getch();
}
79
C-LANGUAGE
Exercises:
1) Accept n elements into an array and display in sorting order.
80
C-LANGUAGE
int i,j;
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",*(p+i)+j);
}
}
Exercises:
1) Accept mXn matrix and display the transpose of the given matrix.
81
C-LANGUAGE
malloc(): By using this pre defined function, we can create the memory
dynamically at initial stage.
malloc function require one argument of type size_type that is data type
size.
malloc() creates memory in bytes format and initial value is garbage.
Syntax:
void* malloc(size_type);
when we are working with DMA related functions, we are required to
perform type casting because function returns void *.
Ex:
int *p;
p=(int*)malloc(sizeof(int));
float *p;
p=(float*)malloc(sizeof(float));
int *p;
p=(int*)malloc(sizeof(int)*10);
82
C-LANGUAGE
When we are working with DMA related programs, at the end of the
program recommended to deallocate memory by using free() function.
free() function requires one argument of type (void*) and retrurns
void type.
calloc(): - By using this pre defined function, we can create the memory
dynamically at initial stage.
calloc() requires two argument of type (count,type_size)
count will provide no of elements, size_type is data type size.
When we are working with calloc() function, it creates the memory in
block format and initial value is zero.
Syntax:
pointervariable=(datatype*)calloc(size,sizeof(datatype));
Ex: int *p;
We want to store 5 elements for the above variable
p=(int*)calloc(5,sizeof(int));
83
C-LANGUAGE
printf("Sum = %d",*sum);
free(p);
free(q);
free(sum);
getch();
}
Exercises:
1) Accept three numbers and display the biggest number using
pointers.
2) Accept a number and display in reverse order.
84
C-LANGUAGE
getch();
}
Exercises:
1) Accept n elements into an array and display the search no is found
or not.
2) Accept n elements into an array and display in sorting order.
for(j=0;j<n;j++)
scanf("%d",(p+i)+j);
}
printf("The Matrix is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",*(p+i)+j);
}
getch();
}
85
C-LANGUAGE
{
for(j=0;j<n;j++)
scanf("%d",(p+i)+j);
}
printf("The Matrix is:\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",*(p+i)+j);
}
getch();
}
Exercises:
1) Accept mXn matrix and display the transpose of the given matrix.
86
C-LANGUAGE
STRUCTURES
A structure is a collection of different types of data elements in a single
entity.
A structure is a combination of primitive and derived data type variables.
By using structures we can create user defined data types.
Size of the structure is sum of all member variable sizes.
Syntax:-
struct <structurename>
{
datatype variable;
datatype variable;
datatype variable;
datatype variable;
};
ex:-
struct student
{
int rno;
char name[20];
int m1,m2,m2;
int tot;
float avg;
};
Ex2:
struct student
{
int rno;
char sname[20];
char fname[20];
int marks;
float avg
};
87
C-LANGUAGE
88
C-LANGUAGE
Arrays Of Structures
We use structures to describe the format of a number of related
variables. For example, in analyzing the marks obtained by a class of
students, we may use a template to describe student name and marks
obtained in various subjects and then declare all the students as structure
variables. In such cases, we may declare an array of structures, each
element of the array representing a structure variable. For example,
struct class student[100];
defines an array called student, that consists of 100 elements. Each
element is defined to be of the type struct class. Consider the following
declaration:
struct marks
{
int subject1;
int subject2;
int subject3;
};
main()
{
static struct marks
student[3]={{45,68,81},{58,65,28},{12,92,75
}};
This declares the student as an array of three elements student[0],
student[1] and student[2] and initializes their members as follows:
student[0],subject1=85;
student[0],subject2=46;
………………………..
………………………..
student[2],subject3=72;
Accept five student details and display total, average, result and
class.
#include<stdio.h>
89
C-LANGUAGE
struct student
{
int rno,m1,m2,m3,tot;
char name[30],res,class;
float avg;
};
struct student s[5];
main()
{
int i;
clrscr();
for(i=0;i<5;i++)
{
printf("Enter rollno:");
scanf("%d",&s[i].rno);
printf("Enter name:");
scanf("%s",&s[i].name);
printf("Enter three subject marks:");
scanf("%d %d %d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3.0;
if(s[i].m1>=35 && s[i].m2>=35 && s[i].m3>=35)
{
s[i].res='p';
if(s[i].avg>=60)
s[i].class='1';
else
if(s[i].avg>=50)
s[i].class='2';
else
s[i].class='3';
}
}
for(i=0;i<5;i++)
{
clrscr();
printf("\t\t----------------------------------------\n");
printf("\t\t STUDENT MARKS REPORT \n");
printf("\t\t----------------------------------------\n");
printf("\t\tROLL NO :%d\n",s[i].rno);
printf("\t\tNAME :%s\n",s[i].name);
printf("\t\tMATHS :%d\n",s[i].m1);
printf("\t\tPHY :%d\n",s[i].m2);
printf("\t\tCHE :%d\n",s[i].m3);
printf("\t\tTOTAL :%d\n",s[i].tot);
90
C-LANGUAGE
printf("\t\tAVERAGE :%f\n",s[i].avg);
if(s[i].res=='p')
printf("\t\tRESULT :PASS\n");
else
printf("\t\tRESULT :FAIL\n");
if(s[i].class=='1')
printf("\t\tCLASS :FIRST\n");
else
if(s[i].class=='2')
printf("\t\tCLASS :SECOND\n");
else
if(s[i].class=='3')
printf("\t\tCLASS :THIRD\n");
else
printf("\t\tCLASS :NILL\n");
printf("\n\nPress any key to continue............\n");
getch();
}
}
Exersises:
1)Calculate the electricity bill for n members
struct salary
{
char name[30];
char department[12];
int basic_pay;
int dearness_allowance;
int house_rent_allowance;
int city_allowance;
}employee;
This structure defines name, department, basic pay and three kinds of
allowances.we can group all the items related to allowance together and
declare them under a substructure as shown below:
struct salary
{
char name[20];
char department[10];
struct
{
91
C-LANGUAGE
int dearness;
int house_rent;
int city;
}
allowance;
}
employee;
The salary structure contains a member named allowance which itself is a
structure with three members. The members contained in the inner
structure namely dearness, house_rent, and city can be referred to as
employee.allowance.dearness
employee.allowance.house_rent
employee.allowance.city
Example
#include<stdio.h>
struct student
{
int rno;
char name[20];
};
struct marks
{
int m1,m2,m3;
int tot;
struct student s;
};
struct marks m;
main()
{
clrscr();
printf("Enter roll no:");
scanf("%d",&m.s.rno);
printf("Enter name:");
scanf("%s",&m.s.name);
printf("Enter three subject marks:");
scanf("%d %d %d",&m.m1,m.m2,&m.m3);
m.tot=m.m1+m.m2+m.m3;
printf("Total=%d",m.tot);
getch();
}
92
C-LANGUAGE
93
C-LANGUAGE
printf(“-------------------------------------------------\n”);
printf(“Meter no :%d\n”,e->mno);
printf(“Name :%s\n”,e->name);
printf(“Previous Reading :%d\n”,e->lmr);
printf(“Present Reading :%d\n”,e->pmr);
printf(“Total Units :%d\n”,e->units);
printf(“Charge :%f\n”,e->charge);
getch();
}
94
C-LANGUAGE
};
struct sum s;
main()
{
clrscr();
printf("Enter two numbers:");
scanf("%d %d",&s.a,&s.b);
s.t=add(s.a,s.b);
printf("Sum=%d",s.t);
getch();
}
add(int a,int b)
{
int r;
r=a+b;
return(r);
}
95
C-LANGUAGE
Unions:-
A Union is a collection of different types of data elements in a single
entity.
Unions are similar to structures the major difference between storage.
In structures each member has its own location where as all members of a
union use the same location.
In implementation, for manipulation of the data, if we are using only one
member then it is recommended to go for Union.
When we are working with unions, all member variables will share same
memory location.
By using union, when we are manipulating multiple members then actual
data is lost.
Syntax:
Union <union name>
{
datatype variable1;
datatype variable2;
};
Ex:- union sss
{
int a;
float b;
}s;
The compiler allocates a space of storage location. i.e largest variable in
the union.
Example
#include<stdio.h>
union sample
{
int a;
float b;
};
union sample s;
main()
{
clrscr();
s.a=10;
s.b=123.45;
printf("\na=%d",s.a);
printf("\nb=%f",s.b);
getch();
}
96
C-LANGUAGE
FILE HANDLING
A file is a name of physical memory location in secondary memory area.
File contains sequence of bytes of data in secondary storage area in the
form of un structured manner.
In implementation, when we required to interact with secondary storage
area, then recommended to go for file operations.
By using files, primary memory related data can be send to secondary
storage area and secondary storage area information can be loaded to
primary memory.
In C programming language, I/O operations are classified into two types:
1. Standard I/O operations.
2. Secondary I/O operations.
When we interacting with primary I/O devices, then it is called standard
I/O operations.
When we interacting with secondary I/O devices, then it is called
secondary I/O operations.
Standard I/O related and Secondary I/O related predefined functions are
available in stdio.h.
File functions:
fopen fclose fprintf putc fputs
getc fscanf fgets fgetchar fread
fwrite flushall ftell feof fseek
remove rename rewind fflush
constants:
EOF NULL SEEK_CUR SEEK_END SEEK_SET
Data type:
FILE
Global variables:
stdin stdout stderr stdprn
97
C-LANGUAGE
fclose():
By using this predefined function, we can close the file after saving
data.
fclose() requires one argument of type FILE and returns an int value.
File modes: -
Always file modes will indicate that for what purpose file need to be
open or create.
File modes are classified in to 3 types:
1. write
2. read
3. append
Depending on operations, file modes are classified into six types:
1.w(write): - Create file for writing, if file already exists, then it will
override. (old file is deleted and new file is created)
If file doesn’t exist then new file will be created.
In “w” mode, file exist or not, always new file is constructed.
2.r(read): - Open an existing file for reading, if the file does not exist then
fopen() returns null.
3.a(append): - Open an existing file for appending (write the data at end of
file) or create a new file for writing if it does not exist.
4.w+(write and read): - Create a file for update that is write and read, if
file already exists then it will override.
In w+ mode, if file is available or not, always new file is constructed.
5.r+(read and write): - Open an existing file for update that is read and
write.
98
C-LANGUAGE
6.a+(w+ and r+): - Open an existing file for update or create a new file for
update.
By using a+ mode, we can perform random operations.
99
C-LANGUAGE
fprintf:- This is used to write a set of data values into the file.
Syntax:- fprintf(pointer variable, “control string”, variable);
Ex:-fprintf(fp,”SUM=%d”,sum);
fscanf:- It is used to read set of values to the file.
Syntax:- fscanf(pointer variable,”control string”, variable);
Ex:-fscanf(fp,”%d”,&a,&b);
100
C-LANGUAGE
fprintf(p,"Total : %d\n",tot);
fprintf(p,"Average : %.2f\n",avg);
if(res=='p')
fprintf(p,"Result : Pass\n");
else
fprintf(p,"Result : Fail\n");
if(class=='1')
fprintf(p,"Class : First\n");
else
if(class=='2')
fprintf(p,"Class : Second\n");
else
if(class=='3')
fprintf(p,"Class : Third\n");
else
fprintf(p,"Class : Nill\n");
fprintf(p,"---------------------------------\n");
}
101
C-LANGUAGE
102
C-LANGUAGE
103
C-LANGUAGE
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
104