CS3251-Programming-in-C-Lecture-Notes-2
CS3251-Programming-in-C-Lecture-Notes-2
EnggTree.com
The programming language „C‟ was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories. Although C was initially developed for writing system software, today it has
become such a popular language that a variety of software programs are written using this
language. The greatest advantage of using C for programming is that it can be easily used on
different types of computers. Many other programming languages such as C++ and Java are also
based on C which means that you will be able to learn them easily in the future. Today, C is
widely used with the UNIX operating system.
www.EnggTree.com
Programming Languages
The purpose of using computers is to solve problems, which are difficult to solve manually. So
the computer user must concentrate on the development of good algorithms for solving
problems. After preparing the algorithms, the programmer or user has to concentrate the
programming language which is understandable by the computer.
Computer programming languages are developed with the primary objectives of facilitating a
large number of people to use computer without the need to know the details of internal structure
of the computer.
Structure of C program
A C program contains one or more functions, where a function is defined as a group of
statements that perform a well-defined task. Figure 1.1 shows the structure of a C program. The
statements in a function are written in a logical sequence to perform a specific task. The main()
Page 1
function is the most important function and is a part of every C program. Rather, the execution of
a C program begins with this function.
From the structure given in Fig. 1.1, we can conclude that a C program can have any number of
functions depending on the tasks that have to be performed, and each function can have any
number of statements arranged according to specific meaningful sequence. Note that
programmers can choose any name for functions. It is not mandatory to write Function1,
Function2, etc., with an exception that every program must contain one function that has its
name as main().
www.EnggTree.com
Page 2
www.EnggTree.com
Storage classes
Storage classes of a variable determine:
1. Storage area of the variable
2. Initial value of variable if not initialized
3. Lifetime of the variable
Page 3
{
int b=20;
printf(“b=%d”,b);
}
printf(“Here b is not visible\n”);
printf(“a=%d”,a);
}
Page 4
Output
a=10
b=20
Here b is not visible
a=10
Page 5
Output:
11 12 13 14 15
4. The extern storage class
Variables that are available to all functions are called external or global variables.
External variables are stored in main memory.
External variables have static (global) lifetime.
External variables have external linkage.
External variables are implicitly initialized to 0.
Example:
extern int v=10;
void call1()
Page 6
void main()
{
call1();
printf(“In main v=%d”,v);
}
void call1()
{
printf(“In call1() v=%d”,v);
}
Output:
In main v=10
In call1( ) v=10
Since v is a external variable it is visible and accessed in all functions.
Eg:
typedef char* cp;
cp c; // is same as char * c;
cp and (char *) can be used interchangeably.
Page 7
Constants
A constant is an entity whose value can‟t be changed during the execution of a program.
Constants are classified as:
1. Literal constants
2. Qualified constants
3. Symbolic constants
Literal constants
Literal constant or just literal denotes a fixed value, which may be an integer, floating point
number, character or a string.
www.EnggTree.com
Literal constants are of the following types.
1. Integer Literal constant
2. Floating point Literal constant
3. Character Literal constant
4. String Literal constant
Page 8
The rules for writing Floating point Literal constants in an exponential form:
A Floating point Literal constants in an exponential form has two parts: the mantissa
part and the exponent part. Both are separated by e or E.
The mantissa part can be either positive or negative. The default sign is positive.
The mantissa part should have at least one digit.
www.EnggTree.com
The mantissa part can have a decimal point.
The exponent part should have at least one digit
The exponent part cannot have a decimal point.
No special characters and blank spaces are allowed.
Page 9
Non-Printable character literal constants are represented with the help of escape sequences. An
escape sequence consists of a backward slash (i.e. \) followed by a character and both enclosed
within single quotes.
Symbolic constants
Symbolic constants are created with the help of the define preprocessor directive. For ex #define
PI= 3.14 defines PI as a symbolic constant with the value 3.14. Each symbolic constant is
replaced by its actual value during the pre-processing stage.
Keywords
Keyword is a reserved word that has a particular meaning in the programming language. The
meaning of a keyword is predefined. It can‟t be used as an identifier.
Page 10
www.EnggTree.com
An operator is a symbol that is used to perform specific mathematical or logical manipulations.
For e.g, a=2+3 Here = & + are the operators
Precedence of operators
The precedence rule is used to determine the order of application of operators in
evaluating sub expressions.
Each operator in C has a precedence associated with it.
The operator with the highest precedence is operated first.
Associativity of operators
The associativity rule is applied when two or more operators are having same precedence in the
sub expression.
An operator can be left-to-right associative or right-to-left associative.
Page 11
www.EnggTree.com
sub expression.
Expressions
An expression is a sequence of operators and operands that specifies computation of a value.
For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +
Page 12
Classification of Operators
The operators in C are classified on the basis of
1) The number of operands on which an operator operates
2) The role of an operator
www.EnggTree.com
Operator Meaning
- Minus
++ Increment
-- Decrement
& Address- of operator
sizeof sizeof operator
2. Binary Operator: A binary operator operates on two operands. Some of the binary
operators are,
Operator Meaning
+ Addition
- Subtraction
* Multiplication
Page 13
/ Division
% Modular
Division
&& Logical AND
3. Ternary Operator
A ternary operator operates on 3 operands. Conditional operator (i.e. ?:) is the ternary operator.
www.EnggTree.com
1. Arithmetic Operators
They are used to perform arithmetic operations like addition, subtraction, multiplication, division
etc.
A=10 & B=20
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give
200
/ The division operator is used to find the quotient. B / A will give 2
% Modulus operator is used to find the remainder B%A will give 0
+,- Unary plus & minus is used to indicate the algebraic +A, -A
sign of a value.
Increment operator
Page 14
Decrement operator
The operator – subtracts one from its operand.
--a or a-- is equivalent to a=a+1
www.EnggTree.com
Prefix decrement (--a) operator will decrement the variable BEFORE the
expression is evaluated.
Postfix decrement operator (a--) will decrement AFTER the expression
evaluation.
E.g.
1. c=--a. Assume a=2 so c=1 because the value of a is decremented and then
it is assigned to c.
2. d=b-- Assume b=2 so d=2 because the value of b is assigned to d before it
is decremented.
2. Relational Operators
Relational operators are used to compare two operands. There are 6 relational
operators in C, they are
Page 15
If the relation is true, it returns value 1 and if the relation is false, it returns value
0.
An expression that involves a relational operator is called as a condition. For e.g
a<b is a condition.
3. Logical Operators
Logical operators are used to logically relate the sub-expressions. There are 3
logical operators in C, they are
www.EnggTree.com
If the relation is true, it returns value 1 and if the relation is false, it returns value
0.
Operator Meaning of Example
Operator Description
&& Logial AND If c=5 and d=2 then,((c==5) && (d>5)) It returns true when
returns false. both conditions are
true
|| Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) It returns true when
returns true. at-least one of the
condition is true
! Logical NOT If c=5 then, !(c==5) returns false. It reverses the state
of the operand
Page 16
4. Bitwise Operators
C language provides 6 operators for bit manipulation. Bitwise operator operates on the
individual bits of the operands. They are used for bit manipulation.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~
www.EnggTree.com
Bitwise complement
<< Shift left
>> Shift right
Truth tables
Page 17
00001100
& 00011001
5. Assignment Operators
To assign a value to the variable assignment operator is used.
Operators Example Explanation
Simple assignment operator = sum=10 10 is assigned to variable sum
+= sum+=10 This is same as sum=sum+10
-= sum-=10 sum = sum-10
Compound assignment operators *= sum*=10 sum = sum*10
Or /+ sum/=10 sum = sum/10
Shorthand assignment operators %= sum%=10 sum = sum%10
&= sum&=10 sum = sum&10
^= sum^=10 sum = sum^10
Page 18
E.g.
var=5 //5 is assigned to var
a=c; //value of c is assigned to a
6. Miscellaneous Operators
Other operators available in C are
a. Function Call Operator(i.e. ( ) )
b. Array subscript Operator(i.e [ ])
c. Member Select Operator
i. Direct member access operator (i.e. . dot operator)
ii. Indirect member access operator (i.e. -> arrow operator)
d. Conditional operator (?:)
e. Comma operator (,)
f. sizeof operator
g. Address-of operator (&)
a) Comma operator
www.EnggTree.com
It is used to join multiple expressions together.
E.g.
int i , j;
i=(j=10,j+20);
In the above declaration, right hand side consists of two expressions separated by
comma. The first expression is j=10 and second is j+20. These expressions are evaluated from
left to right. ie first the value 10 is assigned to j and then expression j+20 is evaluated so the final
value of i will be 30.
b) sizeof Operator
The sizeof operator returns the size of its operand in bytes.
Example : size of (char) will give us 1.
sizeof(a), where a is integer, will return 2.
c) Conditional Operator
Page 19
Syntax :
(Condition? true_value: false_value);
For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
d) Address-of Operator
It is used to find the address of a data object.
Syntax
&operand
E.g.
&a will give address of a.
www.EnggTree.com
Input/Output statements
The I/O functions are classified into two types:
Formatted Functions
Unformatted functions
Page 20
printf() getch()
getche()
getchar()
scanf()
gets()
putch()
putchar()
puts()
Unformatted Functions:
They are used when I/P & O/P is not required in a specific format.
C has 3 types I/O functions.
www.EnggTree.com
a) Character I/O
b) String I/O
c) File I/O
a) Character I/O:
1. getchar() This function reads a single character data from the standard input.
(E.g. Keyboard)
Syntax :
variable_name=getchar();
eg:
char c;
c=getchar();
Page 21
eg
char c=„C‟;
putchar(c);
Example Program
#include <stdio.h>
main()
{
int i;
char ch;
ch = getchar();
putchar(ch);
}
Output:
A
A
www.EnggTree.com
3. getch() and getche() : getch() accepts only a single character from keyboard. The character
entered through getch() is not displayed in the screen (monitor).
Syntax
variable_name = getch();
Like getch(), getche() also accepts only single character, but getche() displays the entered
character in the screen.
Syntax
variable_name = getche();
4 putch(): putch displays any alphanumeric characters to the standard output device. It displays
only one character at a time.
Syntax
putch(variable_name);
b) String I/O
Page 22
1. gets() – This function is used for accepting any string through stdin (keyboard) until enter key
is pressed.
Syntax
gets(variable_name);
puts(variable_name);
Example Program
void main()
{
char ch[30];
clrscr();
printf(“Enter the String : “);
gets(ch);
puts(“\n Entered String : %s”,ch);
puts(ch);
}
Output:
Enter the String : WELCOME
Page 23
www.EnggTree.com
and the optional modifiers width, flag, precision, size.
Conversion Codes
Data type Conversion Symbol
char %c
int %d
float %f
Unsigned octal %o
Pointer %p
Width Modifier: It specifies the total number of characters used to display the value.
Precision: It specifies the number of characters used after the decimal point.
E.g: printf(“ Number=%7.2\n”,5.4321);
Width=7
Precesion=2
Output: Number = 5.43(3 spaces added in front of 5)
Flag: It is used to specify one or more print modifications.
Page 24
Flag Meaning
- Left justify the display
+ Display +Ve or –Ve sign of value
E.g:
Space Display space if there is no sign
0 Pad with leading 0s
printf(“Number=%07.2\n”,5.4321)
Output: Number=0005.43
www.EnggTree.com
%ld means long int variable
%hd means short int variable
3. Control Codes
They are also known as Escape Sequences.
E.g:
Page 25
Page 26
Flow of control: The order in which the program statements are executed is known as flow of
control. By default, statements in a c program are executed in a sequential order
Branching statements
Branching statements are used to transfer program control from one point to another.
2 types
a) Conditional Branching:- Program control is transferred from one point to another based
on the result of some condition
Eg) if, if-else, switch
b) Unconditional Branching:- Pprogram control is transferred from one point to another
without checking any condition
Eg) goto, break, continue, return
www.EnggTree.com
The if-else statement
The switch case statement
(i) The if statement
C uses the keyword if to execute a statement or set of statements when the logical condition is
true.
Syntax:
Test
if (test expression)
Statement; expres
F
Statement
T
Page 27
Example:
#include <stdio.h>
void main()
{
int n;
clrscr();
printf(“enter the number:”);
scanf(“%d”,&n);
if(n>0)
printf(“the number is positive”);
getch();
}
Output: www.EnggTree.com
enter the number:50
the number is positive
if (test expression)
Statement T; Stateme
Stateme
else T F
Statement F;
Page 28
#include <stdio.h>
void main(){
int n,r;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&n);
r=n%2;
if(r==0)
printf(“The number is even”);
else
printf(“The number is odd”);
getch();
}
Output:
Enter a number:15
The number is odd
www.EnggTree.com
Example:2 To check whether the two given numbers are equal
void main()
{
int a,b;
clrscr();
printf(“Enter a and b:” );
scanf(“%d%d”,&a,&b);
if(a==b)
printf(“a and b are equal”);
else
printf(“a and b are not equal”);
getch();
}
Output:
Page 29
Enter a and b: 2 4
a and b are not equal
(iii) Nested if statement
If the body the if statement contains another if statement, then it is known as nested if
statement
Syntax:
www.EnggTree.com
if (test expression3)
{
….
if (test expression n)
}}}
Page 30
{
statement 3;
if (condition)
statementnest;
statement 4;
}
Example:
Program for finding greatest of 3 numbers
#include<stdio.h>
void main()
{
int a,b,c;
printf(“Enter three numbers\n”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
www.EnggTree.com
if(a>c)
{
printf(“a is greatest”);
}
}
else
{ if(b>c)
{
printf(“b is greatest”);
}
else
{
printf(“C is greatest”);
}
}
Page 31
}
Output
Enter three numbers 2 4 6
C is greatest
v) Switch statement
It is a multi way branch statement.
It provides an easy & organized way to select among multiple operations depending upon
some condition.
Execution
1. Switch expression is evaluated.
2. The result is compared with all the cases.
3. If one of the cases is matched, then all the statements after that matched case gets executed.
4. If no match occurs, then all the statements after the default statement get executed.
Switch ,case, break and default are keywords
www.EnggTree.com
Break statement is used to exit from the current case structure
Flowchart
switch(expression)
case: break
constant 0 statement
End of switch
Syntax
switch(expression)
{
case value 1:
program statement;
program statement;
……
break;
case value 2:
program statement;
Program statement;
……
break;
…
case value n:
program statement;
program statement;
……
Example1 break;
default:
void main() program statement;
program statement;
{
}
char ch;
www.EnggTree.com
printf(“Enter a character\n”);
scanf(“%c”,&ch);
switch(ch)
{
case „A‟:
printf(“you entered an A\n”);
break;
case „B‟:
printf(“you entered a B\n”);
break;
default:
printf(“Illegal entry”);
break;
}
getch();
Page 33
}
Output
Enter a character
A
You entered an A
Example2
void main()
{
int n;
printf(“Enter a number\n”);
scanf(“%d”,&n);
switch(n%2)
{
case 0:printf(“EVEN\n”);
www.EnggTree.com
break;
case 1:printf(“ODD\n”);
break;
}
getch();
}
Output:
Enter a number
5
ODD
Page 34
Syntax:
goto label;
Example:1
#include<stdio.h>
void main()
{
Page 35
int c=1;
while(c<=5)
{
if (c==3)
break;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2
Example :2
#include<stdio.h>
void main()
{
www.EnggTree.com
int i;
for(i=0;i<=10;i++)
{
if (i==5)
break;
printf(“ %d”,i);
}
}
Output :1 2 3 4
iii) continue statement
A continue statement can appear only inside a loop.
A continue statement terminates the current iteration of the nearest enclosing
loop.
Syntax:
continue;
Page 36
Example :1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
continue;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2 4 5
Example :2
www.EnggTree.com
#include<stdio.h>
main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
continue;
printf(“ %d”,i);
}
}
Output :1 2 3 4 6 7 8 9 10
iv) return statement:
A return statement terminates the execution of a function and returns the control to the
calling function.
Page 37
Syntax:
return;
(or)
return expression;
Looping statements
Iteration is a process of repeating the same set of statements again and again until the condition
holds true.
Iteration or Looping statements in C are:
1. for
2. while
3. do while
Loops are classified as
Counter controlled loops
www.EnggTree.com
Sentinel controlled loops
Counter controlled loops
The number of iterations is known in advance. They use a control variable called
loop counter.
Also called as definite repetitions loop.
E.g: for
Sentinel controlled loops
The number of iterations is not known in advance. The execution or termination of the
loop depends upon a special value called sentinel value.
Also called as indefinite repetitions loop.
E.g: while
1. for loop
It is the most popular looping statement.
Syntax:
for(initialization;condition2;incrementing/updating)
csenot
escorner.blogspot.com
{ Page 38
Statements;
}
www.EnggTree.com
www.EnggTree.com
3. After the execution of loop, the manipulation expression is evaluated.
4. Steps 2 & 3 are repeated until step 2 condition becomes false.
Page 39
2. while statement
They are also known as Entry controlled loops because here the condition is checked
before the execution of loop body.
Syntax:
while (expression)
{
statements;
}
Page 40
Page 41
i=i+1;
}
printf(“Sum=%d”, sum);
getch();
}
Output:
Enter the value for n
4
Sum=10
3. do while statement
They are also known as Exit controlled loops because here the condition is checked after
the execution of loop body.
Syntax:
do
{
statements;
www.EnggTree.com
}
while(expression);
The body of do-while is executed once, even when the condition is initially false.
Page 42
{
int i=1;
clrscr();
do
{
printf (“%d”,i);
i=i+1;
} while (num<=10);
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10
Page 43
Sum=10
Nested loops
If the body of a loop contains another iteration statement, then we say that the loops are
nested.
Loops within a loop are known as nested loop.
Syntax
while(condition)
{
www.EnggTree.com
while(condition)
{
Statements;
}
Statements;
}
Page 44
Introduction to Arrays
Definition: www.EnggTree.com
An array is a data structure that is used to store data of the same type. The position
of an element is specified with an integer value known as index or subscript.
E.g.
1 3 5 2
a(integer array)
Characteristics:
ii) The individual elements of an array are referred based on their position.
2. Multi-dimensional array
Declarations of Arrays
type name[size]
Here the type can be either int, float, double, char or any oher valid data type. The
number within the brackets indicates the size of the array, i.e., the maximum
number of elements that can be stored in the array.
The values are written with curly brackets and every value is separated by a
comma. It is a compiler error to specify more number of values than the number of
elements in the array.
www.EnggTree.com
It is also known as one-dimensional arrays or linear array or vectors
It consists of fixed number of elements of same type
Elements can be accessed by using a single subscript. eg) a[2]=9;
Eg)
1 3 5 2
a
[0] [1] [2] [3] subscripts or indices
char b[5]={‘A’.’r’,’r’};
Example Programs
C Program to Find Mean, Median, and Mode of Given Numbers.
#define SIZE 100
#include"stdio.h"
float mean_function(float[],int);
float median_function(float[],int);
float mode_function(float[],int);
int main()
{
int i,n,choice;
float array[SIZE],mean,median,mode;
www.EnggTree.com
printf("Enter No of Elements\n");
scanf("%d",&n);
printf("Enter Elements\n");
for(i=0;i
scanf("%f",&array[i]);
do
{
printf("\n\tEnter Choice\n\t1.Mean\n\t2.Median\n\t3.Mode\n4.Exit");
scanf("%d",&choice);
switch(choice)
{
case 1: mean=mean_function(array,n);
printf("\n\tMean = %f\n",mean);
break;
Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
Mean = 3.000000
Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
2
Median = 3.000000
Enter Choice
1.Mean
www.EnggTree.com
2.Median
3.Mode
4.Exit
3
Mode = 3.000000
Enter Choice
1.Mean
2.Median
3.Mode
4.Exit
4
Declaration
datatype arrayname [row size][column size]
www.EnggTree.com
e.g) int a [2][3]; //a is an integer array of 2 rows and 3 columns
number of elements=2*3=6
Initialization
1. By using an initialization list, 2D array can be initialized.
e.g. int a[2][3] = {1,4,6,2}
1 4 6
2 0 0
a
www.EnggTree.com
printf("\n 2. Addition of Matrix:-\n");
printf("\n 3. Multiplication of Matrix:-\n");
printf("\n 4. Exit\n");
printf("\n Enter your choice:-");
scanf("%d",&a);
switch(a)
{
case 1 :
printf("\n Enter the number of row and coloum:-");
scanf("%d%d",&r1,&c1);
printf("\n Enter the element :-");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
www.EnggTree.com
break;
case 2:
printf("\n how many row and coloum in Matrix one:-");
scanf("%d%d",&r1,&c1);
printf("\n How amny row and coloum in Matrix two:-");
scanf("%d%d",&r2,&c2);
if((r1==r2)&&(c1==c2))
{
printf("\n Addition is possible:-");
printf("\n Input Matrix one:-");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&m1[i][j]);
www.EnggTree.com
printf("\n The sum is:-\n");
for(i=0;i<c1;i++)
{
for(j=0;j<r1;j++)
printf("%5d",m3[i][j]);
printf("\n");
}
}
else
printf("\n Addition is not possible:-");
break;
case 3:
www.EnggTree.com
printf("\n Input value of Matrix two:-");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
scanf("%d",&m2[i][j]);
}
for(i=0;i<r1;i++)
for(j=0;j<c2;j++)
{
m3[i][j]=0;
for(k=0;k<c1;k++)
m3[i][j]=m3[i][j]+m1[i][k]*m2[k][j];
}
/*Displaying final matrix*/
break;
case 4:
www.EnggTree.com
exit(0);
break;
}
getch();
}
}
String Operations
Definition:
The group of characters, digits, & symbols enclosed within double quotes is
called as Strings. Every string is terminated with the NULL (‘\0’) character.
E.g. “INDIA” is a string. Each character of string occupies 1 byte of
memory. The last character is always ‘\0’.
Declaration:
char stringname[size];
www.EnggTree.com
String Operations or String Functions
These functions are defined in string.h header file.
1. strlen() function
It is used to find the length of a string. The terminating character (‘\0’) is not
counted.
Syntax
temp_variable = strlen(string_name);
E.g.
s= “hai”;
strlen(s)-> returns the length of string s i.e. 3.
2. strcpy() function
It copies the source string to the destination string
Syntax
strcpy(destination,source);
E.g.
s1=“hai”;
s2= “welcome”;
strcpy(s1,s2); -> s2 is copied to s1. i.e. s1=welcome.
3. strcat() function
It concatenates a second string to the end of the first string.
Syntax
strcat(firststring, secondstring);
E.g.
s1=“hai ”;
s2= “welcome”;
www.EnggTree.com
strcat(s1,s2); -> s2 is joined with s1. Now s1 is hai welcome.
E.g. Program:
#include <stdio.h>
#include <string.h>
void main ()
{
char str1[20] = "Hello";
char str2[20] = "World";
char str3[20];
int len ;
strcpy(str3, str1);
printf("Copied String= %s\n", str3 );
4. strcmp() function
It is used to compare 2 strings.
Syntax
www.EnggTree.com
temp_varaible=strcmp(string1,string2)
If the first string is greater than the second string a positive number is
returned.
If the first string is less than the second string a negative number is
returned.
If the first and the second string are equal 0 is returned.
5. strlwr() function
It converts all the uppercase characters in that string to lowercase characters.
Syntax
strlwr(string_name);
6. strupr() function
It converts all the lowercase characters in that string to uppercase characters.
Syntax
strupr(string_name);
E.g.
str[10]= “HEllo”;
strupr(str);
www.EnggTree.com
puts(str);
Output: HELLO
7. strrev() function
It is used to reverse the string.
Syntax
strrev(string_name);
E.g.
str[10]= “HELLO”;
strrev(str);
puts(str);
Output: OLLEH
char arrayname[rowsize][colsize];
E.g.
www.EnggTree.com
char s[2][30];
Here, s can store 2 strings of maximum 30 characters each.
Initialization
2 ways
1. Using string constants
char s[2][20]={“Ram”, “Sam”};
2. Using initialization list.
char s[2][20]={ {‘R’, ‘a’, ‘m’, ‘\0’},
{‘S’, ‘a’, ‘m’, ‘\0’}};
E.g. Program
#include<stdio.h>
void main()
{
Sorting
Sorting is the process of arranging elements either in ascending or in descending
order.
Sorting Methods
www.EnggTree.com
1. Selection Sort
2. Bubble Sort
3. Merge sort
4. Quick sort
1. Selection sort
It finds the smallest element in the list & swaps it with the element present at
the head of the list.
E.g.
25 20 15 10 5
5 20 15 10 25
5 10 15 20 25
www.EnggTree.com
3. Merge Sort:
Merge sort is based on Divide and conquer method.
It takes the list to be sorted and divide it in half to create two unsorted
lists.
The two unsorted lists are then sorted and merged to get a sorted list.
4. Quick Sort
www.EnggTree.com
This method also uses the technique of ‘divide and conquer’.
Pivot element is selected from the list, it partitions the rest of the list into
two parts – a sub-list that contains elements less than the pivot and other
sub-list containing elements greater than the pivot.
The pivot is inserted between the two sub-lists. The algorithm is recursively
applied to sort the elements.
Program:
#include <stdio.h>
void main()
{
www.EnggTree.com
int i, j, temp, n, a[10];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
Output:
Enter the size of an array: 4
Enter the elements of the array: 4 3 5 1
www.EnggTree.com
Enter the number to be search: 5
Element is in the position 3
2. Binary Search
If a list is already sorted then we can easily find the element using
binary serach.
It uses divide and conquer technique.
Steps:
1. The middle element is tested with searching element. If found, its
position is returned.
2. Else, if searching element is less than middle element, search the left half
else search the right half.
3. Repeat step 1 & 2.
Program:
www.EnggTree.com
Searching element=middle element. So the element is found.
Search key=11
Middle element=7
Searching element>middle
So go to right half: 9 11. Repeat steps until 11 is found or list ends.
Introduction to functions
A function is a subprogram of one or more statements that performs a specific task
when called.
Advantages of Functions:www.EnggTree.com
1. Code reusability
2. Better readability
3. Reduction in code redundancy
4. Easy to debug & test.
Classification of functions:
Based on who develops the function
Based on the number of arguments a function accepts
1. Based on who develops the function
There are two types.
1. Library functions
2. User-defined functions
1. Library functions [Built-in functions]
Library functions are predefined functions. These functions are already developed
by someone and are available to the user for use. Ex. printf( ), scanf( ).
2. User-defined functions
User-defined functions are defined by the user at the time of writing a program.
Ex. sum( ), square( )
Using Functions
A function can be compared to a black box that takes in inputs, processes it, and
then outputs the
result. Terminologies using functions are:
A function f that uses another function g is known as the calling function,
and g is known as the called function.
The inputs that a function takes are known as arguments.
www.EnggTree.com
When a called function returns some result back to the calling function, it is
said to return that result.
The calling function may or may not pass parameters to the called function.
If the called function accepts arguments, the calling function will pass
parameters, else not.
Function declaration is a declaration statement that identifies a function’s
name, a list of arguments that it accepts, and the type of data it returns.
Function definition consists of a function header that identifies the function,
followed by the body of the function containing the executable code for that
function.
Function Prototype
Before using a function, the compiler must know the number of parameters
and the type of parameters that the function expects to receive and the data type of
2
value that it will return to the calling program. Placing the function declaration
statement prior to its use enables the compiler to make a check on the arguments
used while calling that function.
Syntax:
return_data_type function_name(data_type variable1, data_type variable2,..);
Here, function_name is a valid name for the function. Naming a function
follows the same rules that are followed while naming variables. A function should
have a meaningful name that must specify the task that the function will perform.
return_data_type specifies the data type of the value that will be returned
to the calling function as a result of the processing performed by the called
function.
(data_type variable1, data_type variable2, ...) is a list of variables of
specified data types.
www.EnggTree.com
These variables are passed from the calling function to the called function.
They are also known as arguments or parameters that the called function accepts to
perform its task.
Function definition
When a function is defined, space is allocated for that function in the memory. A
function definition comprises of two parts:
Function header
Function body
The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statements
3
.............
return(variable);
}
While return_data_type function_name(data_type variable1, data_type
variable2,...) is known as the function header, the rest of the portion comprising of
program statements within the curly brackets { } is the function body which
contains the code to perform the specific task.
Note that the function header is same as the function declaration. The only
difference between the two is that a function header is not followed by a semi-
colon.
Function Call
The function call statement invokes the function. When a function is invoked, the
www.EnggTree.com
compiler jumps to the called function to execute the statements that are a part of
that function. Once the called function is executed, the program control passes
back to the calling function.
Syntax:
function_name(variable1, variable2, ...);
The following points are to be noted while calling a function:
Function name and the number and the type of arguments in the function call
must be same as that given in the function declaration and the function
header of the function definition.
Names (and not the types) of variables in function declaration, function call,
and header of function definition may vary.
Arguments may be passed in the form of expressions to the called function.
In such a case, arguments are first evaluated and converted to the type of
formal parameter and then the body of the function gets executed.
4
If the return type of the function is not void, then the value returned by the
called function may be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);
Working of a function
void main()
{
int x,y,z;
int abc(int, int, int) // Function declaration
…..
…..
abc(x,y,z) // Function Call
… Actual arguments
… www.EnggTree.com
}
Actual arguments – The arguments of the calling function are called as actual
arguments.
Formal arguments – The arguments of called function are called as formal
arguments.
www.EnggTree.com
Built-in functions (string functions, math functions)
The standard library functions are built-in functions in C programming to
handle tasks such as mathematical computations, I/O processing, string handling
etc. These functions are defined in the header file.
The printf() is a standard library function to send formatted output to the
screen (display output on the screen). This function is defined in "stdio.h" header
file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all
these functions are available for use.
#include <stdio.h>
int main() {
char input_str[20];
char *output_str;
strcpy(input_str, "Hello");
printf("input_str: %s\n", input_str);
output_str = strcpy(input_str, "World");
Output:
input_str: Hello
input_str: World
output_str: World
Output:
The names are different
#include<stdio.h>
#include<string.h>
int main( )
{
char str[] = “ String Functions”;
printf(“%s \n”, strupr(str));
printf(“%s \n”, strlwr(str));
return 0;
}
Output:
STRING FUNCTIONS
string functions
Recursion www.EnggTree.com
A function that calls itself is known as a recursive function.
Direct & Indirect Recursion:
Direct Recursion:
A function is directly recursive if it calls itself.
A( )
{
….
….
A( );// call to itself
….
}
Indirect Recursion:
Function calls another function, which in turn calls the original function.
10
A( )
{
…
…
B( );
…
}
B( )
{
…
…
A( );// function B calls A
…
} www.EnggTree.com
Consider the calculation of 6! ( 6 factorial )
ie 6! = 6 * 5 * 4 * 3 * 2 * 1
6! = 6 * 5!
6! = 6 * ( 6 - 1 )!
n! = n * ( n - 1 )!
Types of Recursion
Direct Recursion
A function is said to be directly recursive if it explicitly calls itself. Here, the
function Func() calls itself for all positive values of n, so it is said to be a directly
recursive function.
int Func (int n)
{
11
if (n == 0)
return n;
else
return (Func (n–1));
}
Indirect Recursion
A function is said to be indirectly recursive if it contains a call to another function
which ultimately calls it. These two functions are indirectly recursive as they both
call each other.
int Funcl (int n)
{
if (n == 0)
return n; www.EnggTree.com
else
return Func2(n);
}
int Func2(int x)
{
return Func1(x–1);
}
Tail Recursion
A recursive function is said to be tail recursive if no operations are pending to be
performed when the recursive function returns to its caller. When the called
function returns, the returned value is immediately returned from the calling
function.
12
int Fact(int n)
{
if (n == 1)
return 1;
else
return (n * Fact(n–1));
}
The above function is a nontail-recursive function, because there is a
pending operation of multiplication to be performed on return from each recursive
call. Whenever there is a pending operation to be performed, the function becomes
non-tail recursive. In such a non-tail recursive function, information about each
pending operation must be stored, so the amount of information directly depends
on the number of calls.
int Fact(n) www.EnggTree.com
{
return Fact1(n, 1);
}
int Fact1(int n, int res)
{
if (n == 1)
return res;
else
return Fact1(n–1, n*res);
}
The same factorial function can be written in a tail recursive manner. In the code,
Fact1 function preserves the syntax of Fact(n). Here the recursion occurs in the
Fact1 function and not in Fact function. Fact1 has no pending operation to be
13
performed on return from recursive calls. The value computed by the recursive call
is simply returned without any modification. So in this case, the amount of
information to be stored on the system stack is constant (only the values of n and
res need to be stored) and is independent of the number of recursive calls.
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int fact(int);
int n,f;
printf(“Enter the number \n”);
scanf(“%d”,&n); www.EnggTree.com
f=fact(n);
printf(“The factorial of a number =%d”,f);
getch();
}
int fact(int n)
{
if(n==1)
return(1);
else
return n*fact(n-1);
}
OUTPUT
Enter the number to find the factorial
14
5
The factorial of a number=120
return 1;
Observe the series of function calls. When the function pending operations in turn
calls the function
Fibonacci(7) = Fibonacci(6) + Fibonacci(5)
Fibonacci(6) = Fibonacci(5) + Fibonacci(4)
Fibonacci(5) = Fibonacci(4) + Fibonacci(3)
Fibonacci(4) = Fibonacci(3) + Fibonacci(2)
Fibonacci(3) = Fibonacci(2) + Fibonacci(1)
Fibonacci(2) = Fibonacci(1) + Fibonacci(0)
Now we have, Fibonacci(2) = 1 + 0 = 1
Fibonacci(4) = 2 + 1 = 3
Fibonacci(5) = 3 + 2 = 5
Fibonacci(6) = 3 + 5 = 8
www.EnggTree.com
Fibonacci(7) = 5 + 8 = 13
Tower of Hanoi
The tower of Hanoi is one of the main applications of recursion. It says, ‘if
you can solve n–1 cases, then you can easily solve the nth case’. The figure (a)
below shows three rings mounted on pole A. The problem is to move all these
rings from pole A to pole C while maintaining the same order. The main issue is
that the smaller disk must always come above the larger disk.
16
In our case, A is the source pole, C is the destination pole, and B is the spare
pole. To transfer all the three rings from A to C, we will first shift the upper two
rings (n–1 rings) from the source pole to the spare pole. We move the first two
rings from pole A to B as shown in figure (b) .
Now that n–1 rings have been removed from pole A, the nth ring can be
easily moved from the source pole (A) to the destination pole (C). Figure (c) shows
this step.
The final step is to move the n–1 rings from the spare pole (B) to the
destination pole (C). This is shown in Fig. (d)
To summarize, the solution to our problem of moving n rings from A to C using B
as spare can be given as:
Base case: if n=1
Move the ring from A to C using B as spare
Recursive case: www.EnggTree.com
Move n – 1 rings from A to B using C as spare
Move the one ring left on A to C using B as spare
Move n – 1 rings from B to C using A as spare
Figure (a)
17
Figure (b)
Figure (c)
www.EnggTree.com
Figure (d)
Example Program
Program for Computation of Sine series
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
18
{
int i, n ;
float x, val, sum, t ;
clrscr() ;
printf("Enter the value for x : ") ;
scanf("%f", &x) ;
printf("\nEnter the value for n : ") ;
scanf("%d", &n) ;
val = x ;
x = x * 3.14159 / 180 ;
t=x;
sum = x ;
for(i = 1 ; i < n + 1 ; i++)
{ www.EnggTree.com
t = (t * pow((double) (-1), (double) (2 * i - 1)) * x * x) / (2 * i * (2 * i + 1)) ;
sum = sum + t ;
}
printf("\nSine value of %f is : %8.4f", val, sum) ;
getch() ;
}
Output:
Enter the value for x : 30
Enter the value for n : 20
Sine value of 30.000000 is : 0.5000
19
int a[10],i,n,m,c,l,u;
l=0,u=n-1;
c=binary(a,n,m,l,u);
if(c==0)
20
return 0;
}
int mid,c=0;
if(l<=u)
{ www.EnggTree.com
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
}
else if(m<a[mid])
{
return binary(a,n,m,l,mid-1);
}
else
return binary(a,n,m,mid+1,u);
}
else
21
return c;
}
Output:
Enter the size of an array: 5
Enter the elements of the array: 8 9 10 11 12
Enter the number to be search: 8
Number is found.
Pointers
Definition:
A pointer is a variable that stores the address of a variable or a function
Advantages
1. Pointers save memory space
2. Faster execution
www.EnggTree.com
3. Memory is accessed efficiently.
Declaration
datatype *pointername;
int a=10; p a
int *p=&a;
2000 10
4000 2000
p is an integer pointer & holds the address of an int variable a.
Pointer to pointer
A pointer that holds the address of another pointer variable is known as a
pointer to pointer.
E.g.
22
int **p;
6000
6000 pptr
8000
So **pptr=12
Operations on pointers
a 12.5
1000 1000
P
2000
2. Dereferencing a pointer
The object referenced by a pointer can be indirectly accessed by
dereferencing the pointer. Dereferencing operator (*) is used for this .This
operator is also known as indirection operator or value- at-operator
Eg) int b;
int a=12;
a 12 int *p;
23 B. Shanmuga Sundari csenotescorner.blogspot.com
1000
Downloaded from EnggTree.com
CS3251 Programming in C UNIT
EnggTree.com
III
1000 p=&a;
b=*p; \\value pointed by p(or)value
at 1000=12,
p so b=12
2000
Example program
#include<stdio.h>
void main() Note
{
int a=12; %p is used for addresses; %u
int *p; can also be used.
int **pptr;
p=&a; *p=value at p
=value at (1000)=12
pptr=&p;
printf(“a value=%d”,a); *pptr=value at(pptr)
printf(“value by dereferencing p is %d \n”,*p); =value at(value at (2000))
printf(“value by dereferencing pptr is %d \n”,**pptr ); =value at (1000)=12
printf(“value of p is %u \n”,p);
printf(“value of pptr is %u\n”,pptr);
}
Output: www.EnggTree.com
a value=12
value by dereferencing p is 12
value by dereferencing pptr is 12
value of p is 1000
value of pptr is 2000
a 12
1000 p 1000
3000
Pointer arithmetic
Arithmetic operations on pointer variables are also possible.
24
1. Addition
(i) An addition of int type can be added to an expression of pointer type. The result
is pointer type.(or)A pointer and an int can be added.
25
Pre-
increment
Result =
initial value
of pointer +
sizeof (T)
Eg. post float* - float* ftr=p++ ftr=? ftr=2000
26
Pre-
decrement
Result =
initial value
of pointer –
sizeof(T)
Eg.pre float* - float* ftr=--p ftr=? ftr=1996
decrement p=2000 p=1996 Value of ptr
27
= Value of
ptr –
sizeof(T)
E.g.) E1[E2]=>*(E1+E2)
Example
#include<stdio.h>
void main()
{
int a[3]={10,15,20};
printf(“Elements are %d %d %d\n”, a[0],a[1],a[2]);
printf(“Elements are %d %d %d\n”, *(a+0),*(a+1),*(a+2);
}
Output:
Elements are 10 15 20
Elements are 10 15 20
10 20 30
29
Example:
Now look at another code in which we store the address of three individual arrays
in the array of pointers:
int main()
{
int arr1[]={1,2,3,4,5};
int arr2[]={0,2,4,6,8};
int arr3[]={1,3,5,7,9};
int *parr[3] = {arr1, arr2, arr3};
int i; www.EnggTree.com
for(i = 0;i<3;i++)
printf(«%d», *parr[i]);
return 0;
}
Output
101
Example Program
Sorting of names
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
30
char *x[20];
int i,n=0;
void reorder(int n,char *x[]);
clrscr();
printf("Enter no. of String : ");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;i++)
{
printf("Enter the Strings %d : ",i+1);
x[i]=(char *)malloc(20*sizeof(char));
scanf("%s",x[i]);
}
reorder(n,x);
printf("\nreorder list is : \n");
for(i=0;i<n;i++)
{
printf("%d %s\n",i+1,x[i]);
}
www.EnggTree.com
getch();
}
void reorder(int n,char *x[])
{
int i,j;
char t[20];
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(strcmp(x[i],x[j])>0)
{
strcpy(t,x[j]);
strcpy(x[j],x[i]);
strcpy(x[i],t);
}
return;
}
Output:
Enter no. of string 5
31
Parameter passing
www.EnggTree.com
Whenever we call a function then sequence of executable statements gets executed.
We can pass some of the information to the function for processing
called argument. There are two ways in which arguments can be passed from
calling function to called function. They are:
1. Pass by value
2. Pass by reference
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int ,int);
a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
www.EnggTree.com
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
OUTPUT:
Before swapping: a =10 and b =20
33
www.EnggTree.com
34
Main function
a b
10 20
1000 1002
Swap function
a1 b1
10 20
2000 2002
After swap function
a1 b1 www.EnggTree.com
20 10
2000 2002
Example Program:
35
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *,int *);
a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)www.EnggTree.com
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
OUTPUT:
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10
Main function
a b
36
10 20
1000 1002
Swap function
a1 b1
1000 1002
2000 2002
After swap function
a b
20 10
www.EnggTree.com
1000 1002
Example Program: Swapping of two numbers and changing the value ofa
variable using pass by reference
#include<stdio.h>
#include<conio.h>
void swap(int *num1, int *num2);
void main() {
int x, y;
printf("\nEnter First number : ");
scanf("%d", &x);
printf("\nEnter Second number : ");
scanf("%d", &y);
37
Output:
Enter First number : 12 www.EnggTree.com
Enter Second number : 21
38
UNIT IV STRUCTURES
Structure - Nested structures – Pointer and Structures – Array of structures – Example
Program using structures and pointers – Self referential structures – Dynamic memory
allocation - Singly linked list - typedef
4.1 Introduction
Using C language we can create new data types. These data types are known as
User Defined data types & can be created by using Structures, Unions &
Enumerations.
Need for Structure
Arrays can store data of same data type. They can’t be used to store data of
different data types. For this Structures are used.
Structures
A structure is a collection of variables of different types under a single name. It
is used for storing different types of data.
3 aspects:
1. Defining a structure type
2. Declaring variables
www.EnggTree.com
3. Using & performing operations.
4.1.1 Structure Definition
The structure can be defined with the keyword struct followed by the name of
structure and opening brace with data elements of different type then closing brace
with semicolon.
General Form
struct [structure tag name]
{
type membername1;
type membername2;
……
}[variable name];
E.g.
struct book
{
char title[25];
int pages;
float price;
};
• Structure definition does not reserve any space in the memory.
• It is not possible to initialize the structure members during the structure
definition.
• A structure definition must always be terminated with a semicolon.
www.EnggTree.com
Suppose, we want to access title of structure variable b1, then, it can be
accessed as:
b1.title
We can also directly assign values to members.
b1.title= “CP”;
4.2 Structures within a Structure (Nested Structures)
A structure can be nested within another structure. Structure within structure is
known as nested structure i.e.) one structure can be declared inside other.
Example program:
#include<stdio.h>
struct name
{
char fname[20],lastname[20];
};
struct student
{
int sno,m1,m2,m3;
int tot;
float avg;
struct name sname;
};
void main()
{
struct student s[10];
float,avg;
int n,i;
printf(“Enter the number of students \n”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{ www.EnggTree.com
printf(“Enter student details \n”);
scanf(“%d”,&s[i].sno);
scanf((“%d%d%d”,&s[i].m1, &s[i].m2, &s[i].m3);
scanf(“%s”, s[i].sname.fname);
scanf((“%s”,s[i].sname.lastname);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/6.0;
}
printf(“Student Mark lists\n”);
for(i=0;i<n;i++)
printf(“%s\t%s\t%f”,s[i].sname.fname, s[i].sname.lastname,s[i].avg);
}
Output:
E.g) s[i].sname.lastname
student www.EnggTree.com
sn
o
m1
m2
m3
avg
name
fname
lastname
4.3 Pointer and Structures
Example:
struct struct_name
{
data_type member_name1;
data_type member_name2;
.....................................
}*ptr;
OR
www.EnggTree.com
struct struct_name *ptr;
Dot(.) operator is used to access the data using normal structure variable and arrow
(->) is used to access the data using pointer variable.
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
ptr = &record1;
printf("Records of Student: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}
Output:
Records of Student:
Id is: 1
Name is: Sankar www.EnggTree.com
Percentage is: 90.500000
Using a single structure variable we can store single student details. To store
information about several students, we have to create a separate variable for each
student. It is not feasible. So array of structures are used.
General form
E.g. Program:
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[15];
int empid,bsal;
float net,gross;
};
www.EnggTree.com
void main()
{
struct employee emp[10];
float hra,da,tax;
int n,i,j;
clrscr();
printf("Enter the number of employees\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter the employee name");
scanf("%s",emp[i].name);
printf("\nEnter the employee id");
scanf("%d",&emp[i].empid);
printf("\nEnter the basic salary");
scanf("%d",&emp[i].bsal);
hra=((10*emp[i].bsal)/100);
da=((35*emp[i].bsal)/100);
tax=((15*emp[i].bsal)/100);
emp[i].gross=emp[i].bsal+hra+da;
emp[i].net=emp[i].gross-tax;
}
printf("Employee Name Employee ID Employee Net Salary \n");
for(i=1;i<=n;i++)
printf("%s\t\t%d\t\t%f\n",emp[i].name,emp[i].empid,emp[i].net);
getch();
}
Output: www.EnggTree.com
Enter the number of Employees
2
Enter the employee name
Anu
Enter the employee id
01
Enter the basic salary
1000
Enter the employee name
Meena
Enter the employee id
02
Enter the basic salary
2000
Employee Name Employee ID Net Salary
Anu 01 1300.000
Meena 02 2600.000
10
www.EnggTree.com
4.6 Self referential structures
Self referential Structures are those structures that contain a reference to data of its
same type. i.e in addition to other data a self referential structure contains a pointer to
a data that it of the same type as that of the structure. For example: consider the
structure node given as follows:
struct node
{
int val;
struct node *next;
};
Here the structure node will contain two types of data an integer val and next which is
a pointer a node. Self referential structure is the foundation of other data structures.
11
1. malloc() function
malloc() allocates N bytes in memory and return pointer to allocated memory. The
returned pointer contains link/handle to the allocated memory.
void * malloc(number_of_bytes);
• It returns void pointer (generic pointer). Which means we can easily typecast it
to any other pointer types.
• It accepts an integer number_of_bytes, i.e. total bytes to allocate in memory.
Note: malloc() returns NULL pointer on failure.
www.EnggTree.com
Example
int N = 10; // Number of bytes to allocate
int *ptr; // Pointer variable to store address
ptr = (int *) malloc(N * sizeof(int)); // Allocate 10 * 4 bytes in memory
Here,
• ptr is a pointer to integer to store address of the allocated memory.
• (int *) is typecast required. As, I mentioned above that malloc() return void *.
Hence, to work with void pointer we must typecast it to suitable type.
• N * sizeof(int) - Since size of int is not fixed on all compilers. Hence, to get size
of integer on current compiler I have used sizeof() operator.
2. calloc() function
12
3. realloc() function
www.EnggTree.com
When working with huge data and if the allocated memory is not sufficient to store data.
In that case, we need to alter/update the size of an existing allocated memory blocks
(which has been created by either malloc() or calloc()).
We use realloc() function to alter/update the size of exiting allocated memory blocks.
The function may resize or move the allocated memory blocks to a new location.
Syntax
void* realloc(ptr, updated_memory_size);
• Similar to all other functions for Dynamic Memory Allocation in C, it returns
void pointer. Which points to the address of existing or newly allocated memory.
• ptr is a pointer to memory block of previously allocated memory.
• updated_memory_size is new (existing + new) size of the memory block.
Example
13
int N = 10;
int *ptr;
ptr = (int *) malloc(N * sizeof(int));
4. free() function
C programming has a built-in library function free() to clear or release the unused
memory.
The free() function clears the pointer (assigns NULL to the pointer) to clear the
dynamically allocated memory. If pointer contains NULL, then free() does nothing
(because pointer will not be pointing at any memory addresses). If it contains any
address of dynamically allocated memory, free() will clear pointer by assigning NULL.
Syntax
www.EnggTree.com
free(ptr);
The function accepts a void pointer ptr. It points to previously allocated memory using
any of Dynamic Memory Allocation functions in C.
Example:
int N=10;
int *ptr;
// Allocate memory using malloc
ptr=(int *) malloc (N* size of (int));
//Free allocated memory
free(ptr);
14
• Linked list is a data structure which in turn can be used to implement other data
structures. Thus, it acts as building block to implement data structures like stacks,
queues and their variations.
• A linked list can be perceived as a train or a sequence of nodes in which each
node contain one or more data fields and a pointer to the next node.
START
1 2 3 4 5 6 7 X
In the above linked list, every node contains two parts- one integer and the other a
pointer to the next node. The left part of the node which contains data may include a
simple data type, an array or a structure. The right part of the node contains a pointer to
the next node (or address of the next node in sequence). The last node will have no next
node connected to it, so it will store a special value called NULL.
A singly linked list is the simplest type of linked list in which every node contains some
data and a pointer to the next node of the same data type. By saying that the node
www.EnggTree.com
contains a pointer to the next node we mean that the node stores the address of the next
node in sequence.
In this algorithm, we first initialize PTR with the address of start. So now PTR points
to the first node of the linked list.
Then in step 2 while loop is executed which is repeated till PTR processes the last node,
that is, until it encounters NULL.
In step 3, we apply the process to the current node.
In step 4, we move to the next node by making PTR point to the node whose address is
stored in the NEXT field.
The algorithm print the information stored in each node of the linked list is shown
below:
www.EnggTree.com
Algorithm to print the information stored in
each node of the linked list
Step 1: [INITIALIZE] SET PTR = START
Step 2: Repeat Steps 3 and 4 while PTR != NULL
Step 3: Write PTR->DATA
Step 4: SET PTR = PTR->NEXT
[END OF LOOP]
Step 5: EXIT
We will traverse each and every node of the list and while traversing every individual
node, we will increment the counter by 1. Once we reach NULL, that is when all the
nodes of the linked list have been traversed, the final value of the counter will be
displayed. Figure below shows the algorithm to print the number of nodes in a linked
list.
www.EnggTree.com
[END OF IF]
[END OF LOOP]
Step 4: SET POS = NULL
Step 5: EXIT
Consider the linked list shown in figure we have val=4, then the flow of the algorithm
can be explained as shown in figure
1 7 3 4 2 6 5 X
1 7 3 4 2 6 5 X
1 7 3 4 2 6 5 X
4.8.3 Insertion in a Singly Linked List
1 7 3 4 2 6 5 X
17
Insert a new node at the head of the list is straightforward. The main idea is that we
create a new node, set its next link to refer to the current head, and then set head to point
to the new node.
Algorithm addFirst(String newData):
create a new node v containing newData
v.setNext(head)
head = v
size = size + 1
18
Algorithm removeFirst()
if (head = = null) then
Indicate an error: the list is empty
tmp = head
head = head.getNext()
tmp.setNext(null)
size = size - 1
Example:
include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct test_struct
{
int val;
struct test_struct *next;
}; www.EnggTree.com
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
struct test_struct* create_list(int val)
{
printf("\n creating list with headnode as [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n"); return NULL;
}
ptr->val = val;
ptr->next = NULL;
head = curr = ptr;
return ptr;
19
}
struct test_struct* add_to_list(int val, bool add_to_end)
{
if(NULL == head)
{
return (create_list(val));
}
if(add_to_end)
printf("\n Adding node to end of list with value [%d]\n",val);
else printf("\n Adding node to beginning of list with value [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{ printf("\n Node creation failed \n"); return NULL;
}
ptr->val = val;
ptr->next = NULL;
if(add_to_end) www.EnggTree.com
{ curr->next = ptr; curr = ptr;
}
else { ptr->next = head; head = ptr;
}
return ptr;
}
struct test_struct* search_in_list(int val, struct test_struct **prev)
{
struct test_struct *ptr = head;
struct test_struct *tmp = NULL;
bool found = false;
printf("\n Searching the list for value [%d] \n",val);
while(ptr != NULL)
{
20
if(ptr->val == val)
{ found = true; break;
}
else
{
tmp = ptr; ptr = ptr->next;
}
}
if(true == found)
{
if(prev) *prev = tmp;
return ptr;
}
else
{
return NULL; } }
www.EnggTree.com
int delete_from_list(int val)
{
struct test_struct *prev = NULL;
struct test_struct *del = NULL;
printf("\n Deleting value [%d] from list\n",val);
del = search_in_list(val,&prev);
if(del == NULL) { return -1; }
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{ curr = prev;
}
else if(del == head)
21
{
head = del->next;
}}
free(del);
del = NULL; return 0;
}
void print_list(void) {
struct test_struct *ptr = head;
printf("\n -------Printing list Start------- \n");
while(ptr != NULL)
{
printf("\n [%d] \n",ptr->val);
ptr = ptr->next;
}
printf("\n -------Printing list End------- \n"); return;
}
int main(void) www.EnggTree.com
{
int i = 0, ret = 0;
struct test_struct *ptr = NULL;
print_list();
for(i = 5; i<10; i++)
add_to_list(i,true); print_list();
for(i = 4; i>0; i--)
add_to_list(i,false);
print_list();
for(i = 1; i<10; i += 4)
{ ptr = search_in_list(i, NULL);
if(NULL == ptr)
{
printf("\n Search [val = %d] failed, no such element found\n",i);
22
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val); }
print_list(); ret = delete_from_list(i);
if(ret != 0) { printf("\n delete [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n delete [val = %d] passed \n",i); } print_list(); } return 0;
}
4.9 Typedef
The typedef keyword enables the programmer to create a new data type name by using
an existing data type.
By using typedef, no new data is created, rather an alternate name is given to a known
data type. www.EnggTree.com
Syntax: typedef existing_data_type new_data_type;
23
2. A data structure that can store related information of different data types
together is
A. array
B. string
C. Structure
D. all of these
Answer: Structure
24
25
26
27
5.1 Introduction
Named means that a particular collection of data on a disk has a name, like
mydata.dat and access to the collection is done by using its name.
A file represents a sequence of bytes on the disk where a group of related data
is stored. File is created for permanent storage of data. It is a readymade structure.
1. Text files
2. Binary files
1. Text Files www.EnggTree.com
A text file consists of consecutive characters, which are interpreted by the
library functions used to access them and by format specifiers used in functions.
Text files are the normal .txt files that you can easily create using Notepad or
any simple text editors.
They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.
2. Binary files
A binary file consists of bytes of data arranged in continuous block. A separate
set of library functions is there to process such data files.
Binary files are mostly the .bin files in your computer. Instead of storing data in
plain text, they store it in the binary form (0's and 1's). They can hold higher amount
of data, are not readable easily and provides a better security than text files.
In C, you can perform four major operations on the file, either text or binary:
3. Closing a file
Function description
www.EnggTree.com
fseek() - set the position to desire point
Opening a file means creating a new file with specified file name and with accessing
mode.
The fopen() function is used to create a new file or to open an existing file.
Syntax:
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the
opened(or created) file.
filename is the name of the file to be opened and mode specifies the purpose of
opening the file.
Mode Description
Mode Purpose
ab+ www.EnggTree.com
opens a binary file in both reading and writing mode
2. Closing a File
A file must be closed after all the operation of the file have been completed. The
fclose() function is used to close an already opened file.
Syntax:
Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.
The ‘fgetc’ function is used to read a character from a file which is opened in read
mode.
Syntax:
c=fgetc(p1);
The fscanf function is used to read data from a file. It is similar to the scanf function
except that fscanf() is used to read data from the disk.
Syntax:
where fb refers to the file pointer. v1, v2, … vn refers variables whose values are read
from the disk “format string” refers the control string which represents the conversion
specification.
The function ‘fputc’ is used to write a character variable x to the file opened in write
mode. www.EnggTree.com
Syntax:
fputc(x,fp1);
fprintf() function is used to write data to a file. It is similar to the printf() function
except that fprintf() is used to write data to the disk.
Syntax:
1. Sequential Access — In this type of file, the data are kept sequentially. To read last
record of the file, it is expected to read all the records before that particular record. It
takes more time for accessing the records.
2. Random Access — In this type of file, the data can be read and modified
randomly. If it is desired to read the last record of a file, directly the same record can
be read. Due to random access of data, it takes less access time as compared to the
sequential file.
A Sequential file is characterized by the fact that individual data items are
arranged serially in a sequence, one after another. They can only be processed in serial
order from the beginning. In other words, the records can be accessed in the same
manner in which they have been stored. It is not possible to start reading or writing a
sequential file from anywhere except at the beginning.
The second and better method of arranging records of a file is called direct
access or random access. In this arrangement one can have access to any record which
is situated at the middle of the file without reading or passing through other records in
the file.
www.EnggTree.com
5.3 Reading Sequential Access file
Data is stored in files so that the data can be retrieved for processing when needed
Example:
Program:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
exit(0);
} // end while
} // end main
Output:
/* Program to read from the num.dat file and find the average of the numbers */
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fp;
int n[50], i = 0;
float sum = 0;
exit(0); www.EnggTree.com
}
while (!feof(fp)) {
sum += n[i];
i++;
fclose(fp);
if (i == 0)
return 0;
Output:
} byte offsets
}
}
}
}
}
}
The functions used to randomly access a record stored in a file are fseek(), ftell(),
rewind(), fgetpos(), and fsetpos().
1. fseek()
• fseek() is used to set the file position pointer for the given stream. Offset is an
integer value that gives the number of bytes to move forward or backward in
the file. Offset may be positive or negative, provided it makes sense. For
example, you cannot specify a negative offset if you are starting at the
beginning of the file. The origin value should have one of the following values
(defined in stdio.h):
• SEEK_SET: to perform input or output on offset bytes from start of the file
• www.EnggTree.com
SEEK_END: to perform input or output on offset bytes from the end of the file
• fseek() can be used to move the file pointer beyond a file, but not before the
beginning.
Example: Write a program to print the records in reverse order. The file must be
opened in binary mode. Use fseek()
#include<stdio.h>
#include<conio.h>
main()
{ int emp_code;
char name[20];
int hra;
int da;
int ta;
};
FILE *fp;
struct employee e;
int result, i;
fp = fopen("employee.txt", "rb");
if(fp==NULL)
exit(1);
} www.EnggTree.com
for(i=5;i>=0;i--)
fclose(fp);
getch();
return 0;
2. rewind()
10
• rewind() is used to adjust the position of file pointer so that the next I/O
operation will take place at the beginning of the file. It’s prototype can be given
as
3. fgetpos()
• The fgetpos() is used to determine the current position of the stream. It’s
prototype can be given as
• Here, stream is the file whose current file pointer position has to be determined.
pos is used to point to the location where fgetpos() can store the position
information. The pos variable is of type fops_t which is defined in stdio.h and
is basically an object that can hold every possible position in a FILE.
www.EnggTree.com
the fsetpos() to return to this same position.
4. fsetpos()
• The fsetpos() is used to move the file position indicator of a stream to the
location indicated by the information obtained in "pos" by making a call to the
fgetpos(). Its prototype is
• Here, stream points to the file whose file pointer indicator has to be re-
positioned. pos points to positioning information as returned by "fgetpos".
• On success, fsetpos() returns a zero and clears the end-of-file indicator. In case
of failure it returns a non-zero value
The program opens a file and reads bytes at several different locations.
#include <stdio.h>
main()
11
FILE *fp;
fpos_t pos;
char feedback[20];
fp = fopen(“comments.txt”, “rb”);
if(fp == NULL)
exit(1);
www.EnggTree.com
printf(“\n Error in fgetpos()");
exit(1);
pos = 90;
exit(1);
12
fclose(fp);
5. ftell()
The ftell function is used to know the current position of file pointer. It is at this
position at which the next I/O will be performed. The syntax of the ftell() defined in
stdio.h can be given as:
On successful, ftell() function returns the current file position (in bytes) for stream.
However, in case of error, ftell() returns -1.
When using ftell(), error can occur either because of two reasons:
First, using ftell() with a device that cannot store data (for example, keyboard)
Second, when the position is larger than that can be represented in a long integer. This
will usually happen when dealing with very large files
FILE *fp;
char c;
www.EnggTree.com
int n;
fp=fopen("abc","w");
if(fp==NULL)
exit(1);
while((c=getchar())!=EOF)
putc(c,fp);
n = ftell(fp);
fclose(fp);
fp=fopen("abc","r");
13
if(fp==NULL)
exit(1);
while(ftell(fp)<n)
{ c= fgetc(fp);
printf('%c", c);
fclose(fp);
Option 1
calls function textFile to store a formatted list of all the accounts (typically called a
report) in a text file called accounts.txt that may be printed later. The function
uses fread and the sequential file access techniques used in the program of Section
below.
14
Option 2
calls the function updateRecord to update an account. The function will update only
a record that already exists, so the function first checks whether the record specified
by the user is empty. The record is read into structure client with fread, then member
acctNum is compared to 0. If it’s 0, the record contains no information, and a message
is printed stating that the record is empty. Then the menu choices are displayed. If the
record contains information, function updateRecord inputs the transaction amount,
calculates the new balance and rewrites the record to the file.
Option 3
calls the function newRecord to add a new account to the file. If the user enters an
account number for an existing account, newRecord displays an error message
indicating that the record already contains information, and the menu choices are
www.EnggTree.com
printed again
Option 4
calls function deleteRecord to delete a record from the file. Deletion is accomplished
by asking the user for the account number and re-initialising the record. If the account
contains no information, deleteRecord displays an error message indicating that the
account does not exist.
Option 5
Example Program:
15
#include <stdio.h>
#include <stdlib.h>
struct clientData {
// prototypes
exit(-1);
16
switch (choice) {
case 1:
textFile(cfPtr); break;
// update record
case 2:
updateRecord(cfPtr); break;
// create record
case 3:
newRecord(cfPtr); break;
www.EnggTree.com
// delete existing record
case 4:
deleteRecord(cfPtr); break;
default:
} // end switch
} // end while
} // end main
17
} // end if
else {
while (!feof(readPtr)) {
} // end if
} // end while
} // end else
18
scanf("%d", &account);
if (client.acctNum == 0) {
www.EnggTree.com
printf("Account #%d has no information.\n", account);
client.firstName, client.balance);
scanf("%lf", &transaction);
19
} // end else
if (client.acctNum == 0) {
} // end if
20
} // end else
scanf("%d", &accountNum);
www.EnggTree.com
// move file pointer to correct record in file
if (client.acctNum != 0) {
} // end if
else { // create record user enters last name, first name and balance
client.acctNum = accountNum;
21
} // end else
www.EnggTree.com
" \"accounts.txt\" for printing\n"
return menuChoice;
Output
22
www.EnggTree.com
Syntax:
23
Here argc counts the number of arguments on the command line and argv[ ] is a
pointer array which holds pointers of type char which points to the arguments passed
to the program
Example:
#include <stdio.h>
#include <conio.h>
int i;
else
return 0;
Remember that argv[0] holds the name of the program and argv[1] points to the first
command line argument and argv[n] gives the last argument. If no argument is
24
A. Buffer
B. Stream
C. File
Answer: File
2. If the mode includes b after the initial letter, what does it indicates?
a) text file
b) big text file
c) binary file
Answer: binary file
www.EnggTree.com
3. What is the function of the mode ‘ w+’?
a) create text file for writing, discard previous contents if any
b) create text file for update, discard previous contents if any
c) create text file for writing, do not discard previous contents if any
d) create text file for update, do not discard previous contents if any
Answer: create text file for update, discard previous contents if any
25
B) FILE
C) FILEFP
D) filefp
Answer: FILE
B. fprintf()
26
C. fputc()
D. fputs()
Answer: fwrite()
A. stdin
B. stdout
C. stderr
D. all of these
A. Stdin
B. stdout www.EnggTree.com
C. stderr
D. all of these
Answer: stderr
A. file pointer
B. buffer
C. stdout
D. stdin
Answer: buffer
A. fread()
27
B. fopen()
C. floes()
D. fflush()
Answer: fopen()
14. Which function returns the next character from stream, EOF if the end of file
is reached, or if there is an error?
A. fgetc()
B. fgets()
C. fputs()
D. fwrite()
Answer: fgetc()
www.EnggTree.com
28