Cse Programming For Problem Solving Course Resources
Cse Programming For Problem Solving Course Resources
Cse Programming For Problem Solving Course Resources
Course Code:ACSB01
I B.Tech II Semester
BY
Mr. P Ravinder
Assistant Professor
1 2
MODULE – I
INTRODUCTION
1 3
Running Course Learning Outcomes
CLOs Course Learning Outcomes
CLO1 Describe the concept of file system.
CLO2 Analyze a given problem and develop an algorithm
to solve the problem.
CLO3 Describe the fundamental programming constructs
and articulate how they are used to develop a
program with a desired runtime execution flow.
CLO4 Gain knowledge to identify appropriate C language
constructs to write basic programs.
1 4
CLOs Course Learning Outcome
CLO5 Identify the right data representation formats based
on the requirements of the problem.
CLO6 Describe the operators, their precedence and
associativity while evaluating expressions in program
statements.
1 5
Computer systems
Definition:
A Computer is an electronic device that stores, manipulates and
retrieves the data.
The following are the objects of computer System
1 6
Computer system components
1 7
Memory Unit
The Memory unit is classified into two types.
They are:
1. Primary Memory
2. Secondary Memory
Primary memory:The following are the types of memories which are
treated as primary
ROM: It represents Read Only Memory that stores data and instructions
even when the computer is turned off. The Contents in the ROM are
modified if they are written . It is used to store the BIOS information.
RAM: It represents Random Access Memory that stores data and
instructions when the computer is turned on. The contents in the RAM
can be modified any no. of times by instructions. It is used to store the
programs under execution.
Secondary Memory: The following are the different kinds of memories
Magnetic Storage: The Magnetic Storage devices store information
that can be read, erased and rewritten a number of times.
Example: Floppy Disks, Hard Disks, Magnetic Tapes
1 8
Software classification:
1 9
Application software
1 10
Relationship between system software and application software
each circle represents an interface point .The inner core is hard ware. The
user is represented by the out layer. To work with the system, the typical user
uses some form of application software. The application software in turn
interacts with the operating system, which is a part of the system software
layer. The system software provides the direct interaction with the hard
ware.
1 11
Computing Environments
1 12
Personal Computing Environment
In 1971, Marcian E. Hoff, working for INTEL combined basic elements the of the
central processing unit into the microprocessor. If we are using a personal
computer then all the computer hardware components are tied together. This
kind of computing is used to satisfy the needs of a single user, who uses the
computer for the personal tasks.
1 13
Distributed Computing
A distributed computing environment provides a seamless
integration of computing functions between different servers
and clients. A client not just a requestor for processing the
information from the server. The client also has the capability to
process information. All the machines Clients/Servers share the
processing task.
1 14
Computer languages
Computer languages
1 15
Machine Language
1 16
Symbolic Languages (or) Assembly
1 17
High-Level Languages
1 18
Language Translators
These are the programs which are used for converting the programs
in one language into machine language instructions, so that they can
be excuted by the computer.
1 19
Creating And Running Programs
The procedure for turning a program written in C into machine
Language.
1 20
Creating And Running Programs
1 21
Writing and Editing Programs
1 22
Compiling Programs
The code in a source file stored on the disk must be translated
into machine language.
This is the job of the compiler.
The Compiler is a computer program that translates the source
code written in a high- level language into the corresponding
object code of the low-level language.
1 23
Executing Programs
1 24
Algorithm
Precise step-by-step plan for a computational procedure that begins with
an input value and yields an output value in a finite number of steps.
1 25
Properties of algorithms
Finiteness:
an algorithm terminates after a finite numbers of steps.
Definiteness:
each step in an algorithm is unambiguous. This means that the
action specified by the step cannot be interpreted in multiple ways
& can be performed without any confusion.
Input:
An algorithm accepts zero or more inputs.
Output:
It produces at least one output.
Effectiveness:
-It consists of basic instructions that are realizable. This means that the
instructions can be performed by using the given inputs in a finite amount
of time.
1 26
Flowchart
A flowchart is a type of diagram, that represents an algorithm or
process, showing the steps as boxes of various kinds, and their order by
connecting these with arrows.
1 27
Common Flowchart Symbols
Terminator: Shows the starting and ending points of a
program
ReadA
Read B
PrintC Stop
C=A+B
1 31
38
Example 2
Find the difference and the division of two numbers and display
the results.
Variables: Algorithm:
• N1: Firstnumber * Step 1:Start
• N2: Secondnumber * Step 2: InputN1
• D : Difference * Step 3: InputN2
• V : Division * Step 4:D=N1–N2
* Step 5: V=N1/N2
* Step 6: OutputD
* Step 7: OutputV
* Step 8:Stop
1 32
Flowchart
Start
Read N1
Read N2
D=N1-N2
1 33
40
Example 3
A: Coefficient of X2
B: Coefficient of X
C: Constant term
delta: Discriminant of theequation
X1: First root of theequation
X2: Second root of theequation
1 34
41
Algorithm:
Step 1: Start
Step 2: Input A, B and C
Step 3: Calculate delta = B2 – 4AC
Step 4: If delta<0 go to step 6, otherwise go to 5
Step 5: If delta>0 go to step 7, otherwise go to 8
Step 6:Output ―Complex roots . Go to step 13
Step 7: Output ―real roots . Go to step 9
Step 8:Output ―eƋual ƌoots . Go to step 9
Step 9: Calculate X1=(-b+√delta)/(2*A)
Step 10: Calculate X2=(-b-√delta)/(2*A)
1 35
Flowchart
Start Read Delta=B*B- 4*A*C
A,B,C
No
Yes Delta < 0
Yes
“Complex Roots” Delta>0
No
“Equal Roots”
“Real Roots”
X1=(-b+√delta)/(2*A)
X2=(-b-√delta)/(2*A)
1 38
Structure Of C Program
1 39
Preprocessor directives:
1 40
Global Declaration Section:
Contains declarations that are visible to all parts of the program
Declaration section :
It is at the beginning of the function. It describes the data that will be
used in the function. Declarations in a function are known as local
declarations as they are visible only to the function that contains
them.
1 41
Statements:
Statements follows the declaration section.It the contains instructions
to the computer. Every statement ends with a semicolon.
Comments:
1. Comment about the program should be enclosed within /**/.
2. Any number of comments can be written at any place in the
program.
3. Comments in the code helps to understand the code
4. Comments cannot be nested.
1 42
main( ):
The executable part of the program begins with the function always.
All statements that belong to main are enclosed in a pair of braces {
}.
First C Program
#include <stdio.h>
void main ()
{
Printf(“Hello World!”);
}
1 43
Process of compiling and running C
program
1 44
Writing and Editing Programs
1 45
Compiling Programs
1 46
Linking Programs
Linker program combines the Object File with the required library
functions to produce another file called ― executable file. Object file
will be the input to the linker program.
1 47
Executing Programs:
Loader program loads the executable file from disk into the
memory and directs the CPU to start execution.
The CPU will start execution of the program that is loaded into the
memory .
1 48
Building a C Program
1 49
C tokens
C tokens are the basic buildings blocks in C language which are
constructed together to write a C program.
Each and every smallest individual unit in a C program is known as
C tokens. C tokens are of six types. They are
1 50
C Keywords
1 51
auto Typedef
continue While
enum case
if do
short float
switch long
volatile sizeof
break union
default char
extern double
int for
Signed register
const static
else Unsigned
Goto return
void struct
1 52
C Identifiers
1 53
They must consist of only letters, digits, orunderscore.
No other special character is allowed.
1 54
C Constants
Integer Constants
Integer constants are whole numbers without any fractional part.
It must have at least one digit and may contain either + or – sign. A
number with no sign is assumed to be positive.
There are three types of integer constants:
1 55
Decimal Integer Constants
1 57
Real Constants
1 58
Representing a real constant in exponent form
1 59
Character Constants
1 60
Escape Characters/ Escape Sequences
C allows us to have certain non graphic characters in character
constants.
1 61
String Constants
String constants are sequence of characters enclosed within double
quotes. For example,
―hello|
―abc|
―hello911|
1 62
Special Symbols
The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose.
*+ ;() ,- , ; : * … = #
Braces{}: These opening and ending curly braces marks the start
and end of a block of code containing more than one executable
statement.
Parentheses(): These special symbols are used to indicate function
calls and function parameters.
Brackets[]: Opening and closing brackets are used as array element
reference. These indicate single and multidimensional subscripts.
1 63
Variables
A variable is nothing but a name given to a storage area that our
programs can manipulate.
Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be
stored within that memory; and the set of operations that can be
applied to the variable.
1 64
Type Description
1 65
Data types
Data types specify how we enter data into our programs and
what type of data we enter.
1 66
C language supports 2 different type of data types:
Derived data types are nothing but primary data types but a little
twisted or grouped together like array, structure, union and pointer.
These are discussed in details later.
1 67
1 68
Integer type
Integers are used to store whole numbers.
1 69
Floating point type
Floating types are used to store real numbers.
double 8 1.7E-308 to
1.7E+308
long double 10 3.4E-4932 to
1.1E+4932
1 70
Character type
Character types are used to store characters value.
1 71
void type
1 72
Operators
C language offers many types of operators. Theyare,
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternaryoperators)
7. Increment/decrementoperators
8. Special operators
1 73
Arithmetic Operators
C Arithmetic operators are used to perform mathematical
calculations like addition, subtraction, multiplication, division and
modulus in C programs.
S.no Arithmetic Operation Example
Operators
1 + Addition A+B
2 – Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
1 74
Assignment operators
The following table lists the assignment operators supported by
the C language −
Operator Description
= Simple assignment operator. Assigns values from right side
operands to left side operand
+= Add AND assignment operator. It adds the right operand to
the left operand and assign the result to the left operand.
-= Subtract AND assignment operator. It subtracts the right
operand from the left operand and assigns the result to the
left operand.
*= Multiply AND assignment operator. It multiplies the right
operand with the left operand and assigns the result to the
left operand.
<<= Left shift AND assignment operator.
>>= Right shift AND assignment operator.
1 75
Relational operators
The following table shows all the relational operators supported by
C language. Assume variable A holds 10 and variable B holds 20
then −
Operator Description
== Checks if the values of two operands are equal or not. If yes,
then the condition becomes true.
!= Checks if the values of two operands are equal or not. If the
values are not equal, then the condition becomes true.
> Checks if the value of left operand is greater than the value of
right operand. If yes, then the condition becomes true.
< Checks if the value of left operand is less than the value of right
operand. If yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal to the
value of right operand. If yes, then the condition becomes true.
<= Checks if the value of left operand is less than or equal to the
value of right operand. If yes, then the condition becomes true.
1 76
Logical operators
Operator Description
&& Called Logical AND operator. If both the operands are non-zero,
then the condition becomes true.
|| Called Logical OR Operator. If any of the two operands is non-
zero, then the condition becomes true.
! Called Logical NOT Operator. It is used to reverse the logical state
of its operand. If a condition is true, then Logical NOT operator
will make it false.
1 77
Bit wise operators
1 78
Conditional operators
(ternary operators)
Conditional operators return one value if condition is true and
returns another value is condition is false.
Syntax : (Condition?true_value:false_value)
1 79
Increment/decrement operators
Syntax:
1 80
Special operators
1 81
Expressions
Arithmetic expression in C is a combination of variables, constants
and operators written in a proper syntax.
1 82
C Operator Precedence And
Associativity
C operators in order of precedence (highest to lowest).
1 83
MODULE – II
CONTROL STRUCTURES
1 84
CLOs Course Learning Outcome
CLO7 Understand branching statements, loop statements and use them in
problem solving.
CLO8 Learn homogenous derived data types and use them to solve
statistical problems.
CLO9 Learn homogenous derived data types and use them to solve
statistical problems.
1 85
CLOs Course Learning Outcome
CLO11 Understand how recursion works and write programs using recursion
to solve problems.
1 86
Running Course Outcomes
1 87
Decision Statements - if Statement
Syntax of if statement:
The statements inside the body of “if” only execute if the given
condition returns true. If the condition returns false then the
statements inside “if” are skipped
if (condition)
{
//Block of C statements here
//These statements will only execute if the condition is true
}
1 88
Flow Diagram of if statement
1 89
Example of if statement
#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}
1 90
If else statement
if(condition) {
// Statements inside body of if
}
else {
//Statements inside body of else
}
1 91
If condition returns true then the statements inside the body of “if”
are executed and the statements inside body of “else” are skipped.
If condition returns false then the statements inside the body of “if”
are skipped and the statements in “else” are executed.
1 92
Flow diagram of if else statement
1 93
Program for checking eligible
for#include
voting or not
<stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
printf("You are eligible for voting");
else
printf("You are not eligible for voting");
return 0;
}
1 94
Nested If..else statement
Syntax of Nested if else statement:
if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
1 95
Example of nested if..else
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 != var2)
{
printf("var1 is not equal to var2\n");
//Nested if else
1 96
if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}}
else
{
printf("var1 is equal to var2\n");
}
return 0;
1 97
}
else..if statement
Syntax of else..if statement:
if (condition1)
{
//These statements would execute if the condition1 is true
}
else if(condition2)
{
//These statements would execute if the condition2 is true
}
.
.
else
{//These statements would execute if all the conditions returnfalse.}
1 98
Example of else..if statement
1 100
Switch statement
Syntax
1 101
switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
1 102
The following rules apply to a switch statement −
You can have any number of case statements within a switch. Each
case is followed by the value to be compared to and a colon.
1 103
When the variable being switched on is equal to a case, the
statements following that case will execute until a break statement is
reached.
When a break statement is reached, the switch terminates, and the
flow of control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow
of control will fall through to subsequent cases until a break is
reached.
A switch statement can have an optional default case, which must
appear at the end of the switch.
1 104
Flow Diagram of switch
1 105
Example
#include <stdio.h>
int main () {
/* local variable definition */
char grade = 'B'; switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
1 106
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
} 1 107
Loop control statements - While loop
Syntax
while(condition) {
statement(s);
}
1 108
Here, statement(s) may be a single statement or a block of
statements. The condition may be any expression, and true is any
nonzero value. The loop iterates while the condition is true.
Here, the key point to note is that a while loop might not execute at
all. When the condition is tested and the result is false, the loop
body will be skipped and the first statement after the while loop will
be executed.
1 109
Flow Diagram
1 110
Example
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}
return 0;
}
1 111
Do-while loop
A do while loop is similar to while loop with one exception that it
executes the statements inside the body of do-while before checking
the condition.
On the other hand in the while loop, first the condition is checked and
then the statements in while loop are executed.
So you can say that if a condition is false at the first place then the do
while would run once, however the while loop would not run at all.
1 112
Syntax of do-while loop
do
{
//Statements
}while(condition test);
1 113
Flow diagram of do while loop
1 114
Example of do while loop
#include <stdio.h>
int main()
{
int j=0;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}while (j<=3);
return 0;
}
1 115
For loop
1 116
Syntax:
1 117
Steps are repeated till exit condition comes.
1 118
1 119
Example: for loop
#include <stdio.h>
int main() {
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0; }
1 120
Jump statements-break
1 121
Break in While Loop :
initialization ;
while(condition)
{
Statement1;
Statement2;
incrementation
break;
1 122
Example
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15) {
/* terminate the loop using break statement */ break;
} } return 0; }
1 123
Continue statement
For the for loop, continue statement causes the conditional test
and increment portions of the loop to execute.
1 124
Example
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
do { if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
} printf("value of a: %d\n", a);
a++;
} while( a < 20 ); return 0; }
1 125
Goto statement
1 126
Example
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:
do { if( a == 15) {
/* skip the iteration */
a = a + 1;
goto LOOP;
} printf("value of a: %d\n", a); a++;
}while( a < 20 ); return 0; }
1 127
MODULE – III
ARRAYS AND FUNCTIONS
1 128
Running Course Learning Outcomes
1 129
Array
1 130
TYPES OF C ARRAYS:
1 131
Array declaration, initialization and
accessing
Array declaration syntax:
data_type arr_name [arr_size];
Array initialization
data_type arr_name *arr_size+=(value1, value2,value3,….);
1 132
ONE DIMENSIONAL ARRAY
1 133
Character array example:
char str[10];
char str*10+=,‘H’,‘a’,‘i’-;
str[0]; /*H is accessed*/
str[1]; /*a is accessed*/
str[2]; /*i is accessed*/
1 134
Example Program For One Dimensional
Array In C:
#include<stdio.h>
int main()
{
int i;
int arr[5] = {10,20,30,40,50};
// declaring and Initializing array in C
//To initialize all array elements to 0, use int arr[5]={0};
/* Above array can be initialized as below also
arr[0] = 10; to
arr[4] = 50; */
for (i=0;i<5;i++)
{// Accessing each variableprintf("value of arr[%d] is %d \n", i, arr[i]);}
}
1 135
Two dimensional array
1 136
Declaration of two dimensional Array in C
data_type array_name[size1][size2];
1 137
Two dimensional array example in C
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
1 138
Strings
For example:
“String”
1 139
Example
#include<stdio.h>
#include<conio.h>
#include<string.h> void main ()
{
char str1[20]; char str2[20];
printf(“Enter First Name”); scanf(“%s”
,&str1); printf(“Enter last Name” );
scanf(“%s” ,&str2); puts(str1);
puts(str2);
}
1 140
String Handling Functions in C
These String functions are:
1. strlen().
2. strupr().
3. strlwr().
4. strcmp().
5. strcat().
6. strcpy().
7. strrev().
1 141
strlen()
The function takes a single argument, i.e, the string variable whose
length is to be found, and returns the length of the string passed.
1 142
Program finding length of a string
#include <stdio.h> #include
<string.h> int main()
{
char a*20+=”Program”
char b*20+=,‘P’,’r’,’o’,’g’,’r’,’a’,’m’,’\0’-;
char c[20];
printf(“Enter string: “); gets(c);
printf(“Length of string a = %d \n”, strlen(a)); printf(“Length
of string b = %d \n”, strlen(b)); printf(“Length of string c =
%d \n”, strlen(c));
return 0;}
1 143
strupr()
strupr() function convertsa given string into uppercase. Syntax
for strupr( ) function is given below.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "Modify This String To Upper";
printf("%s\n",strupr(str));
return 0;
}
Output: MODIFY THIS STRING TO UPPER
1 144
strlwr()
strlwr( ) function converts a given string into lowercase. Syntax for
strlwr( ) function is given below.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%s\n",strlwr (str));
return 0;
}
1 146
strcat()
strcat( ) function in C language concatenates two given strings. It
concatenates source string at the end of destination string.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " fresh2refresh" ;
char target[ ]= " C tutorial" ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ;
strcat ( target, source ) ;
printf ( "\nTarget string after strcat( ) = %s", target ) ;}
1 147
strcpy()
strcpy( ) function copies contents of one string into another string
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strcpy ( target, source ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
return 0;
}
1 148
strrev()
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = "Hello";
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
return 0;
}
1 149
Arrays of strings
A string is a 1-D array of characters, so an array of strings is a 2-D
array of characters.
Just like we can create a 2-D array of int, float etc; we can also
create a 2-D array of character or array of strings.
char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};
1 150
It is important to end each 1-D array by the null character
otherwise, it's just an array of characters. We can't use them as
strings.
1 151
The following program demonstrates how to
print an array of strings.
#include<stdio.h>
int main()
{
int i;
char ch_arr[3][10] = {"spike","tom","jerry"};
printf("1st way \n\n");
for(i = 0; i < 3; i++)
{
printf("string = %s \t address = %u\n", ch_arr + i, ch_arr + i);
}
signal to operating system program ran fine return 0;
}
1 152
Introduction to functions
You can divide up your code into separate functions. How you divide
up your code among different functions is up to you, but logically the
division is such that each function performs a specific task.
1 153
The C standard library provides numerous built-in functions that your
program can call. For example, strcat() to concatenate two strings,
memcpy() to copy one memory location to another location, and
many more functions.
Defining a Function
1 154
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of a function header
and a function body. Here are all the parts of a function−
1 155
Function Name − This is the actual name of the function. The
function name and the parameter list together constitute the function
signature.
1 156
Example
Given below is the source code for a function called max(). This
function takes two parameters num1 and num2 and returns the
maximum value between the two −
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
} 1 157
Function Declarations
• A function declaration tells the compiler about a function name and
how to call the function. The actual body of the function can be
defined separately.
• A function declaration has the following parts −
return_type function_name( parameter list );
• For the above defined function max(), the function declaration is as
follows −
int max(int num1, int num2);
• Parameter names are not important in function declaration only
their type is required, so the following is also a valid declaration−
int max(int, int);
1 158
Function prototype
• A function prototype is simply the declaration of a function that
specifies function's name, parameters and return type. It doesn't
contain function body.
• A function prototype gives information to the compiler that the
function may later be used in the program.
returnType functionName(type1 argument1, type2 argument2,...);
• In the above example, int addNumbers(int a, int b); is the function
prototype which provides following information to the compiler:
1 159
Category of functions:
1 160
• Function with no return values, no arguments
• In this category, the function has no arguments. It does not receive
any data from the calling function. Similarly, it doesn’t return any
value. The calling function doesn’t receive any data from the called
function. So, there is no communication between calling and called
functions.
1 161
• Functions with arguments and return values
• In this category, functions has some arguments and it receives data
from the calling function. Simillarly, it returns a value to the calling
function. The calling function receives data from the called function.
So, it is two-way data communication between calling and called
functions.
1 162
Inter Function communication
1 163
• In C, the inter function communication is classified asfollows...
Downward Communication
Upward Communication
Bi-directional Communication
1 164
• Downward Communication
1 165
Example Program for swapping
using function
#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2);
addition(num1, num2) ; // calling function
getch() ;
}
void addition(int a, int b) // called function
{printf("SUM = %d", a+b) ;}
1 166
Upward Communication
1 167
Example Program on
Upward Communication
#include <stdio.h>
void main(){
int result ;
int addition() ; // function declaration
result = addition() ; // calling function printf("SUM = %d",
result) ;
getch() ;
}
int addition() // called function
{
int num1, num2 ;
num1 = 10;num2 = 20;
return (num1+num2) ;}
1 168
Bi-Directional Communication
• The function with parameters and with return value are considered
under Bi-Directional communication.
1 169
Example Program on
Bidirectional Communication
#include <stdio.h>
void main(){
int num1, num2, result ;
int addition(int, int) ; // function declaration
num1 = 10 ;
num2 = 20 ;
result = addition(num1, num2) ; // calling function
printf("SUM = %d", result) ;
getch() ;
}
int addition(int a, int b) // called function
{
return (a+b) ;
}
1 170
Function Calls
There are two ways that a C function can be called from a program.
They are,
1. Call by value
2. Call by reference
Note:
• Actual parameter – This is the argument which is used infunction
call.
• Formal parameter – This is the argument which is used in function
definition
1 171
Call by Value
The changes made on the formal parameters does not effect the
values of actual parameters. That means, after the execution control
comes back to the calling function, the actual parameter values
remains same.
1 172
Example Program on
Call by value
#include <stdio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration num1 = 10;
num2 = 20 ;
1 174
Example Program on
Call by Reference
#include <stdio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration num1 = 10;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2);
swap(&num1, &num2) ; // calling function
1 175
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
1 176
Parameter Passing Mechanism
In C Programming we have different ways of parameter
passing schemes such as Call by Value and Call by Reference.
1 177
Example Program on
Parameter passing
#include<stdio.h>
void interchange(int number1,int number2)
{
int temp;
temp = number1;
number1 = number2;
number2 = temp;}
int main() {
int num1=50,num2=70; interchange(num1,num2);
printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
return(0);
}
1 178
Output :
Number 1 :50
Number 2 :70
Any update made inside method will not affect the original value of
variable in callingfunction.
In the above example num1 and num2 are the original values and xerox
copy of these values is passed to the function and these values are copied
into number1,number2 variable of sum functionrespectively.
1 179
1 180
A. Call by Reference/Pointer/Address :
#include<stdio.h>
void interchange(int *num1,int *num2)
{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
int main() {
int num1=50,num2=70;
interchange(&num1,&num2);
printf("\nNumber 1 : %d",num1); printf("\nNumber 2 : %d",num2);
return(0);
}
1 181
Output :
Number 1 :70
Number 2 :50
Any updates made inside the called function will modify the original copy
since we are directly modifying the content of the exact memory location
1 182
1 183
Recursion
• Recursion is the process of repeating items in a self-similarway.
• In programming languages, if a program allows you to call a function
inside the same function, then it is called a recursive call of the
function.
void recursion()
{
recursion();/* function calls itself */
}
int main()
{
recursion();
}
1 184
• The C programming language supports recursion, i.e., a function to
call itself.
1 185
Example: Factorial
#include <stdio.h>
unsigned long long int factorial(unsigned int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
1 186
Passing arrays to function
• Whenever we need to pass a list of elements as argument to any
function in C language, it is prefered to do so using an array.
1 187
Returning an Array from a function
1 188
Passing a single array element to a
function
#include<stdio.h>
void giveMeArray(int a);
int main()
{
int myArray[] = { 2, 3, 4 };
giveMeArray(myArray[2]);
return 0;
}
void giveMeArray(int a)
{
printf("%d", a);
}
Output: 4
1 189
Passing a single array element
to function (Call by value)
#include <stdio.h>
void disp( charch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
disp (arr[x]);
}
return 0;
}
OUTPUT: a b c d e f g h i j
1 190
Passing array to function using call
byreference
#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
disp(&arr[i]);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9,0};
for (int i=0; i<10; i++)return0;
}
OUTPUT:
1234567890
1 191
Passing String to a Function
• Function declaration to accept one dimensional string
We know that strings are saved in arrays so, to pass an one
dimensional array to a function we will have the following
declaration.
returnType functionName(char str[]);
• Example:
1 192
Passing one dimensional string to a function
1 193
Example Program on
Passing one dimensional array
#include <stdio.h>
void displayString(char []); int main(void)
{
// variables
char message[] = "Hello World";
// print the string message
displayString(message); return 0;
}
void displayString(char str[])
{
printf("String: %s\n", str);
}
1 194
Storage Classes
1 195
Scope Region or Part of Program in which
Variable is accessible
Extent Period of time during which memory is
associated with variable
Storage Class Manner in which memory is allocated by
the Compiler for Variable DifferentStorage
Classes
1 196
Storage class of variable Determines following things
1 197
Where the variable is stored:
Variables declared with auto storage classes are declared inside main
memory whereas variables declared with keyword register are stored
inside the CPU Register.
1 198
Scope of Variable
Variable may have Block Scope, Local Scope and External Scope.
1 199
Default Initial Value of the Variable
1 200
Lifetime of variable
1 201
Different Storage Classes:
Static storageclass
Extern storageclass
Register storageclass
1 202
Automatic (Auto) storage class
This is default storage class
All variables declared are of type Auto by default
In order to Explicit declaration of variable use ‗auto‘ keyword auto
int num1 ; // Explicit Declaration
Storage : Memory
Scope : Local / BlockScope
Life time : Exists as long as Control remains in the block
Default initial Value : Garbage
1 203
External ( extern ) storage class
1 204
Storage : Memory
Scope : Global / File Scope
Life time : Exists as long as variable is running Retains value within the
function
Default initial Value : Zero
1 205
Static Storage Class
The static storage class instructs the compiler to keep a local variable
in existence during the life-time of the program instead of creating and
destroying it each time it comes into and goes out of scope.
Syntax
{
register int count;
}
1 207
Preprocessor directives
1 208
Preprocessing directives are lines in your program that start with #.
The # is followed by an identifier that is the directive name. For
example, #define is the directive that defines a macro. Whitespace is
also allowed before and after the #.
The # and the directive name cannot come from a macro expansion.
For example, if foo is defined as a macro expanding to define, that
does not make #foo a valid preprocessing directive.
1 209
List of preprocessor directives:
1. #include
2. #define
3. #undef
4. #ifdef
5. #ifndef
6. #if
7. #else
8. #elif
9. #endif
10. #error
11. #pragma
1 210
#include
This variant is used for system header files. It searches for a file
named file in a list of directories specified by you, then in a standard
list of system directories.
#include "file"
1 211
Macro's (#define)
Syntax
#define token value
1 212
#undef
#undef token
#include <stdio.h>
#define PI 3.1415
#undef PI
main() { printf("%f",PI);
}
1 213
#ifdef
Syntax:
#ifdef MACRO
//code
#endif
1 214
#ifndef
Syntax:
#ifndef MACRO
//code
#endif
1 215
#if
Syntax:
#if expression
//code
#endif
1 216
#else
Syntax:
#if expression
//if code
#else
//else code
#endif
1 217
Syntax with #elif
#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif
1 218
#error
The #error preprocessor directive indicates error. The compiler
gives fatal error if #error directive is found and skips further
compilation process.
C #error example
#include<stdio.h>
#ifndef MATH_H
#error First include then compile
#else
void main()
{ float a; a=sqrt(7); printf("%f",a);
}
#endif
1 219
#pragma
1 220
Syntax:
#pragma token
Example:
#include<stdio.h>
#include<conio.h>
void func() ;
#pragma startup func
#pragma exit func
1 221
Example Program on pragma
void main()
{
printf("\nI am in main");
getch();
}
void func()
{
printf("\nI am in func");
getch();
}
1 222
MODULE – IV
STRUCTURES, UNIONS AND
POINTERS
1 223
CLOs COURSE LEARNING OUTCOMES
CLO 14 Understand pointers conceptually and apply them in C programs.
CLO 15 Distinguish homogenous and heterogeneous data types and apply
them in solving data processing applications.
1 224
Need of Structures
• For example: You want to store some information about a person:
his/her name, citizenship number and salary. You can easily create
different variables name, citNo, salary to store these information
separately.
• However, in the future, you would want to store information about
multiple persons. Now, you'd need to create different variables for
each information per person: name1, citNo1, salary1, name2,
citNo2, salary2
• You can easily visualize how big and messy the code would look. Also,
since no relation between the variables (information) would exist, it's
going to be a daunting task.
1 225
• A better approach will be to have a collection of all related
information under a single name Person, and use it for every person.
• Now, the code looks much cleaner, readable and efficient as well.
1 226
Structure Basics
Structure Definition
1 227
Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};
1 228
struct person
{
char name[50];
int citNo;
float salary;
};
This declaration above creates the derived data type struct person.
1 229
Structure variable declaration
struct person
{
char name[50];
int citNo;
float salary;
};
1 230
Example Program
int main()
{
struct person person1, person2, person3[20];
return 0;
}
Another way of creating a structure variable is:
struct person
{
char name[50];
int citNo;
float salary;
} person1, person2, person3[20];
In both cases, two variables person1, person2 and an
array person3 having 20 elements of type struct person are created.
1 231
Accessing members of a structure
#include <stdio.h>
struct Distance
{ int feet;
float inch;
} dist1, dist2, sum;
int main()
{
printf("1st distance\n");
// Input of feet for structure variable dist1
1 233
Example Program on structure
printf("Enter feet: ");
scanf("%d", &dist1.feet);
// Input of inch for structure variable dist1
printf("Enter inch: ");
scanf("%f", &dist1.inch);
printf("2nd distance\n");
// Input of feet for structure variable dist2
printf("Enter feet: ");
scanf("%d", &dist2.feet);
// Input of feet for structure variabledist2
printf("Enter inch: ");
1 234
scanf("%f", &dist2.inch);
sum.feet = dist1.feet + dist2.feet;
sum.inch = dist1.inch +dist2.inch;
if (sum.inch > 12)
{
//If inch is greater than 12, changing it to feet.
• ++sum.feet;
sum.inch = sum.inch - 12;
} // printing sum of distance dist1 and dist2
printf("Sum of distances = %d\'-%.1f\"", sum.feet, sum.inch);
return 0;
}
1 235
Output
1st distance
Enter feet: 12
Enter inch: 7.92
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances = 15'-5.7"
1 236
Structure Initialization
1 237
Way1: Declare and Initialize
struct student
{
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3};
1 238
In the above code snippet, we have seen that structure is declared
and as soon as after declaration we have initialized the structure
variable.
std1 = { "Pritesh",67,78.3}
1 239
Way2: Declaring and Initializing
MultipleVariables
struct student
{
char name[20];
int roll; std1 = {"Pritesh",67,78.3};
float marks; std2 = {"Don",62,71.3};
}
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
In this example, we have declared two structure variables in above
code. After declaration of variable we have initialized two variable.
1 240
Way3: Initializing single member
struct student
{
int mark1; int
mark2; int
mark3;
} sub1={67};
1 241
• Though there are three members of structure,only one is initialized.
• Then remaining two members are initialized withZero.
• If there are variables of other data type then their initial values will
be
integer 0
float 0.00
char NULL
1 242
Way4: Initializing inside main
struct student
{
int mark1; int mark2;
int mark3;
};
void main()
{
Struct student s1={89,54,65};
- - - --
When we declare a structure then
- - - -- memory won’t be allocated for the
- - - -- structure. i.e only writing below
}; declaration statement will never allocate
memory
1 243
struct student
{
int mark1; int mark2; int mark3;
};
1 244
Accessing Structure Members
1 245
Example Program
#include<stdio.h>
struct stud
{
char name[20];
char fname[10];
};
struct stud s;
main()
{
scanf("%s%s",&s.name,&s.fname);
printf("%s%s",s.name,s.fname);
}
Output:vedha srinivas Vedhasrinivas
1 246
struct employee
{
char name[100]; int age;
float salary;
char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};
int age = employee_one.age;
float salary= employee_one.salary;
char department= employee_one.department;
1 247
Accessing array of structure elements
STRUCT STUD
{
Datatype member1; Datatype member2;
.
.
} struct stud s[50];
1 248
Nested Structures
1 249
Example Program
structure tagname_1
{
member1; member2; member3;...
Member n; structure tagname_2
{
member_1; member_2; member_3;...
member_n;
}, var1
} var2;
1 250
• To access the members of the inner structure, we write a variable
name of the outer structure, followed by a dot(.) operator, followed
by the variable of the inner structure, followed by a dot(.) operator,
which is then followed by the name of the member we want to
access.
1 251
Example
struct student
{
struct person
{
char name[20];
int age;
char dob[10];
}p;
int rollno;
float marks;
} stu;
1 252
• It is important to note that structure person doesn't exist on its own.
We can't declare structure variable of type struct person anywhere
else in the program.
• Instead of defining the structure inside another structure. We could
have defined it outside and then declare it's variable inside the
structure where we want to use it. For example:
struct person
{
char name[20];
int age;
char dob[10];
};
1 253
• We can use this structure as a part of a bigger structure.
struct student
{
struct person info;
int rollno;
float marks;
}
1 254
Initializing nested Structures
1 255
The following program demonstrates how we can use nested
structures
#include<stdio.h>
struct person
{
char name[20]; int age; char dob[10];};
struct student
{
struct person info; int roll_no; float marks;
};
int main()
{
struct student s1;printf("Details of student: \n\n");
1 256
printf("Enter name: "); scanf("%s", s1.info.name);
printf("Enter age: "); scanf("%d", &s1.info.age);
printf("Enter dob: "); scanf("%s", s1.info.dob);
printf("Enter roll no: "); scanf("%d", &s1.roll_no);
printf("Enter marks: "); scanf("%f", &s1.marks);
printf("\n*******************************\n\n");
printf("Name: %s\n", s1.info.name);
printf("Age: %d\n", s1.info.age);
printf("DOB: %s\n", s1.info.dob);
printf("Roll no:
%d\n", s1.roll_no);
printf("Marks: %.2f\n", s1.marks);
// signal to operating system program ran fine return 0;
1 257
}
Array of structures:
Need of array of structures:
1 258
Syntax:
Struct struct-name
{
datatype var1;
datatype var2;
--------------------
--------------------
datatype varN
};
Struct struct-name obj[size]
1 259
Initializing Array of Structure:
Alternative 1:
struct Book
{
char bname[20];
int pages;
char author[20];
float price;
} b1[3] = {
{"Let us C",700,"YPK",300.00},
{"Wings of Fire",500,"APJ Abdul Kalam",350.00},
{"Complete C",1200,"Herbt Schildt",450.00}
};
1 260
Initializing Array of Structure:
Alternative 2:
struct Book
{
char bname[20];
int pages;
char author[20];
float price;
};
void main()
{
struct Book b1[3] = {{"Let usC",700,"YPK",300.00},
{"Wings of Fire",500,"Abdul Kalam",350.00},
{"Complete C",1200,"Herbt Schildt",450.00}
};
}
1 261
Important Points:
Note 1: All Structure Members need not be initialized
#include<stdio.h>
struct Book
{
char bname[20];
int pages;
char author[20];
float price;
}b1[3] = {
{"Book1",700,"YPK"},
{"Book2",500,"AAK",350.00},
{"Book3",120,"HST",450.00}}}
1 262
struct Book
{
void main() char bname[20];
{ int pages;
char author[20];
printf("\nBook Name : %s",b1[0].bname); float price;
printf("\nBook Pages : %d",b1[0].pages); }b1[3] =
printf("\nBook Author : %s",b1[0].author); {
{},
printf("\nBook Price : %f",b1[0].price); {"Book2",500,"AAK",350.00},
{"Book3",120,"HST",450.00}
};
1 263
Output
• Book Name :
• Book Pages : 0 Book Author
• Book Price : 0.000000
It is clear from above output , Default values for different data types.
1 264
Structures and functions
1 265
Passing structure by value
1 266
Passing structure by reference
1 267
Structures and pointers
Structures can be created and accessed using pointers. A pointer
variable of a structure can be created as below:
struct name {
member1;
member2;
.
.
};
int main()
{
struct name *ptr;
}
Here, the pointer variable of type struct name is created.
1 268
Accessing structure's member through pointer
1 269
1. Referencing pointer to another address to access the memory
Consider an example to access structure's member through pointer.
#include <stdio.h>
typedef struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1; // Referencing pointer to memory address of
person1
printf("Enter integer: ");
scanf("%d",&(*personPtr).age);
1 270
printf("Enter number: ");
scanf("%f",&(*personPtr).weight);
printf("Displaying: ");
printf("%d%f",(*personPtr).age,(*personPtr).weight);
return 0;
}
In this example, the pointer variable of type struct person is
referenced to the address of person1. Then, only the structure
member through pointer can can accessed.
1 272
Example
Example to use structure's member through pointer using
malloc() function.
#include <stdio.h>
#include <stdlib.h>
struct person {
int age;
float weight;
char name[30];
};
int main()
{
struct person *ptr;
1 273
int i, num;
1 274
printf("Displaying Infromation:\n");
for(i = 0; i < num; ++i)
printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)-
>weight);
return 0;
}
1 275
Output
Enter number of persons:2
Enter name, age and weight of the person respectively:
Adam
2
3.2
Enter name, age and weight of the personrespectively:
Eve
6
2.3
Displaying Information:
Adam
Eve 6
1 276
Structure and Functions
• In C, structure can be passed to functions by two methods:
1 277
Example 1
1 278
Example Contd
int main()
{
struct student stud;
printf("Enter student's name: ");
scanf("%s", &stud.name);
printf("Enter roll number:");
scanf("%d", &stud.roll);
display(stud); // passing structure variable stud as argument
return 0;
}
void display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
} 1 279
Example Contd
Enter student's name: Kevin Amla
Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149
Passing structure by reference
The memory address of a structure variable is passed to function
while passing it by reference.
If structure is passed by reference, changes made to the structure
variable inside function definition reflects in the originally passed
structure variable.
1 280
Self Referencial Structures
struct demo
{
Data_type member1, member2;
struct demo *ptr1,*ptr2;
}
1 281
Unions
1 282
•A union can also be viewed as a variable type that can contain many
different variables (like a structure), but only actually holds one of
them at a time (not like a structure).
•This can save memory if you have a group of data where only one
of the types is used at a time.
1 283
Union Declaration
union union-type-name
{
type variable-names;
type variable-names;
…
... }[union variable];
1 284
Union Intialization
union student
{
char name[20];
int marks;
- union student s=,“surya”,560-;
1 285
1 286
1 287
1 288
Bit Fields
• Bit field
– Member of a structure whose size (in bits) has been specified
– Enable better memory utilization
– Must be defined as int or unsigned
– Cannot access individualbits
• Defining bit fields
– Follow unsigned or int member with a colon (:) and aninteger
constant representing the width of the field
– Example:
– struct BitCard {
– unsigned face : 4;
– unsigned suit : 2;
– unsigned color : 1;
– };
1
1 289
• Unnamed bit field
– Field used as padding in the structure
– Nothing may be stored in thebits
– struct Example {
– unsigned a : 13;
– unsigned : 3;
– unsigned b : 4;
–}
– Unnamed bit field with zero width aligns next bit field to anew
storage unit boundary
2
1 290
Example
For example, consider the following declaration of date withoutuse of
bit fields.
#include <stdio.h>
// A simple representation of date
struct date
{
unsigned int d;
unsigned int m;
unsigned int y;
};
int main()
{
1 291
printf("Size of date is %d bytes\n", sizeof(structdate));
Output:
Size of date is 12 bytes
Date is 31/12/2014
1 292
typedef and enumerators
typedef:
Syntax:
typedef data_type new_name;
• typedef: It is a keyword.
• data_type: It is the name of any existing type or user defined type
created using structure/union.
• new_name: alias or new name you want to give to anyexistingtype
or user defined type.
1 293
Example for typedef:
1 294
Example program on typedef
strcpy( book.title, "C
#include <stdio.h> Programming"); strcpy(
#include <string.h> book.author, "Nuha Ali"); strcpy(
typedef struct Books { book.subject, "C
char title[50]; char Programming Tutorial");
author[50]; char
book.book_id = 6495407; printf(
subject[100]; int
"Book title : %s\n",
book_id; book.title);
} Book; printf( "Book author : %s\n",
int main( ) book.author);
{ printf( "Book subject : %s\n",
Book book; book.subject);
printf( "Book book_id : %d\n",
book.book_id);return 0;
}
1 295
Structures with typedef:
• structstudent
{
int mark [2];
char name [10];
float average;
}
Variable for the above structure can be declared intwoways
1st way :
• struct student record; /* for normal variable */
struct student *record; /* for pointer variable*/
2nd way :
• typedef struct studentstatus;
1 296
Struct with typedef:
1 297
Enumeration data type:
• An enumeration is a user-defined data type that consists ofintegral
constants. To define an enumeration, keyword enum is used.
Syntax:
enum flag ,const1, const2,……constN};
enum boolean
{
false;
true;
};
1 299
Example of enumerated type
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday,
friday, saturday};
int main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}
Output 4 day
1 300
Pointer Basics
Pointer Definition and syntax
1 301
Examples of pointer declaration
1 302
Pointer concept with diagrams
• int i;
• int *j;
• j=&i;
1 303
Pointer Basic Example:
#include <stdio.h>
int main()
{
int *ptr, i; i = 11;
/* address of i is assigned to ptr */
ptr = &i;
/* show i's value using ptr variable */
1 305
OUTPUT:
• Address of c: 2686784
• Value of c: 22
• Address of pointer pc:2686784
• Content of pointer pc: 22
• Address of pointer pc:2686784
• Content of pointer pc: 11
• Address of c: 2686784
• Value of c: 2
1 306
Pointer Arithmetic
1 307
• Increment and decrement ++ and --
• Addition and Subtraction + and-
• Comparison <, >, <=, >=, ==, !=
1 309
#include <stdio.h>
#define SIZE 5
int main()
{
int arr[SIZE] = {10, 20, 30, 40, 50};
int *ptr;
int count;
ptr = &arr[0]; // ptr points to arr[0]
count = 0;
printf("Accessing array elements using pointer \n");
1 310
while(count < SIZE)
{
printf("arr[%d] = %d \n", count, *(ptr + count));
count++;
}
return 0;
}
1 311
Pointer comparison
1 312
If you want to check if two pointer points to same location. For
example,
int main()
{
int num = 10;
int *ptr1 = # // ptr1 points to num
int *ptr2 = # // ptr2 also points to num
if(ptr1 == ptr2)
{
// Both pointers points to same memory location
// Do some task
}
return 0;}
1 313
Pointer to pointer
1 314
Syntax:
int **p1;
1 315
• Simple program to represent Pointer to a Pointer
#include <stdio.h>
int main()
{
int a = 10;
int *p1; //this can store the address of variable a
int **p2;
/*
this can store the address of pointer variable p1 only.
It cannot store the address of variable 'a'
*/
p1 = &a;
p2 = &p1;
1 316
printf("Address of a = %u\n", &a);
printf("Address of p1 = %u\n", &p1);
printf("Address of p2 = %u\n\n", &p2);
// below print statement will give the address of 'a'
printf("Value at the address stored by p2 = %u\n", *p2);
printf("Value at the address stored by p1 = %d\n\n", *p1);
printf("Value of **p2 = %d\n", **p2); //read this *(*p2)
/*
This is not allowed, it will give a compile time error-
p2 = &a;
printf("%u", p2);
*/return 0;}
1 317
While dereferencing a void or Generic pointer, the C compiler does
not have any clue about type of value pointed by the void pointer.
1 318
void or Generic pointer
1 319
Here is some code using a void
pointer:
#include <stdio.h>
#include<string.h> intmain()
{
int num[3] = {10,20,30};
char name[30] = "Welcome to C World";
int *pint = NULL;
void *pvoid = NULL; int i;
pint = #
1 320
Example for array of pointer
1 321
Array of Pointers
• When we say memory wastage, it doesn't means that the strings will
start occupying less space, no, characters will take the same space,
but when we define array of characters, a contiguos memory space is
located equal to the maximum size of the array, which is a wastage,
which can be avoided if we use pointers instead
1 322
Advantages
1 323
1 324
Example
1 325
Arrays in C
0x1000 a[0]
1Pointers
Arrays and 327
2
Memory Addresses
1Pointers
Arrays and 328
3
Pointers
int *ptr;
1Pointers
Arrays and 329
4
Pointer Operations in C
Creation
& variable Returns variable’s memory address
Dereference
* pointer Returns contents storedataddress
Indirect assignment
*pointer = val Stores value ataddress
Of course, stillhave...
Assignment
pointer = ptr Stores pointer in anothervariable
1Pointers
Arrays and 330
5
Using Pointers
int i1;
int i2; int *ptr1; int
*ptr2; 0x1000
0x1014 …
i1 = 1;
0x1010 ptr2:
i2 = 2;
0x100C … 0x1000
ptr1 = &i1; ptr2 =
ptr1; 0x1008 ptr1:
*ptr1 = 3; 0x1004 i2: 32
i2 = *ptr2; 0x1000 i1: 31
1Pointers
Arrays and 331
6
Using Pointers (cont.)
int int1 = 1036; /* some data to point to */
int int2 = 8;
*int_ptr1 = int_ptr2;
int1 becomes 8
1Pointers
Arrays and 332
7
Using Pointers (cont.)
int int1 = 1036; /* some data to point to */
int int2 = 8;
int_ptr1 = *int_ptr2;
1Pointers
Arrays and 333
8
Arrays and Pointers
Passing arrays:
Dirty “secret”:
Array name a pointer to the initial (0th) Really int*array
Must explicitly
pass the size
array element
int
foo(int array[],
a[i] *(a +i) unsigned int size)
{
… array*size - 1]…
An array is passed to a function asa }
pointer
int
– The array size is lost!
main(void)
{
Usually bad style to interchange arrays int a[10], b[5];
and pointers … foo(a, 10)… foo(b, 5) …
}
– Avoid pointer arithmetic!
1
Arrays andPointers 334
9
int i; int *p;
int array[10]; int array[10];
1Pointers
Arrays and 335
11
Pointers as function arguments
Pointer preliminaries:
Pointer Definition:
Function basics:
In this case, changes made to the parameter inside the function
have no effect on the argument.
Syntax:
Datatype function_name(datatype variable_name);
1 337
Call by value example:
#include <stdio.h>
void swap(int i, int j)
{
int t; t=i; i=j; j=t;
}
void main()
{
int a,b;
a=5; b=10;
printf("%d %d\n", a, b);
swap(a,b);
printf("%d %d\n", a, b);
}
1 338
Function Parameter passing methods:
Call by reference:
This method copies the address of an argument into the formal
parameter.
1 339
Call by reference Example
1 340
Pointers as function arguments:
1 341
Functions used in Dynamic Memory allocation
malloc()
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
1 342
Example for passing pointer to
function
#include <stdio.h>
void salaryhike(int *var, int b)
{
*var = *var+b;
}
int main()
{
int salary=0, bonus=0;
printf("Enter the employee current salary:");
scanf("%d", &salary);
printf("Enter bonus:");
scanf("%d", &bonus);
salaryhike(&salary, bonus);
printf("Final salary: %d", salary);
return 0;
} 1 343
Functions of returning pointers
doesn't live outside the function. They have scope only inside the
function.
1 344
Pointer to functions
type (*pointer-name)(parameter);
#include <stdio.h>
1 346
Pointer to functions
the functions are declared inside the calling function, hence they will
live outside the function as well.
1 347
Dynamic memory allocation
1 348
Functions used in Dynamic Memory allocation
calloc()
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
1 349
free()
dellocate the previously allocated space syntax of free()
free(ptr);
realloc()
1 350
MODULE – V
FILE HANDLING AND
BASICALGORITHMS
1 351
CLOs Course Learning Outcome
CLO17 Differentiate text files and binary files and write the
simple C programs using file handling functions.
CLO18 Apply the concepts to solve real-time applications
using the features of C language.
CLO19 Gain knowledge to identify appropriate searching and
sorting techniques by calculating time complexity for
problem solving.
CLO20 Possess the knowledge and skills for employability
and to succeed in national and international level
competitive examinations.
1 352
Files and Streams
File:
1 353
Stream:
1 354
A stream is linked to a file using an open operation. A stream is
disassociated from a file using a close operation.
There are two types of streams: text (used with ASCII characters
some character translation takes place, may not be one-to-one
correspondence between stream and what's in the file) and
binary (used with any type of data, no character translation, one-
to-one between stream and file).
1 355
File I/O Streams in C ProgrammingLanguage
:
1 356
Predefined Streams:
1 357
Standard Input Stream Device:
1 358
Standard Output Stream Device:
1 359
1 360
Difference between Standard Input and Standard Output
Stream Device:
1 361
Some Important Summary
1 362
File Operations
1 363
Working with files
Writing a file
When working with files, you need to declare a pointer of type file.
FILE *fp;
1 364
Opening a file - for creation and edit
fp = fopen("fileopen","mode")
For Example:
fopen("newprogram.txt","w");
1 365
Opening Modes in Standard I/O
For reading and writing to a text file, we use the functions fprintf() and
fscanf().
They are just the file versions of printf() and scanf(). The only difference is
that, fprint and fscanf expects a pointer to the structureFILE.
Syntax:
Ch=fgetc(fp);
1 367
Closing a file
The file that is opened should be closed after work is over we need to
create close the file after reading or writing.
Syntax:
Fclose(fp);
Fcloseall();// for multiple files
1 368
Files
Examples
Turbo C++ - binary file Word 4.0 - binary file lab1.c - text file
1 369
Text Files
All files are coded as long sequences of bits (0s and 1s)
Some files are coded as sequences values
of ASCII character (referred to as text files)
1 370
File Terms
element at a time
1 371
File Pointers
FILE *stream
1 372
fopen Command
Syntax: fopen(“FileName”,”mode”);
• File Name is an appropriate name for a file on the computer youare
working on, example: “C:\My Files\lab.dat”
1 373
fclose Command
Syntax:
fclose(FilePointer)
1 374
Open/Closing File
int main() {
FILE *stream;
if ((stream = fopen(“lab.data”,”r”)
== NULL) {
printf(“Unable to open lab.data\n”);
return(1);
}
/* Read data from lab.data using FILE *
variable stream */
if (fclose(stream) == EOF) , printf(“Error
closing lab.data\n”); return(2);
}
}
1 375
fprintf Command
Syntax:
fprintf( filep, “Format”, ValueList);
• Works similarly to printf, but data sent to file rather than screen
– printf(“Format”,ValueList) is a shorthand for
fprintf(stdout,”Format”,ValueList)
• fprintf returns the number of characters printed or EOF (-1) if an
error occurs
1 376
fscanf Command
Syntax:
• fscanf( filep, “Format”, AddrList);
Works similarly to scanf, but data received from file rather than
keyboard
1 377
fscanf/fprintf Example
FILE *fptr;
ptr = fopen("fileopen","mode")
1 379
In C Programming we can open file in different modes such as reading
mode,writing mode and appending mode depending on purpose of
handling file. Following are the different Opening modes of File :
File opening modes
1 380
File Opening Mode Chart
1 381
Types of file
1 382
Example to Open a File
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("INPUT.txt","r")
fclose(fp);
1 383
Different modes:
Reading Mode
fp = fopen("hello.txt","r");
Writing Mode
fp = fopen("hello.txt","w");
Append Mode
fp = fopen("hello.txt","a");
1 384
Another Example To Open File:
#include<stdio.h>
void main()
{
FILE *fp; char ch;
fp = fopen("INPUT.txt","r"); // Open file in Read mode
while(1)
{
ch = fgetc(fp); // Read a Character
if(ch == EOF ) // Check for End of File break ;
printf("%c",ch);
}
fclose(fp); // Close File after Reading
}
1 385
Ways of Detecting End of File
In Text File :
1 386
Ways of Detecting End of File (Contd..)
In Binary File :
feof function is used to detect the end of file
It can be used in textfile
feof Returns TRUE if end of file is reached
Syntax :
int feof(FILE *fp);
1 388
File i/o functions
FILE *fptr;
1 389
fopen() :
create a new file or open a existing file
fclose() :
function is used to close an already opened file.
1 390
getc() and putc() are the simplest functions which can be used to
read and write individual characters to a file.
fscanf() function reads from the file, which can then be printed on
the console using standard printf() function
1 391
fseek() Contd
Return
Type: Integer
Value: On success Zero(0)
On failure Non-Zero
1 392
fseek() example
Code:
int main () {
FILE * fp;
1 394
ftell() Example
Code:
int main () {
FILE * fp;
long int len;
fp = fopen ("file.txt","r");
if (fp==NULL)
printf ("Error in opening file"); else {
fseek (fp, 0, SEEK_END);
len=ftell (fp);
fclose (fp);
printf ("The file contains %ld characters.\n",len);
}
return 0;
}
1 395
ftell() Example Contd.
•In this example, file.txt is opened and using fseek(), file pointer is set
to the end of the file.
•Then, ftell() is used to get the currentposition, i.e. offset from the
beginning of the file.
1 396
rewind()
rewind()
It is used to set the file pointer at the beginning of the file. Function
prototype:
Parameters
1 397
int main () {
int n;
FILE * fp;
fp = fopen ("file.txt","w+");
if (fp==NULL)
printf ("Error in opening file");
else { fputs ("France is my favorite team",fp);
rewind (fp);
fputs("Brazil",fp);
fclose (fp);
}
r}eturn 0;
1 398
File position functions
The C library function int fseek(FILE *stream, long int offset, int
whence) sets the file position of the stream to the given offset.
1 399
Example
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is tutorialspoint.com", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}
1 400
Let us compile and run the above program that will create a file
file.txt with the following content. Initially program creates the file
and writes This is tutorialspoint.com but later we had reset the write
pointer at 7th position from the beginning and used puts() statement
which over-write the file with the following content –
1 401
Command Line Arguments
1 402
The command line arguments are handled using main() function
arguments where argc refers to the number of arguments passed,
and argv[] is a pointer array which points to each argument passed to
the program.
1 403
Example Program
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n"); }
}
1 404
When the above code is compiled and executed withoutpassing
any argument, it produces the following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself
and argv[1] is a pointer to the first command line argument supplied,
and *argv[n] is the last argument. If no arguments are supplied, argc
will be one, and if you pass one argument then argc is set at 2.
1 405
Searching
Linear Search
Binary Search
1 406
Linear Search
1 407
Features of Linear Search Algorithm
1 408
Binary Search
Binary Search is used with sorted array or list. In binary search, we
follow the following steps:
We start by comparing the element to be searched with the
element in the middle of the list/array.
If we get a match, we return the index of the middle element.
If we do not get a match, we check whether the element to be
searched is less or greater than in value than the middle element.
If the element/number to be searched is greater in value than the
middle number, then we pick the elements on the right side of the
middle element(as the list/array is sorted, hence on the right, we
will have all the numbers greater than the middle number), and
start again from the step 1.
If the element/number to be searched is lesser in value than the
middle number, then we pick the elements on the left side of the
middle element, and start again from the step 1.
1 409
Features of Binary Search
1 410
Sorting
1 411
Above value sort by apply any sorting technique. C languagehave
following technique to sort values;
1. Bubble Sort
2. Selection Sort
3. InsertionSort
1 412
Bubble Sort in C
1 413
Selection Sort in C
1. Step 1: Select the first element of the list (i.e., Element at first
position in the list).
1. Step 2: Compare the selected element with all other elements
in the list.
2. Step 3: For every comparision, if any element is smaller
than selected element (for Ascending order), then these
two are swapped.
3. Step 4: Repeat the same procedure with next position in the list
till the entire list is sorted.
1 415
Insertion Sort in C
• The insertion sort inserts each element in proper place. The strategy
behind the insertion sort is similar to the process of sorting a pack of
cards.
• You can take a card, move it to its location in sequence and move
the remaining cards left or right as needed.