Introduction to C Programming Basics
Introduction to C Programming Basics
MODULE-1
Introduction to C: Problem Solving, Problem Analysis Chart, Developing an Algorithm,
Flowchart and Pseudocode, program structure, Compilation & Execution process, Interactive
and Script mode, Comments, Indentation, Error messages, Primitive data types, Constants,
Variables, Reserved words, Arithmetic, Relational, Logical, Bitwise, Assignment, Conditional
operators, Input/Output Functions, Built-in Functions.
Practical: Create Problem Analysis Charts, Flowcharts and Pseudocode for simple C programs
(Minimum three).
Define Computer:
Computer is a calculating machine, which accepts data through input device, processes it using
processing device and give the result through output device. Computer is an electro-
mechanical machine. It consists of electronic parts (IC‟S) electrical (motors, fan) and
Mechanical parts (Outer cover, keyboard).
Characteristics of Computer:
The following are the characteristics of a computer:
1. Speed: Computer can process the data at an extremely high speed.
2. Accuracy: Computer will produce accurate result.
3. Reliability: It is the measurement of performance of computer.
4. Versatile: Computer can be used for different purpose.
5. Storage capacity: computer can store large amount of data.
Hardware: All the physical parts of the computer is called hardware. You can touch and feel.
Example: Keyboard, Mouse, outer cover, IC‟s
Software:Programs written for the computer is called software. Ex: MS-Word, C program,
Windows 10 OS
Operating System:It is the interface between user of the computer and computer hardware.
Text Editor: It is an application program which allows user to type text and edit it.
Computer Languages:
Machine Level Language (MLL) : Binary language it use 1 and 0. It is the only language
understood by the computer.
Assembly Level Language (ALL) : It uses short notations like add, sub, mul and div etc.
It cannot be understood by the computer. Hence ALL needs to be converted into MLL
Assembler: is the program, which converts ALL to MLL and vice versa.
Example for ALL: ALL 8085, ALL 8086
High Level Language (HLL) : It is English like language. It is easy to understand by the
programmer.
It cannot be understood by the computer.
HLL needs to be converted into MLL.
Compiler or Interpreter will be used to convert HLL to MLL and vice versa.
Compiler: converts HLL to MLL in one step.
Interpreter: Converts HLL to MLL line by line.
Example: C,C++, Java
[Link] solving
Problem solving in computer programming is the iterative process of understanding a problem,
devising a detailed step-by-step solution (an algorithm), and translating that solution into a
computer program. Key stages include defining and analyzing the problem to determine inputs
and outputs, developing an algorithm using natural language or flowcharts, coding the
algorithm into a programming language, and testing and debugging the program to ensure it
works correctly. This core skill allows programmers to break down complex issues into
manageable steps for a computer to execute.
[Link]:It is the step-by-step procedure to solve a given problem. It will accept input,
processes and gives output. It is simple to represent and it is independent of programming
language.
Example:
I. Write an algorithm to exchange the contents of two variable.
1. [Start]
II. Write an algorithm to find the area of a triangle given base and height.
1. [Start]
2. [Input – Base and height of the triangle]
Read(b,h)
3. [Process – to compute the area of the triangle]
a <- 0.5*b*h
4. [Output the area]
Write (a)
5. [Stop]
III. Write an algorithm to find the area of a triangle given its 3 sides.
1. [Start]
2. [Input – 3 sides of the triangle]
Read(a,b,c)
3. [Process – to compute half perimeter]
s<- (a+b+c)/2.0
4. [Process to compute the area ]
a <- sqrt( s * (s-a) * (s-b) * (s-c) )
5. [Output the area]
Write (a)
6. [Stop]
VI. Write an algorithm to compute the sum of first ‘n’ natural numbers
1. [Start]
2. [Input a number]
Read(n)
3. [Initialize]
sum < - 0
4. [compute the sum of first „n‟ numbers ]
for i <- 1 to n step 1
sum <- sum + i
end for
5. [Display the sum]
Write(sum)
6. [Stop]
VII. Write an algorithm to compute the factorial of the given number
1. [Start]
2. [Input a number]
Read(n)
3. [Initialize]
fact < - 1
4. [compute the factorial of „n‟ ]
for i <- 1 to n step 1
fact <- fact* i
end for
5. [Display the sum]
6. [Stop]
4. Flow chart:
It is the pictorial representation of an algorithm. All the steps are drawn in the form of
different shapes. Commonly used symbols for flow chart are :
5. Pseudocode
Pseudocode is an informal, high-level description of an algorithm or program logic. It uses a
mix of natural language (like English) and common programming constructs to outline the
steps involved in a process, without adhering to the strict syntax rules of any specific
programming language.
Human-readable:
It is designed for human understanding, not for execution by a computer.
Language-independent:
It can be understood by programmers regardless of their preferred programming language.
Focus on logic:
It emphasizes the sequence of operations and decision-making within an algorithm.
Informal syntax:
While it often uses keywords like IF, ELSE, FOR, WHILE, PRINT, etc., it does not require
precise punctuation or grammar like actual code.
Indentation for structure:
Indentation is commonly used to show the hierarchical structure of control flow (e.g., within
loops or conditional statements).
Purpose of pseudocode:
Algorithm design:
It helps in planning and structuring algorithms before writing actual code.
Communication:
It facilitates communication and understanding of algorithms among developers, designers,
and project managers.
Problem-solving:
It allows focusing on the logical steps to solve a problem without getting bogged down by
language-specific syntax.
Documentation:
It can serve as a form of documentation for algorithms.
Example
START
DECLARE variable 'number'
GET input from user and STORE in 'number'
A Pseudocode is a step-by-step
A Flowchart is pictorial representation of
description of an algorithm in code like
flow of an algorithm.
structure using plain English text.
Flowchart Pseudocode
This is a way of visually representing data, These are fake codes as the word pseudo
these are nothing but the graphical means fake, using code like structure but
representation of the algorithm for a better plain English text instead of programming
understanding of the code language
6. Introduction to C
C is a programming language developed at AT & T‟s Bell Laboratories of USA in 1972. It
was designed and written by a man named Dennis Ritchie. In the late seventies C began to
replace the more familiar languages of that time like PL/I, ALGOL, etc.
Interpreter
Assembler
Compiler and interpreter are used to convert the high level language into machine
level language. The program written in high level language is known as source program and
the corresponding machine level language program is called as object program. Both
compiler and interpreter perform the same task but there working is different. Compiler read
the program at-a-time and searches the error and lists them. If the program is error free then
it is converted into object program. When program size is large then compiler is preferred.
Whereas interpreter read only one line of the source code and convert it to object code. If it
check error, statement by statement and hence of take more time.
On Mac OS X, CodeWarrior and Xcode are two IDEs that are used by many programmers.
Under Windows, Microsoft Visual Studio is a good example of a popular IDE. Kylix is a
popular IDE for developing applications under Linux. Most IDEs also support program
development in several different programming languages in addition to C, such as C# and
C++.
Example:
// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
// Subprogram
int sum(int y)
{
return y + X;
}
The compilation is the process of converting the source code of the C language into
machine code. As C is a mid-level language, it needs a compiler to convert it into an
executable code so that the program can be run on our machine.
The C program goes through the following phases during compilation:
Working Process
In the context of C programming, "interactive mode" and "script mode" refer to how
C programs are typically developed and executed, although the terminology is more
commonly associated with interpreted languages like Python.
In a C debugger, you can set breakpoints, step through code line by line, inspect
variable values, and even modify variables during runtime. This provides immediate
feedback on specific parts of your code.
Debugging, testing small code snippets, understanding program flow, and exploring
variable states during execution.
Script Mode (for C):
:
This is the standard way to develop and run C programs. You write your entire
program in source code files (e.g., .c files).
The C source code is compiled into an executable binary file using a C compiler (like
GCC). This executable is then run as a complete program.
8. Comments
Comments in C programming are non-executable statements within the source code that are
ignored by the compiler. Their primary purpose is to provide explanations, documentation,
and notes for human readers of the code, improving readability and maintainability.
9. Indentation in C
[Link] Meassages
In C programming, "errors" refer to issues that prevent a program from compiling or
executing correctly. These errors can be categorized into several types:
Syntax Errors:
Occur when the code violates the grammatical rules of the C language.
Examples include missing semicolons, unbalanced brackets, or misspelled keywords.
Detected by the compiler during the compilation phase, preventing the creation of an
executable.
Linker Errors:
Arise during the linking phase, when the linker attempts to combine object files and
libraries to create a final executable.
Occur if the linker cannot find the definitions for functions or variables that have been
declared in the code but not defined (e.g., missing library files).
Runtime Errors:
Happen while the program is executing.
Often caused by illegal operations, such as division by zero, accessing invalid memory
locations, or attempting to open a non-existent file.
Can lead to program crashes or unexpected behavior.
Logical Errors:
The program compiles and runs without crashing, but it produces incorrect or
unexpected output.
Result from flaws in the program's algorithm or logic, where the code does not correctly
implement the intended functionality.
Compiler Warnings:
Not strictly errors, but indications of potential issues in the code that might lead to
problems later.
Examples include uninitialized variables or non-standard coding practices.
While warnings do not prevent compilation, it is best practice to address them to avoid
future errors.
Preprocessor Errors:
Occur during the preprocessor stage, before compilation.
Can be caused by issues with preprocessor directives, such as incorrect use
of #include or inability to locate a referenced header file.
Memory Errors:
A specific type of runtime error related to memory management.
Examples include memory leaks (failure to free dynamically allocated memory) or
attempting to access memory that has already been freed.
11.C Tokens: Character set, Identifiers, Keywords, constants, Data types, type
qualifiers, Declaration and Initialization of variables.
Token: The smallest individual units in a program are called tokens. The „C‟
1. Character set
2. Keywords
3. Identifiers
4. Constants
5. Operators
Character set:
\b backspace
\a audible bell
\v vertical tab
\t horizontal tab
\f form feed
\r carriage return
\” double quotes
\‟ single quotes
\\ back slash
\r is a carriage return character; it tells your terminal emulator to move the cursor at the
start of the line.
The cursor is the position where the next characters will be rendered.
So, printing a \r allows overriding the current line of the terminal emulator.
Example Program:
#include<stdio.h> main()
{
printf("Backspace Character\b");
printf(" Audible Bell\a\n");
printf("Vertical Tab\vDemonstration\n");
printf("Horizental Tab\tDefault 8 spaces\n");
printf("Form feed\fIt is only with Printer\n");
printf("Carriage Return\rmove the cursor at the start of the line\n");
printf("Single Quotes The \"Sun\" rises in the \'east\'\n");
printf("Backslash \\hai\n");
}
Output:
12.1 Keywords:
Keywords are reserved words. All keywords have fixed meanings. Keywords serve as
basic building blocks for program statements. In „C‟, there are 32 keywords. All
keywords must be written in lower case.
12.2 Identifiers: Identifier refers to the names of the variables, functions and arrays.
12.3 Constants:
Constants refer to fixed values that do not change during the execution of a program.
Integer constants:
Real constants:
Note: Character constants have integer values known as ASCII values. Since each
character constant represent an integer value, so character arithmetic is possible.
Example Program:
#include<stdio.h> main()
{
char ch='a'; printf("ch=%c\n",ch);
printf("ASCII value of \'%c\'=%d\n",ch,ch);
}
Output:
ch=a
ASCII value of 'a'=97
//Character Arithmetic
#include<stdio.h> main()
{
Output:
ch=a
ASCII value of c=99
12.4 variables in C:
In C programming, a variable is a named storage location in memory used to hold
data. Variables are fundamental for storing and manipulating information during
program execution.
Naming Rules:
Variable names must follow specific rules:
They can contain letters (A-Z, a-z), digits (0-9), and underscores (\_).
They must begin with a letter or an underscore.
They are case-sensitive (e.g., myVar and myvar are different).
They cannot be C reserved keywords (e.g., int, float, if).
They cannot contain spaces or other special characters.
Scope and Lifetime:
Variables have a defined scope (where they are accessible in the code) and lifetime (how
long they exist in memory). Common types include:
Local variables: Declared inside a function, accessible only within that function,
and exist only while the function is executing.
Global variables: Declared outside any function, accessible throughout the entire
program, and exist for the program's entire execution.
Static variables: Retain their value between function calls.
Usage:
Once declared and potentially initialized, variables can be used in expressions,
assignments, function calls, and input/output operations.
Example:
int num1 = 5;
int num2 = 3;
int sum = num1 + num2; // Using variables in an expression
printf("Sum: %d\n", sum); // Displaying the variable's value
12.5 Data types:
Data type specifies which type of data that we are storing in a variable. There are 3 types
of data types.
i. Integer
ii. Floating point
iii. Character
iv. Double precision floating point
Integer:
Signed integer uses one bit for sign and 15 bits for the magnitude of the number.
Formula to find number of bits occupied by data type when number of bytes is known:
-2n-1 to 2n-1 - 1
Floating point types:
Floating point or real numbers are stored in 32 bits (on all 16 bit and 32 bit machines)
with 6 bits precision.
3 classes of floating point types:
i. float
ii. double
iii. long double
Character types:
#include<stdio.h> main()
{
'C' supports a feature known as “type definition” that allows users to define an
identifier that would represent an existing data type.
The user defined data type identifier can later be used to declare variables.
General form:
where type is any existing data type, identifier is a new name given to the data
type.
Example program:
#include<stdio.h> int main()
{
Output:
Enter 2 values
5
6
Enter 2 values
1.9
6.7
a=5 b=6
x=1.900000 y=6.700000
Where identifier is a user defined enumerated data type, which can be used to
declare variables which can have one of the values enclosed within the braces
(known as enumeration constants).
After this definition, we can declare variables to be of this 'new' type.
enum identifier v1,v2,…,vn can only have one of the values value1, value2, …, valuen.
The assignments are:
v1=value3;
v5=value1;
Example:
Example program:
#include<stdio.h> main()
{
enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
enum day weekst,weekend;
weekst=Monday;
weekend=Thursday;
printf("weekst=%d\nweekend=%d\n",weekst,weekend);
}
Output:
weekst=0
weekend=3
Example program:
#include<stdio.h> main()
{
Output:
weekst=5
weekend=7
#include<stdio.h> main()
{
Type qualifiers:
We can change the properties of primitive or fundamental data type. There are
two type qualifiers:
i. const for constant
ii. volatile
const:
Example program:
1. #include<stdio.h>
2. main()
3. {
4. const int classsize=60;
5. printf("classsize=%d\n",classsize);
6. classsize=classsize*3;
7. printf("classsize=%d\n",classsize);
8. }
Note: The compiler gives an error at line number 6: assignment of read-onlyvariable 'a'.
volatile:
ANSI standard defines qualifier volatile that could be used tell explicitly the compiler that
a variable‟s value may be changed at any time by some external sources (from outside the
program).
Example:
volatile int a;
Example program:
#include<stdio.h>
main()
{
volatile int a=5;
printf("a=%d\n",a);
a=a*4;
printf("a=%d\n",a);
}
Output: a=5 a=20
13. Operator
This is a symbol use to perform some operation on variables, operands or with the
constant. Some operator required 2 operand to perform operation or Some required
single operation.
Several operators are there those are, arithmetic operator, assignment, increment ,
decrement, logical, conditional, comma, size of , bitwise and others.
1. Arithmetic Operator
This operator used for numeric calculation. These are of either Unary arithmetic
operator, Binary arithmetic operator. Where Unary arithmetic operator required
only one operand such as +,-, ++, --,!, tiled. And these operators are addition,
subtraction, multiplication, division. Binary arithmetic operator on other hand
required two operand and its operators are +(addition), -(subtraction),
*(multiplication), /(division), %(modulus). But modulus cannot applied with
floating point operand as well as there are no exponent operator in c.
Unary (+) and Unary (-) is different from addition and subtraction.
When both the operand are integer then it is called integer arithmetic and the result is
always integer. When both the operand are floating point then it is called floating
arithmetic and when operand is of integer and floating point then it is called mix type
or mixed mode arithmetic . And the result is in float type.
[Link] Operator
A value can be stored in a variable with the use of assignment operator. The
assignment operator(=) is used in assignment statement and assignment expression.
Operand on the left hand side should be variable and the operand on the right hand
side should be variable or constant or any expression. When variable on the left hand
side is occur on the right hand side then we can avoid by writing the compound
statement. For example,
int x= y;
int Sum=x+y+z;
The Unary operator ++, --, is used as increment and decrement which acts upon single
operand. Increment operator increases the value of variable by one
.Similarly decrement operator decrease the value of the variable by one. And these
operator can only used with the variable, but cann't use with expression and constant
as ++6 or ++(x+y+z)
It again categories into prefix post fix . In the prefix the value of the variable is
incremented 1st, then the new value is used, where as in postfix the operator is written
after the operand(such as m++,m--).
EXAMPLE
let y=12; z=
++y; y= y+1;
z= y;
Similarly in the postfix increment and decrement operator is used in the operation . And
then increment and decrement is perform.
EXAMPLE
let x= 5; y=
x++; y=x;
x= x+1;
[Link] Operator
5. Conditional Operator
void main()
{
int a=10, b=2
is:%d”);
}
Output:
Value is:10
6. Comma Operator
Comma operator is use to permit different expression to be appear in a situation where
only one expression would be used. All the expression are separator by comma and are
evaluated from left to right.
EXAMPLE
int i, j, k, l;
for(i=1,j=2;i<=5;j<=10;i++;j++)
7. Sizeof Operator
Size of operator is a Unary operator, which gives size of operand in terms of byte
that occupied in the memory. An operand may be variable, constant or data type
qualifier.
In one's complement all 0 changes to 1 and all 1 changes to 0. In the bitwise OR its
value would obtaining by 0 to 2 bits.
As the bitwise OR operator is used to set on a particular bit in a number. Bitwise
AND the logical AND.
It operate on 2operands and operands are compared on bit by bit basic. And hence both
the operands are of same type.
Operator used with one or more operand and return either value zero (for false) or one
(for true). The operand may be constant, variables or expressions. And the expression
that combines two r more expressions is termed as logical expression.
C has three logical operators :
Operator Meaning
&& AND
|| OR
! NOT
Where logical NOT is a unary operator and other two are binary operator. Logical
AND gives result true if both the conditions are true, otherwise result is false. And
logial OR gives result false if both the condition false, otherwise result is true.
[Link]/Output Functions
C programming relies on a set of standard input/output (I/O) functions, primarily found in
the <stdio.h> header file, to interact with the user and external files. These functions facilitate
receiving data from input devices (like the keyboard) and displaying information to output
devices (like the monitor).
#include <stdio.h>
int main() {
int age = 30;
printf("Your age is: %d\n", age);
return 0;
}
scanf(): This is a formatted input function used to read data from the console. It also uses a
format string to specify the expected data type and requires the address of the variable where
the input should be stored (using the & operator).
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
getchar(): Reads a single character from the standard input.
putchar(): Writes a single character to the standard output.
gets(): Reads a line of text (including spaces) from the standard input into a character
array. Note: gets() is considered unsafe due to potential buffer overflows and is generally
discouraged in favor of fgets().
puts(): Writes a string to the standard output, followed by a newline character.
START
DECLARE integer num1, num2, sum
DISPLAY "Enter first number: "
READ num1
DISPLAY "Enter second number: "
READ num2
CALCULATE sum = num1 + num2
DISPLAY "The sum is: ", sum
END
2. Program to Find the Larger of Two Numbers
START
DECLARE integer num1, num2
DISPLAY "Enter first number: "
READ num1
DISPLAY "Enter second number: "
READ num2
IF num1 > num2 THEN
DISPLAY num1, " is larger."
ELSE IF num2 > num1 THEN
DISPLAY num2, " is larger."
ELSE
DISPLAY "Both numbers are equal."
END IF
END
*************************************************************************
UNIT-II CONTROL STRUCTURES AND FUNCTIONS
Contents
Control Structures- Conditional Statements, Looping Statements
Functions-Library Functions, User defined Functions, Function Prototype, Function Definitions,
Types of Functions, Functions with and without arguments, Functions with no return and with
Return Values - Nested Functions - Recursion.
CONTROL STRUCTURES
CONTROL STRUCTURE
Control Statements
Conditional Unconditional
[Link]
4. if..else ladder
5. switch statement
CONDITIONAL STATEMENT
True
Statements
Syntax:
If(condition)
{
True statements;
}
If the condition is true, then the true statements are executed.
If the condition is false then the true statements are not executed, instead the
program skips past them.
The condition is given by relational operators like ==,<=,>=,!=,etc.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf(“Enter one value”);
scanf(“%d”,&i);
if(i<=25)
printf(“The entered no %d is < 25”,i);
getch();
}
Output:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,n;
clrscr();
printf(“Enter two values”);
n=scanf(“%d%d”,&a,&b);
if(n==2)
{
printf(“the sum of two numbers : %d”,a+b);
printf(“the product of two numbers:%d”,a*b);
}
getch();
}
Output:
It is basically two way decision making statement and always used in conjunction
with condition.
It is used to control the flow of expression and also used to carry the logical test and
then pickup one of the two possible actions depending on the logical test.
If the condition is true, then the true statements are executed otherwise false
statements are executed.
The true and false statements may be single or group of statements.
Condition
True statements;
else
False statements;
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(“Enter two value”);
scanf(“%d%d”,&a,&b);
if(a>b)
Output:
When a series of if_else statements are needed in a program, we can write an entire
if_else statement inside another if and it can be further nested. This is called nesting if.
Syntax:
if(condition 1)
{
if(condition 2)
{
True statement 2;
else
False statement 2;
}
else
False statement 1;
}
Example 1: //program to find the greatest of three numbers.
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
return 0;
}
Output:
Syntax:
if(condition 1)
{
if(condition 2)
{
True statement 2;
}
elseif(condition 3)
{
True statement 3;
else
False statement 3;
}
else
False statement 1;
}
Switch Statement
The switch statement is used to execute a particular group of statements from
several available groups of statements.
It allows us to make a decision from the number of choices.
It is a multi-way decision statement.
case 1: statements
break;
case 2: statements
break;
default: statements
break;
Syntax:
switch(expression)
{
case 1:
state
ment;
break;
case 2:
state
ment;
break;
default: statement;
break;
}
// program to print the give number is odd / even using switch case statement.
#include<stdio.h>
#include<conio.h> void main()
{
int a,b,c;
printf(“Enter one value”); scanf(“%d”,&a);
switch(a%2)
{
case 0:
printf(“The given no %d is even”, a);
break;
default :
printf(“The given no %d is odd”, a);
break;
}
}
Output:
Unconditional statement
Break statement
The break statement is used to terminate the loop.
When the keyword break is used inside any loop, control automatically transferred to
the first statement after the loop.
Syntax:
break;
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==6)
break;
printf(“%d”,i);
}
}
Output:
1 2 3 4 5
Continue Statement
In some situation, we want to take the control to the beginning of the loop, bypassing
the statement inside the loop which have not been executed, for this purpose the
continue is used.
When the statement continue is encountered inside any loop, control automatically
passes to the beginning of the loop.
Syntax:
continue;
While(condition)
{
……..
if(condition)
continue;
……….
}
Break Continue
Break statement takes the control to the Continue statement takes the control to be
outside of the loop beginning of the loop
It is also in switch statement This can be used only in loop statements
Always associated with if condition in loop This is also associated with if condition
Goto Statement:
C provides the goto statement to transfer control unconditionally from one place to
another place in the program.
A goto statement can change the program control to almost anywhere in the program
unconditionally.
The goto statement require a label to identify the place to move the execution.
The label is a valid variable name and must be ended with colon(:).
Syntax:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(“Enter the numbers”);
scanf(“%d%d”,&a,&b);
if(a==b)
goto equal;
else
{
printf(“%d and %d are not equal”,a,b);
exit(0);
}
equal: printf(“%d and %d are equal”,a,b);
}
Output:
LOOPING STATEMENTS
A loop statement allows us to execute certain block of code repeatedly until test condition is
false.
1. for loop
2. while loop
3. do...while loop
for loop:
The initialization statement is executed only once at the beginning of the for loop. Then the test
expression is checked by the program. If the test expression is false, for loop is terminated. But
if test expression is true then the code/s inside body of for loop is executed and then update
expression is updated. This process repeats until test expression is false.
for loop example
Write a program to find the sum of first n natural numbers where n is entered by user.
Note: 1,2,3... are called natural numbers.
#include <stdio.h>
void main(){
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to
sum=sum+count */
}
printf("Sum=%d",sum);
Output
#include <stdio.h>
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
Output
This program takes a positive integer from user and stores it in variable n. Then, for loop is
executed which checks whether the number entered by user is perfectly divisible by i or not
starting with initial value of i equals to 2 and increasing the value of i in each iteration. If the
number entered by user is perfectly divisible by i then, flag is set to 1 and that number will not
be a prime number but, if the number is not perfectly divisible by i until test condition i<=n/2 is
true means, it is only divisible by 1 and that number itself and that number is a prime number.
Different Types of For Loop in C Programming
for(i=0;i<5;i++)
printf("sathyabama");
for(i=0;i<5;i++)
{
printf("Statement 1"); printf("Statement 2");
printf("Statement 3"); if(condition)
{
--------
--------
}
}
If we have block of code that is to be executed multiple times then we can use curly braces to
wrap multiple statement in for loop
No Statement inside For Loop
for(i=0;i<5;i++)
{
}
It is bodyless for loop. It is used to increment value of “i”.This are not used generally. At
the end ,for loop value of i will be 5.
for(i=0;i<5;i++);
We will not get compile error if semicolon is at the end of for loop.
This is perfectly legal statement in C Programming.
This statement is similar to bodyless for loop.
for(i=0,j=0;i<5;i++)
{
statement1;
statement2;
statement3;
}
we have to set value of ‘i’ before entering in the loop otherwise it will take garbage value of „i‟.
Infinite For Loop:
i = 0;
for( ; ; )
{
statement1;
statement2;
statement3;
if(breaking condition)
break;
i++;
}
Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause
overflow of stack.
While Loop
Initialization;
while(condition)
{
----------
---------
----------
------
Increment/decrement;
}
For Single Line of Code – Opening and Closing braces are not needed. while(1) is used
for Infinite Loop
Initialization, Increment/Decrement and Condition steps are on different Line.
While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then
and then only code is executed ]
Examples:
#include <stdio.h>
int main()
{
int y = 0;/* Don't forget to declare variables*/
while ( y < 10 ) {/* While y is less than 10 */
printf( "%d\n", y );
y++; /* Update y so the condition can be met
eventually */
}
getchar();
}
#include<stdio.h>
void main()
{
int num=300;
while(num>255); //Note it Carefully
printf("Hello");
}
Output :
Will not print anything
1. In the above program , Condition is specified in the While Loop
2. Semicolon at the end of while indicated while without body.
3. In the program variable num doesn‟t get incremented , condition remains true forever.
4. As Above program does not have Loop body , It won‟t print anything
#include<stdio.h>
void main()
{
while(1)
printf("Hello");
}
Output :
#include<stdio.h>
void main()
{
int num=20;
while(num>10) {
printf("Hello");
}
}
Output :
1. Condition is specified in while Loop, but terminating condition is not specified and even
we haven‟t modified the condition variable.
2. In this case our subscript variable (Variable used to Repeat action) is not either
incremented or decremented
3. so while remains true forever.
Character as a Parameter in While Loop
#include<stdio.h>
void main()
{
while('A')
printf("Hello");
}
Output :
Infinite Time "Hello" word
Explanation :
DO..WHILE
The structure is
initialization;
do
{
--------------
--------------
incrementation;
}while(condition);
The condition is tested at the end of the block instead of the beginning, so the block will be
executed at least once. If the condition is true, it go back to the beginning of the block and
execute it again. A do..while loop is almost same as a while loop except that the loop body is
guaranteed to execute at least once.
#include <stdio.h>
int main()
{
int z;
z = 0; do {
/* " sathyabama is printed at least one time even though the
condition is false */
printf( "sathyabama\n" ); } while ( z != 0 );
getchar();
#include<stdio.h>
#include<stdio.h>
#include<stdio.h>
void main() {
int i = 1;
do {
printf("%d", i);
i++;
} while (i <= 5);
}
FUNCTIONS
LIBRARY FUNCTIONS
Definition
C Library functions are inbuilt functions in C language which are clustered in a group and
stored in a common place called Library. Each and every library functions in C executes explicit
functions. In order to get the pre- defined output instead of writing our own code, these library
functions will be used. Header file consists of these library functions like Function prototype and
data definitions.
Every input and output operations (e.g., writing to the terminal) and all mathematical
operations (e.g., evaluation of sines and cosines) are put into operation by library
functions.
The C library functions are declared in header files (.h) and it is represented as
[file_name].h
The Syntax of using C library functions in the header file is declared as
“#include<file_name.h>”. Using this syntax we can make use of those library functions.
#include<filename.h>” command defines that in C program all the codes are included in
the header files followed by execution using compiler.
It is required to call the suitable header file at the beginning of the program in terminal in
order to use a library function. A header file is called by means of the pre-processor
statement given below,
#include<filename.h>
Whereas the filename represents the header file name and #include is a pre- processor directive.
To access a library function the function name must be denoted, followed by a list of
arguments, which denotes the information being passed to the function.
Example
In case if you want to make use of printf() function, the header file <stdio.h> should be included at
the beginning of the C program.
#include <stdio.h>
int main()
{
/* NOTE: Error occurs if printf() statement is written without using
the header file */
Example
To find the square root of a number we use our own part of code to find them but this may
not be most efficient process which is time consuming too. Hence in C programming by declaring
the square root function sqrt() under the library function “math.h” will be used to find them rapidly
and less time consuming too. Square root program using the library functions is given below:
Finding Square root Using Library Function
#include <stdio.h>
#include <math.h>
int main(){
float num,root;
printf("Enter a number to find square root.");
scanf("%f",&num);
root=sqrt(num); /* Computes the square root of num and stores in
root. */
printf("Square root of %.2f=%.2f",num,root);
return 0;
}
C Header Files
In C Programming we can declare our own functions in C library which is called as user-
defined functions.
It is possible to include, remove, change and access our own user defined function to or
from C library functions.
Once the defined function is added to the library it is merely available for all C programs
which are more beneficial of including user defined function in C library function
Once it is declared it can be used anywhere in the C program just like using other C library
functions.
By using these library functions in GCC compilers (latest version), compilation time can be
consumed since these functions are accessible in C library in the compiled form.
Commonly the header files in C program are saved as ”file_name.h” in which all library
functions are obtainable. These header files include source code and this source code is
further added in main C program file where we include this header file via “#include
<file_name.h>” command.
Step 1:
For instance, hereby given below is a test function that is going to be included in the C
library function. Write and save the below function in a file as “addition.c”
addition(int a, int b)
{
int sum;
total =a + b;
return sum;
}
Step 2:
To add this function to library, use the command given below (in turbo C).
c:\> tlib [Link] + c:\ [Link]
+ represents including c:\[Link] file in the math library.
We can delete this file using – (minus).
Step 5:
Create a file “addition.h” and declare sample of addition() function like below.
int addition (int a, int b);
Now “addition.h” file has the prototype of function “addition”.
Note : Since directory name changes for each and every IDE, Kindly create, compile and
add files in the particular directory.
Step 6:
Here is an example to see how to use our newly added library function in a C program.
# include <stdio.h>
// User defined function is included here.
# include “c:\\addition.h”
int main ( )
{
int total;
// calling function from library
total = addition (10, 20);
printf ("Total = %d \n", total);
}
Output:
Total = 30
Source code checking for all header files can be checked inside “include” directory
following C compiler that is installed in system.
For instance, if you install DevC++ compiler in C directory in our system, “C:\Dev-
Cpp\include” is the path where all header files will be readily available.
The entire C programming inbuilt functions that are declared in conio.h header file are given
below. The source code for conio.h header file is also given below for your reference.
List of inbuilt conio.h file C functions:
Functions
Predefined Function is a part of a header file, User- Defined function are part of the program
which are called at runtime which are compiled at runtime
The Predefined function name is given by the User- Defined function name created by the
developer user
Predefined Function name cannot be changed User defined Function name can be changed
User Defined Functions
The function defined by the users according to their context (or) requirements is
known as a user defined function.
The User defined function is written by the programmer to perform specific task (or)
operation, which is repeatedly used in the main program.
These functions are helpful to break down the large program into a number of the
smaller function.
The user can modify the function in order to meet their requirements.
Every user define function has three parts namely
Function Declaration
Function Calling
Function Definition
While it is possible to write any complex program under the function, and it leads to a
number of problems, such as
The problem becomes too large and complex.
The user can‟t go through at a glance
The task of debugging, testing and maintenance become difficult.
If a problem is divided into a number of parts, then each part may be independently
coded and later it combined into a single program. These subprograms are called
functions, it is much easier to understand, debug and test the program.
Function Declaration
Like normal variable in a program, the function can also be declared before they
defined and invoked
Function declaration must end with semicolon (;)
A function declaration must declare after the header file
The list of parameters must be separated by comma.
The name of the parameter is optional, but the data type is a must.
If the function does not return any value, then the return type void is must.
If there are no parameters, simply place void in braces.
The data type of actual and formal parameter must match.
Syntax:
Return_type function_name (datatype parameter1, datatype parameter2,…);
Description:
Example:
int add(int x,int y,int z);
Function Call
The function call be called by simply specifying the name of the function, return
value and parameters if presence.
Syntax: function_name();
function_name(parameter);
return_value =function_name (parameter);
Description:
function_name : Name of the function
Parameter : Actual value passed to the calling function
Example
fun();
fun(a,b);
fun(10,20);
c=fun(a,b);
e=fun(2.3,40);
Function Definition
It is the process of specifying and establishing the user defined function by specifying
all of its element and characteristics.
Syntax:
Return_type function_name (datatype parameter1, datatype parameter2)
Example 1
#include<stdio.h>
#include<conio.h>
void add(); //Function Declaration void sub();//Function Declaration
void main()
{
clrscr();
add(); //Function call
sub(); //Function call
getch();
}
void add() //Function Definition
{
int a,b,c;
printf(“Enter two values”);
scanf(“%d%d”,&a,&b); c=a+b;
printf(‚add=%d‛,c);
}
void sub() //Function Definition
{
int a,b,c;
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
c=a-b;
printf(“sub=%d”,c);
}
Example 2 :
//Program to check whether the given number is odd or even
#include<stdio.h>
#include<conio.h>
void oddoreven()
{
printf("Enter One value");
scanf("%d",&oe);
if(oe%2==0)
printf("The Given Number%d is even");
else
printf("The Given Number %d is odd");
}
void main()
{
clrscr();
oddoreven();
getch();
}
Function Parameter
The Parameter provides the data communication between the calling function and called
function.
There are two types of parameters.
o Actual parameter: passing the parameters from the calling function to the
called function i.e the parameter, return in function is called actual parameter
o Formal parameter: the parameter which is defined in the called function i.e. The
parameter, return in the function definition is called formal parameter
Example:
main()
{
………..
Where
………..
Fun(a,b);
a,b are the actual
……….. parameters
………..
} x,y are formal parameter
Fun(int x,int y)
{
…………
…………
}
Example Program
#include<stdio.h>
#include<conio.h>
void add(int,int); //Function Declaration Output:
void sub(float,int);//Function Declaration
void main() add=7
{ sub=-2.500000
clrscr();
add(3,4); //Function call
sub(2.5,5); //Function call
getch();
}
void add(int a,int b)//Function Definition
{
int c;
c=a+b;
printf(“add=%d”,c);
}
void sub(float a, int b) //Function Definition
{
float c;
c=a-b;
printf(“sub=%f”,c);
}
Example 2:
//program for factorial of given
number #include<stdio.h>
#include<conio.h> void main()
{
int fact(int); Output:
int f; Enter one value 5
clrscr(); The Factorial of given
printf("Enter one value"); number 5 is 120
scanf("%d",&f);
printf("The Factorial of given number %d is %d",f,fact(f));
getch();
}
int fact(int f)
{
if(f==1) return 1;
else
return(f*fact(f-1));
}
Function Prototype (or) Function Interface
The functions are classified into four types depends on whether the arguments
are present or not, whether a value is returned or not. These are called
function prototype.
In ‘C’ while defining user defined function, it is must to declare its prototype.
A prototype states the compiler to check the return type and arguments type of
the function.
A function prototype declaration consists of the function’s return type, name
and argument. It always ends with semicolon. The following are the function
prototypes
o Function with no argument and no return value.
o Function with argument and no return value.
o Function with argument and with return value.
o Function with no argument with return value.
In this prototype, no data transfer takes place between the calling function and
the called function. i.e., the called program does not receive any data from the
calling program and does not send back any value to the calling program.
Syntax:-
main() void Fun()
{ {
The dotted lines indicates that,
………..
there is only transfer of control,
………..
……….. but no data transfer.
………..
Fun();
……….. }
………..
}
Example program 1
#include<stdio.h> Output:
#include<conio.h> Enter two values 6 4
mul=24
void mul();
void main()
{
clrscr();
mul();
getch();
}
void mul()
{
int a,b,c;
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
c=a*b;
printf(“mul=%d”,c);
}
Example program 2
//Program for finding the area of a circle using Function with no argument
and no return value
I#include<stdio.h>
#include<conio.h>
void circle();
Output:
void main()
Enter radius 5
{ The area of circle 78.500000
circle();
}
void circle()
{
int r;
float cir;
printf("Enter radius");
scanf("%d",&r);
cir=3.14*r*r;
printf("The area of circle is %f",cir);
}
Function with argument and no return value
In this prototype, data is transferred from the calling function to called
function. i.e., the called function receives some data from the calling function
and does not send back any values to calling function
It is one way data communication.
Syntax:-
main() void Fun(x,y) The solid lines indicate data
{ { transfer and dotted line indicates
……….. ……….. a transfer of control.
……….. ………..
Fun(a,b);
a and b are the actual
……….. }
……….. parameters
}
Example program 1: x and y are formal parameters
#include<stdio.h>
#include<conio.h>
void add(int,int);
void main() Output:
{ Enter two values 6 4
clrscr(); add=10
int a,b;
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
add(a,b);
getch();
}
void add(int x,int y)
{
int c;
c=x+y;
printf(“add=%d”,c);
}
Example program 2:
//Program to find the area of a circle using Function with argument and no return value
#include<stdio.h>
#include<conio.h>
void circle(int);
Output:
void main()
Enter radius 5
{ The area of circle 78.500000
int r;
clrscr();
printf("Enter radius");
scanf("%d",&r);
circle(r);
}
void circle(int r)
{
float cir;
cir=3.14*r*r;
printf("The area of circle is %f",cir);
getch();
}
Function is a good programming style in which we can write reusable code that
can be called whenever required.
Whenever we call a function, the sequence of executable statements gets
executed. We can pass some of the information (or) data to the function for
processing is called a parameter.
In ‘C’ Language there are two ways a parameter can be passed to a function.
They are
o Call by value
o Call by reference
Call by Value:
This method copies the value of the actual parameter to the formal parameter of the
function.
Here, the changes of the formal parameters cannot affect the actual parameters,
because formal parameter are photocopies of the actual parameter.
The changes made in formal arguments are local to the block of the called function.
Once control returns back to the calling function the changes made disappears.
Example Program
#include<stdio.h>
#include<conio.h>
void cube(int);
int cube1(int);
void main() Output:
Call by reference
Call by reference is another way of passing parameter to the function.
Here the address of the argument is copied into the parameter inside the function, the
address is used to access arguments used in the call.
Hence, changes made in the arguments are permanent.
Here pointer is passed to function, just like any other arguments.
Example Program
#include<stdio.h>
#include<conio.h>
void swap(int,int);
Output:
void main() Before swapping a=5 b=10
After swapping a=10 b=5
{
int a=5,b=10;
clrscr();
printf(“Before swapping a=%d b=%d”,a,b);
swap(&a,&b);
printf(“After swapping a=%d b=%d”,a,b);
getch();
}
void swap(int *x,int *y)
{
int *t;
t=*x;
*x=*y;
*y=t;
}
If we are calling any function inside another function call, then it is known as Nesting
function call. In other words, a function calling different functions inside is termed as Nesting
Functions.
Example:
// C program to find the factorial of a number.
#include <stdio.h>
//Nesting of functions
//calling function inside another function
//calling fact inside print_fact_table
function
Output:
1 factorial is 1
2 factorial is 2
3 factorial is 6
4 factorial is 24
5 factorial is 120
Recursion
#include <stdio.h>
int fact(int); // function declaration
void main() // main function
{
printf("Factorial =%d",fact(5)); // fact(5) is the function call
}
int fact(int n) // function definition
{
if (n==1) return 1; else
return n * fact(n-1); // fact(n-1) is the recursive function call
}
Output:
Factorial = 120
Discussion:
For 1! , the functions returns 1, for other values, it executes like the one below:
When the value is 5, it comes to else part and calculates like this,
= 5 * fact (5-1) = 5 * fact (4)
=120
Example :
Output: 11
QUESTIONS FOR PRACTICE
1. What would be the output of the following programs:
(a) main( )
{
int a = 300, b, c ; if ( a >= 400 )
b = 300 ; c = 200 ;
printf ( "\n%d %d", b, c ) ;
}
(b) main( )
{
int a = 500, b, c ; if ( a >= 400 )
b = 300 ; c = 200 ;
printf ( "\n%d %d", b, c ) ;
}
(c) main( )
{
int x = 10, y = 20 ; if ( x == y ) ;
printf ( "\n%d %d", x, y ) ;
}
(d) main( )
{
int x = 3, y = 5 ;
if ( x == 3 )
printf ( "\n%d", x ) ;
else
printf ( "\n%d", y ) ;
}
(e) main( )
{
int x = 3 ; float y = 3.0 ;
if ( x == y )
printf ( "\nx and y are equal" ) ;
else
printf ( "\nx and y are not equal" ) ;
}
(f) main( )
{
int x = 3, y, z ; y = x = 10 ;
z = x < 10 ;
printf ( "\nx = %d y = %d z = %d", x, y, z ) ;
}
(g) main( )
{
int k = 35 ;
printf ( "\n%d %d %d", k == 35, k = 50, k > 40 ) ;
}
(h) main( )
{
int i = 65 ; char j = ‘A’ ;
if ( i == j )
printf ( “C is WOW” ) ;
else
printf( "C is a headache" ) ;
}
(i) main( )
{
int a = 5, b, c ; b = a = 15 ;
c = a < 15 ;
printf ( "\na = %d b = %d c = %d", a, b, c ) ;
}
(j) main( )
{
int x = 15 ;
printf ( "\n%d %d %d", x != 15, x = 20, x < 30 ) ;
}
5. C program to display all prime numbers between Two interval entered by user.
6. C program to reverse a given number.
7. Program to Check Whether Given Number is Perfect Or Not.
8. Program Even Number Pyramid in C
2 4
2 4 6
2 4 6 8
3 5
7 11 13
17 19 23 29
31 37 41 43 47
a) 1+ 2 + 3 +......+ n.
2 2 2 2
b) 1 + 2 + 3 +.... + n .
11. The keyword used to transfer control from a function back to the calling
function is
a) Switch b) Return c) Goto
12. Write a program to Calculate the Power of a Number Using Recursion
13. How many times the program will print "Sathyabama University" ?
#include<stdio.h>
int main()
{
printf("\nSathyabma University");
main();
return 0;
}
a) Infinite times b) 32767 times c) Till stack overflows
14. What will be the output of the program?
#include<stdio.h>
int f1(int);
int main()
{
int k=35;
k = f1(k=f1(k=f1(k)));
printf("k=%d\n", k);
return 0;
}
int f1(int k)
{
k++;
return k;
}
15. Which of the following function declaration is illegal?
a) int 11bhk(int); b) int 11bh2k(int a);
c) int 22bhk2(int*, int []); d) All of the mentioned
Lifetime of Variables
The lifetime refers to how long the variable retains its value in memory.
Variables can have automatic, static, or dynamic lifetimes depending on where and how they’re declared
Local variables declared within a function have local scope and automatic lifetime. This means they are
created when the function is called and destroyed when the function exits.
#include <stdio.h>
void exampleFunction() {
int main() {
exampleFunction();
return 0;
In this example, localVar exists only within example Function. When example Function is
called, localVar is created, and when the function exits, it is destroyed.
Global variables are declared outside of any function and have global scope. They are accessible from any
function in the same file and have a static lifetime, meaning they exist for the entire runtime of the
program.
#include <stdio.h>
void display() {
int main() {
return 0;
In this case, globalVar is accessible both in main and display functions and remains in memory for the
program’s lifetime.
Block scope applies to variables declared within specific blocks like loops, conditionals, or other code
blocks.
#include <stdio.h>
int main() {
return 0;
Here, the variable i has block scope, limited to the for loop. It is created when the loop starts and
destroyed when the loop ends.
A static local variable has a local scope (accessible only within the function) but a static lifetime (it
retains its value between function calls).
#include <stdio.h>
void staticExample() {
count++;
int main() {
staticExample(); // Output: 1
staticExample(); // Output: 2
staticExample(); // Output: 3
return 0;
Here, count is a local variable with static storage, so it retains its value between calls to staticExample.
The extern keyword is used to declare a global variable in another file, allowing access across multiple
files.
File 1 (file1.c):
#include <stdio.h>
void display() {
File 2 (file2.c):
#include <stdio.h>
int main() {
printf("Accessing globalVar from file2: %d\n", globalVar);
return 0;
In file2.c, we declare globalVar with extern, indicating that it is defined in another file. This
allows file2.c to access globalVar from file1.c.
C programming and problem solving Module 3
MODULE 3
Arrays
INTRODUCTION
Arrays: Array is a sequential collection of similar data items.
Pictorial representation of an array of 5 integers
10 20 30 40 50
A[0] A[1] A[2] A[3] A[4]
A single dimensional array is a linear list of related data items of same data type.
In memory, all the data items are stored in contiguous memory locations.
Declaration of one-dimensional array(Single dimensional array)
Syntax:
datatype array_name[size];
float b[5];
The above statement allocatests 5*4=20 Bytes of memory for the array b.
Each element in the array is identified using integer number called as index.
If n is the size of array, the array index starts from 0 and ends at n-1.
Declaration of arrays only allocates memory space for array. But array elements are not initialized
and hence values has to be stored.
Therefore to store the values in array, there are 3 methods
1. Initialization
2. Assigning Values
3. Input values from keyboard through scanf()
Where
datatype can be char,int,float,double
array name is the valid identifier
size is the number of elements in array
v1,v2,v3…......vn are values to be assigned.
2 4 34 3 4
10 20 0 0 0
4. String Initialization
Sequence of characters enclosed within double quotes is called as string.
The string always ends with NULL character(\0)
S V I T \0
S[0] S[1] S[2] S[3] S[4]
10 20 30
for(i=0; i<n;i++)
{
sum=sum+ a[i];
}
printf(“sum is %d\n”,sum):
#include<stdio.h>
void main()
{
int i,n,a[10],big;
printf(“enter number of array elements\n”);
scanf(“%d”,&n);
printf(“enter array elements\n”);
for(i=0; i<n;i++)
{
scanf(“%d”,&a[i]);
}
big=a[0];
for(i=0; i<n;i++)
{
if(a[i]>big)
big=a[i];
}
printf(“the biggest element in an array is %d\n”,big);
}
#include<stdio.h>
void main()
{
int i,n,a[10];
a[0]=0;
a[1]=1;
printf(“enter n\n”);
scanf(“%d”,&n);
if(n==1)
{
printf(“%d\t”,a[0]);
}
if(n==2)
{
printf(“%d\t %d\t”,a[0],a[1]);
}
if(n>2)
{
printf(“%d \t %d\t”,a[0],a[1]);
for(i=2;i<n;i++)
{
a[i]=a[i-1]+a[i-2];
printf(“%d\t”,a[i]);
}
}
}
data_type array_name[exp1][exp2];
Or
data_type
array_name[row_size][column_size];
For example:
int a[2][3];
The above statements allocates memory for 3*4=12 elements i.e 12*2=24 bytes.
{a1,a2,......an}
{b1,b2,.....bn}
..............
{z1,z2........zn}
10 20 30
40 50 60
70 80 90
40 50 0
70 80 0
#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“eneter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“array elements are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}
}
#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3],b[3][3] ,c[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array a elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“resultant matrix c is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=a[i][j];
}
}
printf(“matrix b is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
}
#include<stdio.h>
void main()
{
int m,n,i,j,sum,p,q,k,a[3][3],b[3][3],c[3][3];
printf(“enter number of rows and columns of matrix a \n”);
scanf(“%d %d”,&m,&n);
printf(“enter number of rows and columns of matrix b \n”);
scanf(“%d %d”,&p,&q);
if(n!=p)
{
printf(“multiplication not possible\n”):
exit(0);
}
printf(“enter matrix a elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter array b elements\n”);
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
}
}
printf(“resultant matrix a is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“resultant matrix a is \n”);
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
printf(“resultant matrix a is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
6 Write a program to find sum of each row and sum of each column
#include<stdio.h>
void main()
{
int m,n,i,j,rsum,csum,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<m;i++)
{
rsum=0;
for(j=0;j<n;j++)
{
rsum=rsum+a[i][j];
}
printf(“sum is %d”,rsum);
}
for(i=0;i<m;i++)
{
csum=0;
for(j=0;j<n;j++)
{
csum=csum+a[i][j];
}
printf(“sum is %d”,csum);
}
#include<stdio.h>
void main()
{
int m,n,i,j,sum=0,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<m;i++)
{
sum=sum+a[i][j];
}
printf(“sum is %d”,rsum);
}
Searching
The process of finding a particular item in the large amount of data is called searching.
The element to be searched is called key element.
There are two methods of searching:
1] Linear search.
2] Binary search.
1] Linear Search:
Linear search also called sequential search is a simple searching technique.
In this technique we search for a given key item in linear order i.e,one after the other from
first element to last element.
The search may be successful or unsuccessful.
If key item is present, the search is successful, otherwise unsuccessful search.
for(i=0; i<n;i++)
{if(key==a[i])
{
printf(“successful search\n”);
exit(0);
}
}
printf(“unsuccessful search\n”);
}
2] Binary Search:
Binary search is a simple and very efficient searching technique which can be applied if the items are
arranged in either ascending or descending order.
In binary search first element is considered as low and last element is considered as high.
Position of middle element is found by taking first and last element is as follows.
mid=(low+high)/2
Mid element is compared with key element, if they are same, the search is successful.
Otherwise if key element is less than middle element then searching continues in left part of the array.
If key element is greater than middle element then searching continues in right part of the array.
The procedure is repeated till key item is found or key item is not found.
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
printf(“successful search\n”);
exit(0);
}
if(key<a[mid])
{
high=mid-1;
}
else
{
low=mid+1;
}
}
printf(“unsuccesfull seasrch\n”);
}
Sorting
The process of arranging elements in either ascending order or descending order is called Sorting.
Bubble Sort
getch();
}
Selection Sort
In Selection sort, the smallest element is exchanged with the first element of the unsorted list of elements
(the exchanged element takes the place where smallest element is initially placed). Then the second
smallest element is exchanged with the second element of the unsorted list of elements and so on until all
the elements are sorted. In the following C program we have implemented the same logic.
Before going through the program, lets see the steps of selection sort with the help of an example:
Entered elements: 22 0 -90 89 17
Step 1: -90 0 22 89 17 (22 and -90 exchanged position)
Step 2: -90 0 22 89 17 (0 is at right place, no exchange needed)
Step 3: -90 0 17 89 22 (22 and 17 exchanged position)
Step 4: -90 0 17 22 89 (89 and 22 exchanged position)
for(i=0; i<n-1;i++)
{
min=i;
//finding min value starting from index i+1
for(j=i+1; j<n; j++)
{
if (a[ j ]>a[ min] )
{
min=j;
}
}
//starting 1st element of unsorted part with min value
temp= a[ j ];
a[ j ]= a[ j+1 ];
a[ j+1 ]=temp;
getch();
}
Strings
Definition:
A string is a sequence of characters within double quotes. A string constant is always terminated y null character.
A string is pictorially represented as follows:
a S V I T \0
0 1 2 3 4
String Declaration:
Like all other variable a string variable a string variable also has to be declared before it is used.
0 1 2 3 4 5 6 7 8 9
String Initialization:
Initialization is a process of assigning values to a string, before doing manipulation.
Strings are initialized in 4 ways:
1. Initializing character by character
2. Partial Array Initialization
3. Initialization without size
4. Initialization of Array with string
b S V I T \0
0 1 2 3 4
NOTE: scanf() cannot read spaces and any special symbols i.e
conversion code cannot read spaces, it will terminated as soon
as space appear.
Write a program to read and print an string using scanf() and printf()
#include<stdio.h>
void main()
{
char str[20];
printf(“enter the string\n”);
scanf(“%s”,str);
printf(“The entered string is \n”);
printf(“%s”,str);
}
Write a program to read and print an string using gets() and puts()
#include<stdio.h> OutPut:
#include<string.h>
void main() Enter the string
{ HELLO HOW R U
char str[20]; The entered string is
printf(“enter the string\n”); HELLO HOW R U
gets(str);
printf(“The entered string is \n”);
puts(str);
}
H E L L O H O W R U \0
Based on the kind of data processed, the I/O function are classified into
1. Token Oriented I/O functions:
2. Line Oriented I/O functions
3. Character Oriented I/O functions
2 strcpy strcpy(char dest[ ] , char src[ ]); char src[5] =”SVIT”; This function copies content
char dest[5]; from source string to
strcpy(dest ,src); destination string including \0.
src[0] src[1] src[2] src[3] src[4] Size of dest string should be
s V I T \0 greater or equal to the size of
source string src to store the
S V I T \0 entire source string.
3. strncpy strcpy(char dest[ ] , char src[ ],int n); char src[5] =”SVIT”; This function copies n
char dest[5]; characters from source string to
strcpy(dest ,src,2); destination string .
src[0] src[1] src[2] src[3] src[4] In thisexample only 2
S V I T \0 characters are copied from src
to dest.
S V \0
5 strncat strncat(char s1[ ] , char s2[ ],n); char s1[5]=”SVIT”; This function copies the n
char s2[5]=”ECE”; characters of s2 string to the
strncat(s1,s2,2); end of s1 string.
The delimiter of s1 is replaced
S V I T \0 by first character of s2.
0 1 2 3 4
E C E \0
0 1 2 3 4
S1 S V I T E C \
0
0 1 2 3 4 4 6 7 8 9
6 strcmp int strcmp( char s1[ ] , char s2[ ]); 1) Strings are equal where:
S1[4]=”RAM”; s1 is first string
S2[4]=”RAM”; s2 is second string
Strcmp(S1,S2); This function used to
compare two strings.
R == S2[0] R The comparison starts with
S1[0] first character of each
S1[1] A == S2[1] A string.
S1[2] M == S3[2] M This comparison continues
S1[3] \0 == S4[3] \0 till the corresponding
character differ or until the
S1[0]==S2[0] end of the character is
R==R(ASCII value of R is compared) reached.
similarly for other characters. The strcmp Returns 3values
S1[3]==S2[3] Possibly:
\0==\0(ASCII value of \0 is compared and it returns 0 if both strings are equal.
is 0.) returns positive value ,if s1>s2
2)String S1 is Lesser than String S2 returns negative value if s1<s2
S1[4]=”ABC”;
S2[4]=”BAC”;
Strcmp(S1,S2);
S1[0] A == S2[0] B
S1[1] B == S2[1] A
S1[2] C == S3[2] C
S1[3] \0 == S4[3] \0
S1[0]==S2[0]
A==B(ASCII value of A is compared with
ASCII value of B)
i.e 65==66 returns S1<S2
S1[0] B == S2[0] A
S1[1] B == S2[1] B
S1[2] C == S3[2] C
S1[3] \0 == S4[3] \0
S1[0]==S2[0]
A==B(ASCII value of A is compared with
ASCII value of B)
i.e 66==65 returns S1>S2
7 strncmp int strcmp( char s1[ ] , char s2[ ], n); 1) Strings are equal where:
S1[4]=”RAM”; s1 is first string
S2[4]=”RAM”; s2 is second string
strcmp(S1,S2,2); This function used to
comparen number of
R == S2[0] R characters two strings.
S1[0] The comparison starts with
S1[1] A == S2[1] A first character of each
S1[2] M == S3[2] M string.
S1[3] \0 == S4[3] \0 This comparison continues
till the corresponding
Only 2 characters from each S1 and S2 is character differ or until the
compared. end of the character is
Other function is similar to strcmp(). reached or specified number
of characters have been
tested..
The strcmp Returns 3values
Possibly:
returns 0 if both strings are equal.
returns positive value ,if s1>s2
returns negative value if s1<s2
8 strrev( ) void strrev(char str[ ]); Given string This function reverse all
S1 S V I T E C E \0 characters in the S1 except
0 1 2 3 4 5 6 7 89 Null character.
strrev(s1 The original string is lost.
Reverse String
S1 E C E T I V S \0
0 1 2 3 4 5 6 7 8 9
S1[6]==S1[0]
S1[5]==S1[1]
S1[4]==S1[2]
S1[3]==S1[3]
S1[2]==S1[4]
S1[1]==S1[5]
S1[0]==S1[6]
strlen() strrev()
#include<stdio.h>
#include<stdio.h> #include<string.h>
#include<string.h> void main()
void main() {
{ char name[15]; char str[]=”INDIA”;
int len; strrev(str);
printf(“Enter the string\n”); printf(“string=%s”,str);
gets(name); }
len=strlen(name);
printf(“\n The string length is %d”,len); OUTPUT
} String=AIDNI
OUTPUT
Enter the string
COMPUTER
The string length is 8
strcpy() strncpy()
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
void main() void main()
{ {
char src[15],char dest[15]; char src[15],char dest[15];
printf(“Enter the source string\n”); int n;
gets(src); printf(“Enter the source string\n”);
strcpy(dest,src); gets(src);
printf(“\n The copied string is \n”); printf(“Enter n”);
puts(dest); scanf(“%d”,&n);
} strncpy(dest,src);
printf(“\n The copied string is \n”);
puts(dest);
OUTPUT }
Enter the source string
COMPUTER OUTPUT
The copied string is Enter the source string
COMPUTER COMPUTER
Enter n
3
The copied string is
COM
strcat() strncat()
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
void main() void main()
{ {
char S1[15],char S2[15]; char S1[15],char S2[15];
printf(“Enter the string 1\n”); int n;
gets(S1); printf(“Enter the string 1\n”);
printf(“Enter the string 2\n”); gets(S1);
gets(S2); printf(“Enter the string 2\n”);
strcat(S1,S2); gets(S2);
printf(“\n The Concatenated string is \n”); printf(“Enter n”);
puts(S1); scanf(“%d”,&n);
} strncat(S1,S2,n);
printf(“\n The Concatenated string is \n”);
OUTPUT puts(S1);
Enter the string1 }
HELLO
Enter the string 2 OUTPUT
ALL Enter the string1
The Concatenated string is HELLO
HELLOALL Enter the string 2
SVIT
Enter n
2
The Concatenated string is
HELLOSV
strcmp() strcnmp()
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
void main() void main()
{ {
char S1[15],char S2[15]; char S1[15],char S2[15];
edit characters
edit characters represent the valid characters that are allowed in the string and should be enclosed within „ [ „ and „]‟
Working:
Each character read by scanf is compared with edit character set.
If the character read is in edit character set, it is copied into str
The above procedure is repeated as long as the character read is in edit character set.
If the character read does not match with edit character set, the reading process is stopped and remaining characters will still
be available in keyboard buffer.
If the first character read is not in edit characters set, the scanf is terminated and a „\0‟ is copied into str indicating null
string.
The edit characters set is indicated by the symbol caret(^)
Array of Strings
Group of Strings is known as array of strings.
To represent array of strings two dimensional array is required.
Declaration Syntax: char string_name[row][column];
Initialization
char a[5][10]={
“ARJUN”,
“BHARATHI”,
“SAMAYA”,
“SVIT”,
“VINAYAKA”
};
0 1 2 3 4 5 6 7 8 9
0 A R J U N \0
a B H A R A T H I \0
1
2 S A M A Y A \0
3 S V I T \0
4 V I N A Y A K A \0
Note: Example program is binary search
1 Department of CSE
Objectives
• To understand the need and application of pointers
• To learn how to declare a pointer and how it is represented in
memory
• To learn the relation between arrays and pointers
• To study the need for call-by-reference
• To distinguish between some special types of pointers
2 Department of CSE
Agenda
• Basics of Pointers
• Declaration and Memory Representation
• Operators associated with pointers
• address of operator
• dereferencing operator
• Arrays and Pointers.
• Compatibility of pointers
• Functions and Pointers
• Special types of pointers
• void pointer
• null pointer
• constant pointers
• dangling pointers
• pointer to pointer
3 Department of CSE
Introduction
4 Department of CSE
Pointer Declaration
• General form of a pointer variable declaration:-
datatype *ptrname;
• Eg:-
• int *p; (p is a pointer that can point only integer variables)
• float *fp; (fp can point only floating-point variables)
5 Department of CSE
Initialization of Pointer Variable
• Uninitialized pointers will have some unknown memory address in them.
6 Department of CSE
Why Pointers?
• Manages memory more efficiently.
• Leads to more compact and efficient code than that can be obtained
in other ways
7 Department of CSE
Referencing/ “Address of ” operator
• To make a pointer point to another variable, it is necessary to obtain
the memory address of that variable.
8 Department of CSE
Dereferencing/Indirection Operator
• It‟s a unary operator - *
• This is akin to looking inside a safety deposit box only to find the
number of (and, presumably, the key to ) another box, which you
then open.
9 Department of CSE
Referencing & Dereferencing Operators
10 Department of CSE
Sample Code -1 : Simple Pointer
#include<stdio.h> Output:-
int main()
{ Number : 10
int x=10;
int *ip;
Address: 0x7fff4fab3044
ip=&x; Number using pointer : 10
printf("Number : %d\n",x);
printf("Address: %p\n",(&x)); Address using Pointer: 0x7fff4fab3044
printf("Number using pointer : %d\n", *ip);
printf("Address using Pointer: %p\n",ip);
return 0;
}
11 Department of CSE
Sample Code -2 : Pointers to different types
#include<stdio.h> Output:-
int main()
{ Number using pointer : 10
int x=10;
int *ip;
Address using Pointer: 0x7fff4f5c31bc
float y=2.5, *fp; Decimal value : 2.500000
fp = &y;
ip=&x; Address of y : 0x7fff4f5c31b8
printf("Number using pointer : %d\n", *ip);
printf("Address using Pointer: %p\n",ip);
printf("Decimal value : %f\n",*fp);
printf("Address of y : %p\n",fp);
return 0;
}
12 Department of CSE
Sample Code -3 : Same pointer to multiple variables
#include<stdio.h> Output:-
int main()
{ Enter three integers : 10 20 30
int a,b,c,*p; //a,b and c are variables and p is a
pointer pointer points to a. Value is 10
printf("Enter three integers : "); pointer points to b. Value is 20
scanf("%d %d %d",&a,&b,&c);
p = &a; pointer points to c. Value is 30
printf("pointer points to a. Value is %d\n",*p);
p = &b;
printf("pointer points to b. Value is %d\n",*p);
p = &c;
printf("pointer points to c. Value is %d\n",*p);
return 0;
}
13 Department of CSE
Sample Code -4 : Multiple Pointers to same variable
#include<stdio.h> Output:-
int main()
{ Enter an integer : 15
int a;
int *p = &a; 15
int *q = &a; 15
int *r = &a;
15
printf("Enter an integer : ");
scanf("%d",&a);
printf("%d\n",*p);
printf("%d\n",*q);
printf("%d\n",*r);
return 0;
}
14 Department of CSE
Pointer and 1D Array
15 Department of CSE
Relationship between array and pointer
• The name of array is a pointer to the first element
• Address of first element and name of array represent the same memory address.
16 Department of CSE
Sample Program 5 : Pointer and Array I
Output:-
#include<stdio.h>
int main() 0x7fff03b2d380 0x7fff03b2d380
{ 11
int a[5] = {1,2,3,4,5};
int *p = a;
printf("%p %p\n",&a[0],a);
printf("%d %d\n",*a,*p);
return 0;
}
17 Department of CSE
Sample Program 6 : Pointer and Array II
#include<stdio.h>
Output:-
int main()
First element : 1 1
{
int a[5] = {1,2,3,4,5}; Second element: 2 2
int *p = &a[1];
return 0;
}
Note:-When a pointer to an array is not pointing to the first
element, index can be negative.
18 Department of CSE
Pointer Arithmetic and 1D Arrays
• If „a‟ is an array name, then „a‟ points to first element
• a+1 points to the second element, a+2 points to third element and
so on.
• Generally (a+n) points to (n+1)th element.
19 Department of CSE
Pointer arithmetic on different data types
• Size of single element varies with respect
to data type of array.
20 Department of CSE
Modifying values using pointers
21 Department of CSE
Modifying value using pointer
• If ip points to an integer x, *ip can be used in places where x could
have been used.
22 Department of CSE
Sample Code –7: Updating value using Pointer
#include<stdio.h>
int main() Output:-
{
Number using pointer : 10
int x=10;
int *ip; Address using Pointer:
float y=2.5, *fp; 0x7fff76d4f8ec
fp = &y;
ip=&x; Decimal value : 2.500000
printf("Number using pointer : %d\n", *ip); Address of y : 0x7fff76d4f8e8
printf("Address using Pointer: %p\n",ip);
printf("Decimal value : %f\n",*fp);
Updated Number : 11
printf("Address of y : %p\n",fp); Updated Number : 55
x+=1;
printf("Updated Number : %d\n", *ip);
Updated Number : 56
*ip *=5;
printf("Updated Number : %d\n", *ip);
++*ip;
printf("Updated Number : %d\n", *ip);
return 0;
}
23 Department of CSE
Sample Code -8 : Adding two numbers using Pointers
#include<stdio.h>
int main()
Output:-
{ 10 + 5 = 15
int a=10,b=5,c;
int *p1 = &a;
int *p2 = &b;
int *res = &c;
printf("%d + %d = %d\n",*p1,*p2,c);
return 0;
}
24 Department of CSE
Pointer to array : Order of placing „*‟ and „++‟
• Assume that z is an inger array with two values 1 and 2 (int z[2]={1,2};)
• Let ip be a pointer to z; (int *ip = z;)
• printf("%d\n", ++*ip);
• increments content in the address pointed by ip.
• z[0]=1 was taken and incremented by 1.
• In output the value is 2
• printf("%d\n", *++ip);
• increments the address pointed by ip.
• ip currently points to z[1]=3
• In output the value is 3
25 Department of CSE
Sample Code Snippet - 9a – ++ before *
#include<stdio.h> • Sample Output
main()
{ 0x7fff0fc66d30
int z[2]={1,3};
int * ip = z; 1
printf("%p\n",ip);
printf("%d\n", *ip);
2
printf("%d\n", ++*ip); 0x7fff0fc66d30
printf("%p",ip);
return 0;
}
26 Department of CSE
Sample Code Snippet -9b : * before ++
#include<stdio.h> • Sample Output
main()
{ 0x7ffffc801740
int z[2]={1,3};
int * ip = z; 1
printf("%p\n",ip);
printf("%d\n", *ip);
3
printf("%d\n", *++ip); 0x7ffffc801744
printf("%p",ip);
return 0;
}
27 Department of CSE
Pointer Compatibility
28 Department of CSE
Pointer Compatibility
• Pointers have a type associated with them They can point only
to specific type.
• Two types:-
• Pointer Size Compatibility
• Pointer Dereferencing compatibility
29 Department of CSE
Pointer Size Compatibility
• Size of all pointers is the same; i.e.; every pointer variable holds the
address of one memory location. But the size of variable that the
pointer points to can be different.
• Size of the type that a pointer points to is same as its data size.
30 Department of CSE
Sample Code -10 : Pointer Size Compatibility
#include<stdio.h> printf("Size of c : %3d | ",sizeofc);
int main() printf("Size of pc : %3d | ",sizeofpc);
{ printf("size of *pc : %3d\n",sizeofstarpc);
char c; printf("Size of a : %3d | ",sizeofa);
char* pc; printf("Size of pa : %3d | ",sizeofpa);
int sizeofc = sizeof(c); printf("size of *pa : %3d\n",sizeofstarpa);
int sizeofpc = sizeof(pc); printf("Size of d : %3d | ",sizeofd);
int sizeofstarpc = sizeof(*pc); printf("Size of pd : %3d | ",sizeofpd);
printf("size of *pd : %3d\n",sizeofstarpd);
int a; return 0;
int* pa; }
int sizeofa = sizeof(a);
int sizeofpa = sizeof(pa); Sample Output
int sizeofstarpa = sizeof(*pa);
Size of c : 1 | Size of pc : 8 | size of *pc : 1
double d;
Size of a : 4 | Size of pa : 8 | size of *pa : 4
double* pd;
int sizeofd = sizeof(d); Size of d : 8 | Size of pd : 8 | size of *pd : 8
int sizeofpd = sizeof(pd);
int sizeofstarpd = sizeof(*pd);
31 Department of CSE
Dereferencing Compatibility
• Dereference type is the type of variable that the pointer is
referencing.
32 Department of CSE
Sample Code 11: Pointer Dereferencing Incompatibility
#include<stdio.h>
ptrcompat.c: In function ‘main’:
int main()
{ ptrcompat.c:13: warning: assignment from
int x=10; incompatible pointer type
int *ip;
float y=2.5, *fp;
fp = &y; Output:-
ip=&x;
printf("Number using pointer : %d\n", *ip); Number using pointer : 10
printf("Address using Pointer: %p\n",ip);
printf("Decimal value : %f\n",*fp);
Address using Pointer: 0x7fffda19b6ec
printf("Address of y : %p\n",fp); Decimal value : 2.500000
fp = &x;
printf("New value pointed by fp = %f\n",*fp); Address of y : 0x7fffda19b6e8
return 0; New value pointed by fp = 0.000000
}
33 Department of CSE
Pointers and Functions
34 Department of CSE
How to swap two numbers using function?
#include<stdio.h>
int main() Output:-
{ Enter first number : 5
int a,b;
Enter second number: 10
void swap(int ,int );
Numbers before function call: 5 10
printf("Enter first number : " );
scanf("%d",&a); Numbers before swapping : 5 10
printf("Enter second number: "); Numbers after swapping : 10 5
scanf("%d",&b); Numbers after function call : 5 10
printf("Numbers before function call: %d\t%d\n",a,b);
swap(a,b);
printf("Numbers after function call : %d\t%d\n",a,b);
return 0;
} void swap(int a, int b)
{
int t;
printf("Numbers before swapping : %d\t%d\n",a,b);
t = a;
a = b;
b = t;
printf("Numbers after swapping : %d\t%d\n",a,b);
35 Department of CSE }
How to swap two numbers using function?
• Values are getting interchanged inside the function. But that is not
getting reflected in main.
36 Department of CSE
How to swap two numbers using function?
#include<stdio.h>
int main() Output:-
{ Enter first number : 5
int a,b;
Enter second number: 10
void swap(int *,int *);
Numbers before function call: 5 10
printf("Enter first number : " );
scanf("%d",&a); Numbers before swapping : 5 10
printf("Enter second number: "); Numbers after swapping : 10 5
scanf("%d",&b); Numbers after function call : 10 5
printf("Numbers before function call: %d\t%d\n",a,b);
swap(&a,&b);
printf("Numbers after function call : %d\t%d\n",a,b);
return 0;
} void swap(int *a, int *b)
{
int t;
printf("Numbers before swapping : %d\t%d\n",*a,*b);
t = *a;
*a = *b;
*b = t;
printf("Numbers after swapping : %d\t%d\n",*a,*b);
37 Department of CSE }
Points to be noted while using Call-by-Reference
Call-by-Value Call-by-Reference
Function Declaration void swap(int ,int ); void swap(int *,int *);
Function Header void swap(int a, int b) void swap(int *a, int *b)
Function Call swap(a,b); swap(&a,&b);
38 Department of CSE
When do you need pointers in functions?
• First scenario – In Call-by-Reference.
• There is a requirement to modify the values of actual arguments.
39 Department of CSE
Passing array as an argument to a function
• When an array is passed as an argument to a function, it is actually
passed as reference.
40 Department of CSE
Sample Code 12 : Passing an array to a function
#include<stdio.h>
int main() void square(int *a,int n)
{ {
int a[5]={1,2,3,4,5}; int i;
int i; for(i=0;i<n;i++)
//First argumnt is an array and second argument is its size a[i] *= a[i];
void square(int *,int); }
printf("Array before modification:-\n");
for(i=0;i<5;i++)
printf("%d\t",a[i]);
square(a,5);
printf("\nArray after modification:-\n");
for(i=0;i<5;i++) Output:-
printf("%d\t",a[i]); Array before modification:-
printf("\n");
return 0;
1 2 3 4 5
} Array after modification:-
1 4 9 16 25
41 Department of CSE
Returning Multiple values from a function
• Normally, a function can return only a single value from it, using
„return‟.
• What if, you have to return two or more values from a function?
42 Department of CSE
Sample Code 13 : Returning Multiple Values
#include<stdio.h> void MinMax(int *a, int n, int *min,int *max)
int main() {
{ int i;
int a[5]; *min = *max = a[0];
void MinMax(int *,int,int*,int*); for(i=1;i<n;i++)
int i,min,max; {
for(i=0;i<5;i++) if(a[i] < (*min))
{ *min = a[i];
printf("Number %d : ",(i+1)); }
scanf("%d",&a[i]); for(i=1;i<n;i++)
} {
MinMax(a,5,&min,&max); if(a[i] > (*max))
printf("Minimum element entered : %d\n",min); *max = a[i];
printf("Maximum element entered : %d\n",max); }
return 0; }
}
43 Department of CSE
Sample Code 13 : Returning Multiple Values - Output
Output:-
Number 1 : 2
Number 2 : 1
Number 3 : 3
Number 4 : 5
Number 5 : 4
Minimum element entered : 1
Maximum element entered : 5
44 Department of CSE
Special Pointers
45 Department of CSE
Void Pointer
• A generic type that is not associated with a reference type.
• It is not the address of a particular data type.
• A pointer with no reference type that can store only address of any
variable.
• Compatible for assignment purposes only with all other types of
pointers.
• A pointer of any reference can be assigned to void type and vice
verse.
• Restriction : It can not be dereferenced unless it is cast.
• Declaration:- void* pvoid;
• General Casting:- dest_ptr = (dest_ptr_type *) source_ptr_name;
46 Department of CSE
NULL Pointer
• A pointer of any type that is assigned the constant NULL
• The reference type of pointer will not change by the assignment of
NULL
• Eg:-
int* iptr = NULL; //NULL pointer of type „int‟
Char* cptr = NULL; //NULL pointer of type „char‟
47 Department of CSE
Dangling Pointer
• Arises during object destruction, when an object that has an incoming reference
is deleted or deallocated, without modifying the value of the pointer, so that the
pointer still points to the memory location of the deallocated memory.
• Example of creating Dangling pointer
int main()
{
char *ptr=NULL;
{
char c;
ptr = &c;
}
}
• c falls out of scope after the inner block making ptr a dangling pointer
48 Department of CSE
Constant pointer
• A pointer that cannot change the address its holding.
• Once a constant pointer points to a variable then it cannot point to any other variable.
• Declaration:- <type of pointer> * const <name of pointer>
• Example:- int* const ptr;
• Sample Code : Will give the error 7: error: assignment of read-only variable „ptr‟
#include<stdio.h>
int main(void)
{
int var1 = 0, var2 = 0;
int *const ptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}
49 Department of CSE
Pointer to a Pointer
• A pointer points to an address of another pointer.
• Also called Double Pointer.
• Declaration:- type **ptr_name;
• Example:- int **p;
• Sample:-
int main()
{
int p=5;
int *p1 = &p;
int **pp;
pp = &p1;
printf(“Value of P : %d\n”,**pp);
return 0;
}
Output : Value of P : 5
50 Department of CSE
Summary
• Discussed about Pointer and its importance.
• Discussed relationship between array and pointer
• Discussed about Call-by-Reference and other places where pointers
are needed for functions.
• Discussed special pointers.
51 Department of CSE
References
• Books/Materials
1. C Programming Course – Compiled HTML Help File
2. Brian W Kernighan, Dennis M Ritchie, “The C Programming
Language”, 2nd Edition, PHI
• Web
1. [Link]
2. [Link]
52 Department of CSE
2.3 DYNAMIC MEMORY
ALLOCATION
1 Department of CSE
Objectives
• Learn how to allocate and free memory, and to control dynamic
arrays of any type of data in general and structures in particular.
2 Department of CSE
Agenda
• Dynamic memory allocation
• Malloc
• Calloc
• Realloc
• free
• Pointer Arithmetic
• Array of pointers
3 Department of CSE
Introduction
• While doing programming, if you are aware about the size of an
array, then it is easy and you can define it as an array.
• For example to store a name of any person, it can go max 100
characters so you can define something as follows:
• char name[100]
• But now let us consider a situation where you have no idea about
the length of the text you need to store, for example you want to
store a detailed description about a topic. Here we need to define
a pointer to character without defining how much memory is
required and later based on requirement we can allocate memory .
4 Department of CSE
Memory Allocation Function
5 Department of CSE
Difference between Static and Dynamic
memory allocation
6 Department of CSE
Introduction
• Creating and maintaining dynamic structures requires dynamic
memory allocation— the ability for a program to obtain more
memory space at execution time to hold new values, and to release space no
longer needed.
7 Department of CSE
Memory Allocation Functions
8 Department of CSE
Syntax
• The following are the function used for dynamic memory allocation
• void *malloc(int num);
• This function allocates an array of num bytes and leave them
uninitialized.
• void *calloc(int num, int size);
• This function allocates an array of num elements each of which
size in bytes will be size.
• void *realloc(void *address, int newsize);
• This function re-allocates memory extending it upto newsize.
• void free(void *address);
• This function releases a block of memory block specified by
address.
9 Department of CSE
Block Memory Allocation (malloc)
• Malloc function allocates a block of memory that contains the
number of bytes specified in its parameter.
• It returns a void pointer to the first byte of the allocated memory
• The allocated memory is not initialized . We should therefore assume
that it will contain unknown values and initialize it as required by our
program.
• The function declaration is as follows
• void* malloc (size_t size)
• If it is not successful malloc return NULL pointer.
• An attempt to allocate memory from heap when memory is
insufficient is known as overflow.
10 Department of CSE
malloc
• It is up to the program to check the memory overflow
• If it doesn't the program produces invalid results or aborts with
an invalid address the first time the pointer is used.
11 Department of CSE
malloc
• Malloc function has one more potential error.
• If we call malloc function with zero size , the results are
unpredictable.
• It may return a NULL pointer
• Never call malloc with a zero size!!!!!
12 Department of CSE
Contiguous Memory Allocation (calloc)
• Calloc is primarily used to allocate memory for arrays.
• It differs from malloc only in that it sets memory to null characters.
• void *calloc (size_t element-count, size_t element-size)
13 Department of CSE
Reallocation of memory(realloc)
• The realloc function can be highly inefficient and should be used
advisedly.
• When given a pointer to the previously allocated block of memory,
realloc changes the size of the block by deleting or extending the
memory at the end of the block.
• If memory cannot be extended because of other allocations, realloc
allocates a completely new block and copies the existing memory
allocation to new allocation, and deletes the old allocation.
• void *realloc (void* ptr, size_t newSize)
14 Department of CSE
realloc
15 Department of CSE
Releasing Memory (free)
• When memory locations allocated by malloc, calloc or realloc are no
longer needed, they should be freed using the predefined function
free.
• void free(void* ptr)
• Below shows the example where first one releases a
single element allocated with malloc
• Second example shows 200 elements were allocated
with calloc . When free the pointer 200 elements are
returned to the heap.
16 Department of CSE
free
17 Department of CSE
Difference between malloc and calloc
[Link] malloc() calloc()
It allocates only single block of requested
1 It allocates multiple blocks of requested memory
memory
int *ptr;ptr = malloc( 20 * sizeof(int) );For int *ptr;Ptr = calloc( 20, 20 * sizeof(int) );For
the above, 20*4 bytes of memory only the above, 20 blocks of memory will be created
2 allocated in one block. and each contains 20*4 bytes of memory.
19 Department of CSE
Example-1
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
} Enter number of elements: 3
printf("Sum=%d",sum);
Enter elements of array: 2 7 1
free(ptr);
return 0; Sum=10
}
25 Department of CSE
Dynamic-ex5.c
Memory Leaks
• A memory leak occurs when allocated memory is never used again
but is not freed.
• I can happen when
• The memory’s address is lost
• The free function is never invoked though it should be
• The problem with memory leak is that the memory cannot be
reclaimed and use later. The amount of memory available t the heap
manager will be decreased.
• If the memory is repeatedly allocated and then lost, then the
program may terminate when more memory is needed but malloc
cannot allocate it because it ran out of memory.
26 Department of CSE
Example
char *chunk;
while(10
{
chunk=(char*) malloc (1000000);
printf(“allocating\n”);
}
• The variable chunk is assigned memory from heap. However this
memory is not freed before another block of memory is assigned to
it.
• Eventfully the application will run out of memory and terminate
abnormally.
27 Department of CSE
POINTER ARITHMETIC
28 Department of CSE
Pointer Arithmetic
• This section introduces the concept of pointer arithmetic, and this
will form one of the very important building blocks in understanding
the functionality of pointers.
29 Department of CSE
Pointer Expressions and Pointer Arithmetic
• Arithmetic operations can be performed on pointers
• Increment/decrement pointer (++ or --)
• Add an integer to a pointer( + or += , - or -=)
• Pointers may be subtracted from each other
• All these operations meaningless unless performed on an array
31 Department of CSE
Pointer Increment – Example - 1
#include<stdio.h>
void main()
{
int n;
int *pn; 2686788 2686792
pn=&n; 2686768 2686776
int *pn1;
pn1=pn+1;
printf("%d %d\n", pn,pn1);
double d;
double *pd;
pd=&d;
double *pd1;
pd1=pd+1;
printf("%d %d\n", pd,pd1);
}
32 Department of CSE
Arithmetic-ex1.c
Incrementing Pointer :
• Incrementing Pointer is generally used in array because we have contiguous
memory in array and we know the contents of next memory location.
• Incrementing Pointer Variable Depends Upon data type of the Pointer variable
33 Department of CSE
Example – 2
#include<stdio.h>
int main()
{
int *ptr=(int *)1000;
printf(“Old Value of ptr : %u",ptr);
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
} Old Value of ptr : 1000
New Value of ptr : 1004
34 Department of CSE
Arithmetic-ex2.c
Difference between two integer Pointers –
Example - 3
#include<stdio.h>
int main(){
printf("\nDifference : %d\n",ptr2-ptr1);
35 Department of CSE
Arithmetic-ex3.c
Explanation
• Ptr1 and Ptr2 are two pointers which holds memory address of Float
Variable.
• Ptr2-Ptr1 will gives us number of floating point numbers that can be
stored.
• ptr2 - ptr1 = (2000 - 1000) / sizeof(float)
• = 1000 / 4
36 Department of CSE
Pointer Division – Example - 4
#include<stdio.h>
int main()
{
int *ptr1,*ptr2;
ptr1 = (int *)1000;
ptr2 = ptr1/4;
return(0);
}
Illegal Use of operator : INVALID
37 Department of CSE
Arithmetic-ex4.c
Pointer Expressions and Pointer Arithmetic-Arrays
• 5 element int array on machine with 4 byte ints
• vPtr points to first element v[ 0 ]
• at location 3000 (vPtr = 3000)
• vPtr += 2; sets vPtr to 3008
• vPtr points to v[ 2 ] (incremented by 2), but the machine has
4 byte ints, so it points to address 3008
Pointer/offset notation
*( bPtr + 0 ) = 10
*( bPtr + 1 ) = 20
*( bPtr + 2 ) = 30
*( bPtr + 3 ) = 40
1
2 Copying a string using array notation and pointer notation. */
3 #include <stdio.h>
4
5 void copy1( char * const s1, const char * const s2 ); /* prototype */
6 void copy2( char *s1, const char *s2 ); /* prototype */
7
8 int main( void )
9 {
10 char string1[ 10 ]; /* create array string1 */
11 char *string2 = "Hello"; /* create a pointer to a string */
12 char string3[ 10 ]; /* create array string3 */
13 char string4[] = "Good Bye"; /* create a pointer to a string */
14
15 copy1( string1, string2 );
16 printf( "string1 = %s\n", string1 );
17
18 copy2( string3, string4 );
19 printf( "string3 = %s\n", string3 );
20
21 return 0; /* indicates successful termination */
22
23 } /* end main */
24
25 /* copy s2 to s1 using array notation */
26 void copy1( char * const s1, const char * const s2 )
27 {
28 int i; /* counter */
29
30 /* loop through strings */
31 for ( i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ ) {
32 ; /* do nothing in body */
33 } /* end for */
34
35 } /* end function copy1 */
36 Condition of for loop
37 /* copy s2 to s1 using pointer actually performs an action
notation */
38 void copy2( char *s1, const char *s2 )
39 {
40 /* loop through strings */
41 for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ ) {
42 ; /* do nothing in body */
43 } /* end for */
44
45 } /* end function copy2 */
string1 = Hello
string3 = Good Bye
ARRAY OF POINTERS
48 Department of CSE
Introduction
• An array of pointer is similar to an array of ant predefined data type
• As a pointer variable always contain an address, an array of pointer is
a collection of addresses.
• These can be address of ordinary isolated variable or of array
elements.
• The elements of an array of pointers are stored in the memory just
like elements of any other kind of array.
• Example is given below..
Arraypointer-ex1.c
Example - 1
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX]; //array of pointers
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0; Value of var[0] = 10
Value of var[1] = 100
} Value of var[2] = 200
Example - 2
#include<stdio.h>
void main()
{
int arr[3]={1,2,3};
int i, *ptr[3];
for(i=0;i<3;i++)
0028FF30 1
ptr[i]=arr+i; 0028FF34 2
for(i=0;i<3;i++) 0028FF38 3
51
Arraypointer-ex2.c
Department of CSE
Arrays of Pointers - Strings
• Arrays can contain pointers
• For example: an array of strings
char *suit[ 4 ] = { "Hearts", "Diamonds",
"Clubs", "Spades" };
• Strings are pointers to the first character
• char * – each element of suit is a pointer to a char
• The strings are not actually stored in the array suit, only pointers to
the strings are stored
• suit array has a fixed size, but strings can be of any size
Case study: Roman numeral equivalents – Example
-3
#include <stdio.h>
56 Department of CSE
Try it Yourself –Ans - Student mark
#include<stdio.h>
#include<stdlib.h>
void main()
{
int no, *pt,i;
clrscr();
57 Department of CSE
Student mark
printf("* * * * Enter roll no of students. * * * *\n");
for (i=0;i<no;i++)
{
printf("-->");
scanf("%d",(pt+i));
}
58 Department of CSE
Structures and Unions
Structure
A structure is a user defined data type. We know that arrays can be used to
represent a group of data items that belong to the same type, such as int or float. However
we cannot use an array if we want to represent a collection of data items of different types
using a single name. A structure is a convenient tool for handling a group of logically related
data items.
Structure is a user defined data type used to represent a group of data items of
different types using a single name.
struct student
{
int rollno;
char name[25];
float totalmark;
};
SSASGFGC@Hospet Page 1
Structures and Unions
Thus, the stud1 and stud2 are structure variables of type student. The above
structure can hold information of 2 students.
struct structure_name
{
type element 1;
type element 2;
……………..
type element n;
} var1,var2,…,varn;
The following single declaration is equivalent to the two declaration presented in the
previous example.
struct student
{
int rollno;
char name[25];
float totalmark;
} stud1, stud2;
Example:
In the above example stud1 is a structure variable of type student. To access the
member name, we would write [Link]. Similarly, stud1’s rollno and stud1’s totalmark
can be accessed by writing [Link] and [Link] respectively.
SSASGFGC@Hospet Page 2
Structures and Unions
#include<conio.h>
void main()
{
struct student
{
char *name;
int rollno;
float totalmark;
};
struct student stud1={"Venkat",1,98};
struct student stud3= {"Shweta",3,97};
struct student stud2={"Arpita",2,99};
clrscr();
printf(“STUDENTS DETAILS:\n”);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, [Link], [Link],
[Link]);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, [Link], [Link],
[Link]);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, [Link], [Link],
[Link]);
getch();
}
Output
STUDENTS DETAILS:
Roll number: 1
Name: Venkat
Total Marks:98.000000
Roll number: 2
Name: Arpita
Total Marks:99.000000
Roll number: 2
Name:Shweta
Total Marks:99.000000
Array of structures:
It is possible to store a structure has an array element. i.e., an array in which each
element is a structure. Just as arrays of any basic type of variable are allowed, so are arrays
of a given type of structure. Although a structure contains many different types, the
compiler never gets to know this information because it is hidden away inside a sealed
structure capsule, so it can believe that all the elements in the array have the same type,
even though that type is itself made up of lots of different types.
SSASGFGC@Hospet Page 3
Structures and Unions
struct struct_name
{
type element 1;
type element 2;
……………..
type element n;
}array name[size];
Example:
struct student
{
int rollno;
char name[25];
float totalmark;
} stud[100];
int n,i;
clrscr();
printf("Enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter details of %d-th student\n",i+1);
printf("Name:\n");
scanf("%s",&stud[i].name);
printf("Roll number:\n");
scanf("%d",&stud[i].rollno);
printf("Total mark:\n");
scanf("%d",&stud[i].totalmark);
}
SSASGFGC@Hospet Page 4
Structures and Unions
printf("STUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRoll number:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Total mark:%d\n",stud[i].totalmark);
}
getch();
}
OUTPUT
Enter total number of students:
3
STUDENTS DETAILS:
Roll number:11
Name: SUBAHAS
Total mark:589
Roll number:12
Name: RUKSANA
Total mark:594
Roll number:13
Name: SANA
Total mark:595
SSASGFGC@Hospet Page 5
Structures and Unions
declaration of the embedded structure must appear before the declaration of the outer
structure. For example
#include <stdio.h>
#include <conio.h>
void main()
{
struct dob
{
int day;
int month;
int year;
};
struct student
{
struct dob d;
int rollno;
char name[25];
int totalmark;
}stud[25];
int n,i;
clrscr();
printf("Enter total number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEnter details of %d student",i+1);
printf("\nName:");
scanf("%s",&stud[i].name);
printf("\nRoll number:");
scanf("%d",&stud[i].rollno);
printf("\nTotal mark:");
scanf("%d",&stud[i].totalmark);
printf("\nDate of birth (Format:01 06 2010):");
scanf("%d%d%d",&stud[i].[Link],&stud[i].[Link],&stud[i].[Link]);
}
printf("\nSTUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
SSASGFGC@Hospet Page 6
Structures and Unions
printf("\nRoll number:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Total mark:%d\n",stud[i].totalmark);
printf("Date of birth : %d / %d / %d \n\n",
stud[i].[Link],stud[i].[Link],stud[i].[Link]);
}
getch();
}
OUTPUT
Enter total number of students 2
STUDENTS DETAILS:
Roll number:12
Name: karthik
Total mark: 588
Date of birth : 11 / 12 / 1997
Roll number:18
Name: sarita
Total mark:598
Date of birth : 1 / 2 / 1997
Union
Union is a user created data type similar to structure but in this case all the members
share a common memory location. The size of the union corresponds to the length of the
largest member. Since the member share a common location they have the same starting
address.
SSASGFGC@Hospet Page 7
Structures and Unions
The real purpose of unions is to prevent memory fragmentation by arranging for a
standard size for data in the memory. By having a standard data size we can guarantee that
any hole left when dynamically allocated memory is freed will always be reusable by
another instance of the same type of union. This is a natural strategy in system
programming where many instances of different kinds of variables with a related purpose
and stored dynamically.
A union is declared in the same way as a structure. The syntax of union declaration is
union union_name
{
type element 1;
type element 2;
……………..
type element n;
};
For example, the following code declares a union data type called Student and a
union variable called stud:
union student
{
int rollno;
float totalmark;
};
union student stud;
It is possible to combine the declaration of union combination with that of the union
variables, as shown below.
union union_name
{
type element 1;
type element 2;
……………..
type element n;
}var1,var2,…,varn;
The following single declaration is equivalent to the two declaration presented in the
previous example.
union student
{
int rollno;
float totalmark;
SSASGFGC@Hospet Page 8
Structures and Unions
}x,y,z;
Structure Union
The amount of memory required to store a The amount of memory required is always equal
structure variable is the sum of the size of all the to that required by its largest member.
members.
Each member have their own memory space. One block is used by all the member of the
union.
Within a structure all members gets memory While retrieving data from a union the type
allocated; therefore any member can be that is being retrieved must be the type most
retrieved at any time. recently stored. It is the programmer's
responsibility to keep track of which type is
currently stored in a union; the results are
implementation-dependent if something is
stored as one type and extracted as another.
One or more members of a structure can be A union may only be initialized with a value
initialized at once. of the type of its first member; thus union u
described above (during example
declaration) can only be initialized with an
integer value.
Structure:
#include<stdio.h>
#include<conio.h>
void main()
{
struct testing
{
SSASGFGC@Hospet Page 9
Structures and Unions
int a;
char b;
float c;
}var;
clrscr();
printf(“\nsizeof(var) is %d”,sizeof(var));
printf(“\nsizeof(var.a) is %d”,sizeof(var.a));
printf(“\nsizeof(var.b) is %d”,sizeof(var.b));
printf(“\nsizeof(var.c) is %d”,sizeof(var.c));
var.a=10;
printf(“\nvalue of var.a is %d”,var.a);
var.b=’b’;
printf(“\nvalue of var.b is %c”,var.b);
var.c=15.55;
printf(“\nvalue of var.c is %f”,var.c);
printf(“\nvalue of var.a is %d”,var.a);
printf(“\nvalue of var.b is %c”,var.b);
printf(“\nvalue of var.c is %f”,var.c);
getch();
}
OUTPUT
sizeof(var) is 7
sizeof(var.a) is 2
sizeof(var.b) is 1
sizeof(var.c) is 4
value of var.a is 10
value of var.b is b
value of var.c is 15.550000
value of var.a is 10
value of var.b is b
value of var.c is 15.550000
Union:
#include<stdio.h>
#include<conio.h>
void main()
{
union testing
{
SSASGFGC@Hospet Page 10
Structures and Unions
int a;
char b;
float c;
}var;
clrscr();
printf(“\nsizeof(var) is %d”,sizeof(var));
printf(“\nsizeof(var.a) is %d”,sizeof(var.a));
printf(“\nsizeof(var.b) is %d”,sizeof(var.b));
printf(“\nsizeof(var.c) is %d”,sizeof(var.c));
var.a=10;
printf(“\nvalue of var.a is %d”,var.a);
var.b=’b’;
printf(“\nvalue of var.b is %c”,var.b);
var.c=15.55;
printf(“\nvalue of var.a is %f”,var.c);
printf(“\nvalue of var.a is %d”,var.a);
printf(“\nvalue of var.b is %c”,var.b);
printf(“\nvalue of var.c is %f”,var.c);
getch();
}
OUTPUT
sizeof(var) is 4
sizeof(var.a) is 2
sizeof(var.b) is 1
sizeof(var.c) is 4
value of var.a is 10
value of var.b is b
value of var.c is 15.550000
value of var.a is -13458
value of var.b is
value of var.c is 15.550000
SSASGFGC@Hospet Page 11
File Handling in C Language
What is file?
File is a collection of bytes that is stored on secondary storage devices like disk. There are two kinds
of files in a system. They are,
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
fopen() function is used to open a file to perform operations such as reading, writing etc. In
a C program, we declare a file pointer and use fopen() as below. fopen() function creates a new file
if the mentioned file name does not [Link] *fp;
General Syntax : *fp = FILE *fopen(const char *filename, const char *mode);
Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on the file. Example: r, w, a, r+, w+ and a+. Please refer
below the description for these mode of operations.
Closing a file
fclose() function closes the file that is being pointed by file pointer fp. In a C program, we close a file
as below.
General Syntax : int fclose(FILE *fp);
fclose (fp);
fprintf()
fprintf() function writes string into a file pointed by fp. In a C program, we write string into a file as
below.
General Syntax : int fprintf(FILE *fp, const char *format, …);
mode description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
// Program to write 5 names in File and read from file and display on screen.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char name[30];
int i;
clrscr();
fp=fopen("[Link]","a+");
for(i=0;i<5;i++)
{
printf("\n\t Name :-");
scanf("%s",&name);
fprintf(fp,"%s",name);
fprintf(fp,"\n"," ");
}
fp=fopen("[Link]","r");
while(!feof(fp))
{
fscanf(fp,"%s",name);
printf("\n %s",name);
}
getch();
}
3 Asst. Prof. P. M. Patil
File Handling in C Language
Following program reads a character from user and write in to file [Link].
# include<stdio.h>
# include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("[Link]", "w");
printf("Enter data");
while( (ch = getchar()) != EOF)
{
putc(ch,fp);
}
fclose(fp);
fp = fopen("[Link]", "r");
while( (ch = getc(fp)! = EOF)
printf("%c",ch);
fclose(fp);
}
#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};
void main()
{
struct emp e;
FILE *p,*q;
4 Asst. Prof. P. M. Patil
File Handling in C Language
p = fopen("[Link]", "a");
q = fopen("[Link]", "r");
printf("Enter Name and Age");
scanf("%s %d", [Link], &[Link]);
fprintf(p,"%s %d", [Link], [Link]);
fclose(p);
do
{
fscanf(q,"%s %d", [Link], [Link]);
printf("%s %d", [Link], [Link]);
}
while( !feof(q) );
getch();
}
In this program, we have create two FILE pointers and both are referring to the same file but
in different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file, which can
then be printed on console usinf standard printf() function.
#include <stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2;
char name[30];
clrscr();
fp1=fopen("[Link]","r");
fp2=fopen("[Link]","w");
while(!feof(fp1))
{
fscanf(fp1,"%s",name);
fprintf(fp2,"%s",name);
}
FILE HANDLING
A file is a collection of bytes stored on a secondary storage device, which is
generally a disk of some kind. The collection of bytes may be interpreted, for
example, as characters, words, lines, paragraphs and pages from a textual
document; fields and records belonging to a database; or pixels from a graphical
image.
The meaning attached to a particular file is determined entirely by the data
structures and operations used by a program to process the file. It is conceivable
(and it sometimes happens) that a graphics file will be read and displayed by a
program designed to process textual data.
The result is that no meaningful output occurs (probably) and this is to be
expected. A file is simply a machine decipherable storage media where
programs and data are stored for machine usage.
File Operations
In programming, we may require some specific input data to be generated
several numbers of times. Sometimes, it is not enough to only display the data
on the console. The data to be displayed may be very large, and only a limited
amount of data can be displayed on the console, and since the memory is
volatile, it is impossible to recover the programmatically generated data again
and again.
However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in
C.
File handling in C enables us to create, update, read, and delete the files stored
on the local file system through our C program. The following operations can be
performed on a file.
Creation of the new file
Opening an existing file
Reading from the file
Writing to the file
Deleting the file
Types of Files
There are two kinds of files in which data can be stored in two ways either in
characters coded in their ASCII character set or in binary format. They are
1. Text Files (or) ASCII file
2. Binary Files
Text Files (or) ASCII file
The file that contains ASCII codes of data like digits, alphabets and symbols is
called text file (or) ASCII file.
Binary Files
A binary file is a file that uses all 8 bits of a byte for storing the information .It is
the form which can be interpreted and understood by the computer.
The only difference between the text file and binary file is the data contain in
text file can be recognized by the word processor while binary file data can’t be
recognized by a word processor.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
1. wb(write)
This opens a binary file in write mode.
SYNTAX: fp=fopen(“[Link]”,”wb”);
2. rb(read)
This opens a binary file in read mode
SYNTAX:fp=fopen(“[Link]”,”rb”);
3. ab(append)
This opens a binary file in a Append mode i.e. data can be added at the end
of file.
SYNTAX: fp=fopen(“[Link]”,”ab”);
4. r+b(read+write)
This mode opens preexisting File in read and write mode.
SYNTAX: fp=fopen(“[Link]”,”r+b”);
5. w+b(write+read)
This mode creates a new file for reading and writing in Binary mode.
SYNTAX: fp=fopen(“[Link]”,”w+b”);
6. a+b(append+write)
This mode opens a file in append mode i.e. data can be written at the end of
file.
SYNTAX: fp=fopen(“[Link]”,”a+b”);
Opening Modes in Standard I/O
r Open for reading If the file does not exist, fopen() returns
NULL
rb Open for reading in binary If the file does not exist, fopen() returns
mode. NULL.
w Open for writing. If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wb Open for writing in binary If the file exists, its contents are overwritten.
mode. If the file does not exist, it will be created.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
a Open for append. i.e, Data is If the file does not exists, it will be created.
added to the end of file.
ab Open for append in binary If the file does not exists, it will be created.
mode. i.e, Data is added to
end of file.
r+ Open for both reading and If the file does not exist, fopen() returns
writing. NULL.
rb+ Open for both reading and If the file does not exist, fopen() returns
writing in binary file. NULL
w+ Open for both reading and If the file exists, its contents are overwritten.
writing. If the file does not exist, it will be created.
wb+ Open for both reading and If the file exists, its contents are overwritten.
writing in binary mode. If the file does not exist, it will be created.
a+ Open for both reading and If the file does not exists, it will be created.
appending.
ab+ Open for both reading and If the file does not exists, it will be created.
appending in binary mode.
FILE *fptr;
fptr = fopen(“C:\\[Link]”,”w”);
if(fptr == NULL)
{
printf(“Error!”);
exit(1);
}
printf(“Enter num: “);
scanf(“%d”,&num);
fprintf(fptr,”%d”,num);
fclose(fptr);
return 0;
}
This program takes a number from user and stores in the file [Link]. After
you compile and run this program, you can see a text file [Link] created in
C drive of your computer. When you open the file, you can see the integer you
entered.
Reading from a text file
Program 2.21: Read from a text file using fscanf()
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen(“C:\\[Link]”,”r”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
fscanf(fptr,”%d”, &num);
printf(“Value of n=%d”, num);
fclose(fptr);
return 0;
}
Reading and writing to a binary file
Functions fread() and fwrite() are used for reading from and writing to a file on
the disk respectively in case of binary files.
Writing to a binary file
To write into a binary file, you need to use the function fwrite(). The functions
takes four arguments: Address of data to be written in disk, Size of data to be
written in disk, number of such type of data and pointer to the file where you
want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Program 2.22: Writing to a binary file using fwrite()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen(“C:\\[Link]”,”wb”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
We declare a structure three Num with three numbers - n1, n2 and n3, and
define it in the main function as num. Now, inside the for loop, we store the
value into the file using fwrite.
The first parameter takes the address of num and the second parameter takes the
size of the structure three Num. Since, we’re only inserting one instance of num,
the third parameter is 1. And, the last parameter *fptr points to the file we’re
storing the data. Finally, we close the file.
Reading from a binary file
Function fread() also take 4 arguments similar to fwrite() function as above.
fread(address_data,size_data,numbers_data,pointer_to_file);
Program 2.23: Reading from a binary file using fread()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
1. fopen () : It creates a new file for use or opens an existing file for use.
2. fclose (): It closes a file which has been opened for use.
3. fscanf( file pointer, format string, address of the variable)
Example: fscanf(fptr,”%d”, &num);
4. fprintf(console output, “format string”, file pointer);
Example: fprintf(stdout, “%f \n”, f); /*note: stdout refers to screen */
5. getw (): This function returns the integer value from a given file and increment the
file pointer position to the next message.
Syntax: getw (fptr);
Where fptr is a file pointer which takes the integer value from file.
6. putw (): This function is used for writing an integer value to a given file.
Syntax: putw (value,fptr);
Where fptr is a file pointer Value is an integer value which is written to a given file.
Example Program for getw() and putw()
Program 2.24: Write a program to read integer data from the user and write it
into the file using putw() and read the same integer data from the file using getw()
and display it on the output screen.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
int n;
clrscr();
fp=fopen(“[Link]”, “wb+”);
printf(“Enter the integer data”);
scanf(“%d”,&n);
while(n!=0)
{
putw(n,fp);
scanf(“%d”,&n);
}
rewind(fp);
printf(“Reading data from file”);
while((n=getw(fp))!=EOF)
{
printf(“%d\n”,n);
}
fclose(fp);
getch();
}
7. fwrite()
This function is used for writing an entire block to a given file.
Syntax: fwrite(ptr,size,nst,fptr);
ptr is a pointer ,it points to the array of structure.
Size is the size of the structure
nst is the number of the structure
fptr is a filepointer.
8. fread()
fread(ptr,size,position,fptr);similar to fwrite
9. fflush(stdin);To clean the input stream
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
3. rewind()
fseek() : Getting data using fseek()
When many records inside a file and need to access a record at a specific
position, you need to loop through all the records before it to get the record. This
will waste a lot of memory and operation time. An easier way to get to the
required data can be achieved using fseek().
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)
fseek(file pointer, displacement, pointer position);
The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location
where the offset starts.
This function is used for seeking the pointer position in the file at the specified
byte.
Syntax: fseek( file pointer, displacement, pointer position);
file pointer - It is the pointer which points to the file.
displacement -It is positive or negative.
This is the number of bytes which are skipped backward (if negative) or forward
(if positive) from the current position. This is attached with L because this is a
long integer.
Pointer position: This sets the pointer position in the file.
Value Pointer position Value Pointer position
0 Beginning of file.
1 Current position
2 End of file
Example:
1. fseek( p,10L,0)
This 0 means pointer position is on beginning of the file, from this statement
pointer position is skipped 10 bytes from the beginning of the file.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
2. fseek( p,5L,1)
This 1 means current position of the pointer position. From this statement
pointer position is skipped 5 bytes forward from the current position.
3. fseek(p,-5L,1):
From this statement pointer position is skipped 5 bytes backward from the
current position.
PREPROCESSOR DIRECTIVES
The C preprocessor is a microprocessor that is used by compiler to transform
your code before compilation. It is called micro preprocessor because it allows
us to add macros.
Note: A macro is a segment of code which is replaced by the value of macro.
Macro is defined by #define directive.
Example
#define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
All preprocessor directives starts with hash # symbol. Let's see a list of
preprocessor directives.
#define: It substitutes a preprocessor using macro.
#include: It helps to insert a certain header from another file.
#undef: It undefines a certain preprocessor macro.
#ifdef: It returns true if a certain macro is defined.
#ifndef: It returns true if a certain macro is not defined.
#if, #elif, #else, and #endif: It tests the program using a certain condition;
these directives can be nested too.
#line: It handles the line numbers on the errors and warnings. It can be used
to change the line number and source files while generating output during
compile time.
#error and #warning: It can be used for generating errors and warnings.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
• Some constants
M_E The base of natural logarithms
M_PI Value of π
M_SQRT2 Square root of 2
Output
> [Link]
[Link]: No such file or directory
if (pos)
printf("The string \"%s\" was found.\n", pos);
char buf[128];
strftime(buf, sizeof(buf),
"Date: %e %B %Y, Time: %H:%M %Z", now);
printf("strftime custom formatting: %s\n", buf);
}
Epoch time: 1405894768
Manual formatting: The date is 7/20/2014.
asctime formatting: Sun Jul 20 18:19:28 2014
strftime custom formatting: Date: 20 July 2014, Time: 18:19 EDT
CSC230: C and Software Tools © NC State University Computer Science Faculty 19
UNIX, POSIX, and you
• UNIX: The defining operating system of the 20th
century, created by Kernigan and Ritchie
(the C guys)
– Many descendants still in use today (HP-UX, Solaris, AIX,
*BSD, Mac OS X, Linux)
• POSIX: A standard where a bunch of UNIXy types
got together and standardized their APIs
• Even Windows supports the core of POSIX
• POSIX is not core C99, but it’s pretty much as well
supported.