0% found this document useful (0 votes)
8 views

Problem Solving Through C Programming

Problem solving through C programming

Uploaded by

katarahimanshu14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Problem Solving Through C Programming

Problem solving through C programming

Uploaded by

katarahimanshu14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

3.

.056
Problem Solving
Through C
Programming

[Type text] Manoj Pandya


Page 1
+91 - 9460378169
2
Problem Solving Through C Programming

UNIT - I

Algorithm development: Definition and properties of algorithms, flow charts symbols, Types
of flow chart, testing and debugging, Example of simple algorithms and flow chart. Program
Development Cycle, Program design, Errors : syntax error , runtime error, logical error.

UNIT – II

Programming in C: structure of C programs, compilation and execution of C programs,


character set, keywords, data types , constants, symbolic constants and variables, expressions.
Operators : Assignment , Arithmetic , Relational , Logical, Conditional , comma , Increment/
Decrement, Bitwise, sizeof operator , Compound assignment operators. Associativity and
precedence of C operators. Input/ output statements. Control statements - if-else, switch.

UNIT – III

Loops: for, while, do-while .Nested loops and combined loops. Break and Continue statements.
C preprocessor: Symbolic constants, macro substitution - Simple, Argumented , Nested.

UNIT – IV

Functions: built-in and user-defined functions, function declaration , Advantages of user defined
functions. Category of functions. parameter passing- call by value & call by reference, recursive
functions.
Array: Creating of one dimensional array, initialization , Accessing elements of 1 D array.
Two dimensional array ,initialization , Accessing elements of 2D array. Array and strings,
string-handling functions.

UNIT – V

Pointers: pointer variable and its importance, pointer arithmetic, array of pointers, function of
pointers, structure of pointers, dynamic memory allocation functions.
Structures and Union: Declaration of structures, initialization and accessing structure members.
Function and structures , Array of structure, self-referential structure, unions, enumeration.
File Input/Output: Create, Open, Read, Write, Delete, Close.

2 Manoj Pandya
+91-9460378169
3
Problem Solving Through C Programming

Unit - I

3 Manoj Pandya
+91-9460378169
4
Problem Solving Through C Programming

Algorithm Development:-

Definition:-
An algorithm is a step by step method of solving a problem. It is
commonly used for data processing, calculation and other related computer and mathematical
operations.

Properties:-
An algorithm must satisfy the following properties:-
Input:- The algorithm must have input values from a specified set.
Output:- The algorithm must procedure the output values from a specified set of input values.
The output values are the solution to a problem.
Finiteness:- For any input, the algorithm must terminate after a finite number of steps.
Definiteness:- All steps of the algorithm must be precisely defined.
Effectiveness:- It must be possible to perform each step of the algorithm correctly and in a finite
amount of time.

Problem1: Write algorithm to find the greater number between two numbers
Step1: Start
Step2: Read/input A and B
Step3: If A greater than B then C=A
Step4: if B greater than A then C=B
Step5: Print C
Step6: End

Problem2: An algorithm to find the largest value of any three numbers.


Step1: Start
Step2: Read/input A,B and C
Step3: If (A>=B) and (A>=C) then Max=A
Step4: If (B>=A) and (B>=C) then Max=B
Step5: If (C>=A) and (C>=B) then Max=C
Step6: Print Max
Step7: End

Problem3: An algorithm to calculate even numbers between 0 and 99


Step1: Start
Step2: I ← 0
Step3: Write I in standard output
Step4: I ← I+2
Step5: If (I <=98) then go to line 3
Step6: End

4 Manoj Pandya
+91-9460378169
5
Problem Solving Through C Programming

Problem4: Design an algorithm which gets a natural value, n, as its input and calculates odd numbers
equal or less than n. Then write them in the standard output:

Step1: Start
Step2: Read n
Step3: I ← 1
Step4: Write I
Step5: I ← I + 2
Step6: If ( I <= n) then go to line 4
Step7: End

Problem5: Design an algorithm which generates even numbers between 1000 and 2000 and then prints
them in the standard output. It should also print total sum:
Step1: Start
Step2: I ← 1000 and S ← 0
Step3: Write I
Step4: S ← S + I
Step5: I ← I + 2
Step6: If (I <= 2000) then go to line 3 else go to line 7
Step7: Write S
Step8: End

Problem6: Design an algorithm with a natural number, n, as its input which calculates the following
formula and writes the result in the standard output: S = ½ + ¼ + … +1/n

Step1: Start
Step2: Read n
Step3: I ← 2 and S ← 0
Step4: S= S + 1/I
Step5: I ← I + 2
Step6: If (I <= n) then go to line 4 else write S in standard output
Step7: End

Flow Chart:-
A flowchart is a type of diagram that represents a workflow or process. A
flowchart can also be defined as a diagrammatic representation of an algorithm, a step-by-step
approach to solving a task.
The flowchart shows the steps as boxes of various kinds, and their order
by connecting the boxes with arrows. This diagrammatic representation illustrates a solution
model to a given problem. Flowcharts are used in analyzing, designing, documenting or
managing a process or program in various fields.
5 Manoj Pandya
+91-9460378169
6
Problem Solving Through C Programming

Nowadays, flowcharts play an extremely important role in displaying


information and assisting reasoning. They help us visualize complex processes, or make explicit
the structure of problems and tasks. A flowchart can also be used to define a process or project to
be implemented.

Flowchart Symbols:-

There are 6 basic symbols commonly used in flowcharting of


assembly language Programs: Terminal, Process, input/output, Decision, Connector and
Predefined Process. This is not a complete list of all the possible flowcharting symbols, it is the
ones used most often in the structure of Assembly language programming.

6 Manoj Pandya
+91-9460378169
7
Problem Solving Through C Programming

General rules for flowcharting:-

1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points.
The exit point for all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown
as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
• From one page to another page.
• From the bottom of the page to the top of the same page.
• An upward flow of more than 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.

Problem1: Find the area of a circle of radius r.

7 Manoj Pandya
+91-9460378169
8
Problem Solving Through C Programming

Problem2: Convert temperature Fahrenheit to Celsius.

Problem3: Algorithm for find the greater number between two numbers.

8 Manoj Pandya
+91-9460378169
9
Problem Solving Through C Programming

Problem4: Flowchart for the problem of printing even numbers between 9 and 100:

Problem5: Flowchart for the problem of printing odd numbers less than a given number. It should
also calculate their sum and count.

9 Manoj Pandya
+91-9460378169
10
Problem Solving Through C Programming

Problem6: Flowchart for the calculate the average from 25 exam scores.

Types of Flow Chart:-


Flowcharts are as unique as snowflakes. And while the variations
are endless, there are four flowchart types that are particularly versatile and can be used for
describing business, manufacturing or administrative processes, seeing how an organization
functions, how different departments work together and much more.

10 Manoj Pandya
+91-9460378169
11
Problem Solving Through C Programming

1. Process Flowchart: Illustrate the way a manufacturing, administrative or service


process works or plan out a project.

A process flowchart is probably the most versatile of the four commonly used
flowchart types and can be applied to virtually anything. It can be used for mapping out roles and
responsibilities within an organization to gain clarity, for drawing up a proposal for a new
process or project, or for showing the way you wake up in the morning (shown below). The
possibilities are endless.

2. Swimlane Flowchart: Describe how separate departments, processes or employees


interact.

A swimlane flowchart comes in handy when you need to show multiple things
side by side. The below example illustrates the way an internal-facing department runs parallel
with an external-facing one and at what point they come in contact with each other.

11 Manoj Pandya
+91-9460378169
12
Problem Solving Through C Programming

3. Workflow Chart: Understand data and document flow within your organization.

A workflow chart shows the way a business or process functions. The below
example illustrates the steps required for a potential customer to renew a policy through a
company website. This type of flowchart can be used to train new employees, to discover
potential problem areas, and to clarify business operations by showing a high-level overview.

12 Manoj Pandya
+91-9460378169
13
Problem Solving Through C Programming

4. Data Flowchart: See where data flows in and out of an information system or business.

A data flowchart shows the way data is processed. It comes in handy when
you want to design or analyze a system. Although most often used for software, it can be used to
analyze any type of information flow. The below example shows a typical sales funnel. In this
case the “data” is consumer behavior.

13 Manoj Pandya
+91-9460378169
14
Problem Solving Through C Programming

Testing and Debugging:-


Testing is a process of finding bugs or errors in a software
product that is done manually by tester or can be automated.

Debugging is a process of fixing the bugs found in testing


phase. Programmer or developer is responsible for debugging and it can’t be automated.

Difference Between Testing and Debugging:-

Testing Debugging
The purpose of testing is to find bugs and The purpose of debugging is to correct
errors. those bugs found during testing.
Debugging is done by programmer or
Testing is done by tester.
developer.
It can be automated. It can’t be automated.
It must be done only by insider i.e.
It can be done by outsider like client.
programmer.
Most of the testing can be done without Debugging can’t be done without proper
design knowledge. design knowledge.

14 Manoj Pandya
+91-9460378169
15
Problem Solving Through C Programming

Program Development Life Cycle:-

When we want to develop a program using any programming


language, we follow a sequence of steps. These steps are called phases in program development.
The program development life cycle is a set of steps or phases that are used to develop a program
in any programming language.

Generally, program development life cycle contains 6 phases, they are as follows:-

 Problem Definition
 Problem Analysis
 Algorithm Development
 Coding & Documentation
 Testing & Debugging
 Maintenance

15 Manoj Pandya
+91-9460378169
16
Problem Solving Through C Programming

1. Problem Definition:-

In this phase, we define the problem statement and we decide the


boundaries of the problem. In this phase we need to understand the problem statement, what is
our requirement, what should be the output of the problem solution. These are defined in this
first phase of the program development life cycle.

2. Problem Analysis:-

In phase 2, we determine the requirements like variables, functions,


etc. to solve the problem. That means we gather the required resources to solve the problem
defined in the problem definition phase. We also determine the bounds of the solution.

3. Algorithm Development:-

During this phase, we develop a step by step procedure to solve the


problem using the specification given in the previous phase. This phase is very important for
program development. That means we write the solution in step by step statements.

4. Coding & Documentation:-

This phase uses a programming language to write or implement


actual programming instructions for the steps defined in the previous phase. In this phase, we
construct actual program. That means we write the program to solve the given problem using
programming languages like C, C++, Java etc.,

5. Testing & Debugging:-

During this phase, we check whether the code written in previous step
is solving the specified problem or not. That means we test the program whether it is solving the
problem for various input data values or not. We also test that whether it is providing the desired
output or not.

6. Maintenance:-

During this phase, the program is actively used by the users. If any
enhancements found in this phase, all the phases are to be repeated again to make the
enhancements. That means in this phase, the solution (program) is used by the end user. If the
user encounters any problem or wants any enhancement, then we need to repeat all the phases
from the starting, so that the encountered problem is solved or enhancement is added.

Program Design:-
A process that an organization uses to develop a program. It is most often an
iterative process involving research, consultation, initial design, testing and redesign. A program
design is the plan of action that results from that process.
16 Manoj Pandya
+91-9460378169
17
Problem Solving Through C Programming

Errors:-
Error is an illegal operation performed by the user which results in abnormal
working of the program. Programming errors often remain undetected until the program is
compiled or executed. Some of the errors inhibit the program from getting compiled or executed.
Thus errors should be removed before compiling and executing.

Types of Errors:-

Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax
are known as syntax errors. This compiler error indicates something that must be fixed before the
code can be compiled. All these errors are detected by compiler and thus are known as compile-
time errors. Most frequent syntax errors are:

 Missing Parenthesis (})


 Printing the value of variable without declaring it
 Missing semicolon
 Syntax of a basic construct is written wrong. For example : while loop

Run-time Errors: Errors which occur during program execution(run-time) after successful
compilation are called run-time errors. One of the most common run-time error is division by
zero also known as Division error. These types of error are hard to find as the compiler doesn’t
point to the line at which the error occurs.

Logical Errors: On compilation and execution of a program, desired output is not


obtained when certain input values are given. These types of errors which provide incorrect
output but appears to be error free are called logical errors. These are one of the most common
errors done by beginners of programming. These errors solely depend on the logical thinking of
the programmer and are easy to detect if we follow the line of execution and determine why the
program takes that path of execution.

Linker Errors: These error occurs when after compilation we link the different
object files with main’s object using Ctrl+F9 key(RUN). These are errors generated when the
executable of the program cannot be generated. This may be due to wrong function prototyping,
incorrect header files. One of the most common linker error is writing Main() instead of main().

Semantic errors: This error occurs when the statements written in the program are not
meaningful to the compiler.
Ex:- a + b = c; //semantic error

17 Manoj Pandya
+91-9460378169
18
Problem Solving Through C Programming

Unit - II

18 Manoj Pandya
+91-9460378169
19
Problem Solving Through C Programming

Programming in C:-

Structure of C programs:-

Documentation section: The documentation section consists of a set of comment lines


giving the name of the program, the author and other details, which the programmer would
like to use later.

Link section: The link section provides instructions to the compiler to link functions from
the system library such as using the #include directive.

Definition section: The definition section defines all symbolic constants such using the
#define directive.

Global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global declaration
section that is outside of all the functions. This section also declares all the user-defined
functions.

19 Manoj Pandya
+91-9460378169
20
Problem Solving Through C Programming

main() function section: Every C program must have one main function section. This
section contains two parts; declaration part and executable part

1. Declaration part: The declaration part declares all the variables used in the
executable part.
2. Executable part: There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. The program
execution begins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical end of the program. All statements in the
declaration and executable part end with a semicolon.

Subprogram section: If the program is a multi-function program then the subprogram


section contains all the user-defined functions that are called in the main () function. User-
defined functions are generally placed immediately after the main() function, although they
may appear in any order.

Compilation and Execution of C Program:-

compiler is a software which converts high level language


into machine level language. And this process is known as compilation.

After compilation we get a file known as object file which


is machine language. Object file can be directly loaded into computer memory and execute or
run that. The process of loading object file and running that file is known as executing.

Character Set:-
The character set are set of words, digits, symbols and operators that are
valid in C. There are four types of Character Set:-

20 Manoj Pandya
+91-9460378169
21
Problem Solving Through C Programming

Keywords:-
Keywords are those words who has special meaning for compiler. We can't use
keywords as variable name. C has 32 Keywords as follows:

Data Types:-

21 Manoj Pandya
+91-9460378169
22
Problem Solving Through C Programming

Data types are used to define a variable. Data types represents the type of
information present in a variable. Data types are the keywords, which are used for assigning a
type to a variable.

There are five basic data types associated with variables:

1. int- integer: a whole number.


2. float- floating point value: i.e. a number with a fractional part.
3. double- a double-precision floating point value.
4. char- a single character.
5. void- valueless special purpose type which we will examine closely in later sections.

int- Integer data types:- Integers are whole numbers that can have both positive and negative
values but no decimal values. Example:- 0, -5, 10
For example: int id; Here, id is a variable of type integer. We can declare multiple variable at
once in C programming. For example: int id, age;

float- Floating types:- Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0
etc. We can declare a floating point variable in C by using either float or double keyword.
Example:- float accountBalance; , double bookPrice;

char- Character types:- Keyword char is used for declaring character type variables.
Example:- char test = 'h'; Here, test is a character variable. The value of test is 'h'.

Different data types also have different ranges up to which they can store numbers.

22 Manoj Pandya
+91-9460378169
23
Problem Solving Through C Programming

Constants:-

Constants is categorized into two basic types and each of these types has
own sub types/categories. These are: Primary Constants

1. Numeric Constants
o Integer Constants
o Real Constants
2. Character Constants
o Single Character Constants
o String Constants
o Backslash Character Constants

Integer Constant:- Its refer to sequence of digits. Integers are of three types:

1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer

Example:- 15, -265, 0, 99818, +25, 045, 0X6

Real constant:- The numbers containing fractional parts like 99.25 are called real or
floating points constant.

23 Manoj Pandya
+91-9460378169
24
Problem Solving Through C Programming

Single Character Constants:- It simply contains a single character enclosed within ‘and‘ (pair
of single quote). It is to be noted that the character ‘8‘ is not the same as 8. Character constants
have specific set of integer values known as ASCII values (American Standard Code for
Information Interchange).
Example: - ‘X’, ‘5’, ‘;’

String Constants:- These are sequence of characters enclosed in double quotes and they
may include letters, digits, special characters and blank-spaces. It is again to be noted that “G”
and ‘G‘ are different – because “G” represents string as it is enclosed within pair of double
quotes whereas ‘G’ represents a single character.
Example:- “Hello!”, “2015”, “2+1”

Backslash character constant:-


C supports some character constants having backslash in front of it. The lists of
backslash characters have specific meaning which is known to the compiler. They are also
termed as “Escape Sequence”.

24 Manoj Pandya
+91-9460378169
25
Problem Solving Through C Programming

Symbolic Constants:-

Symbolic Constant is a name that substitutes for a sequence of


characters or a numeric constant, a character constant or a string constant. When program is
compiled each occurrence of a symbolic constant is replaced by its corresponding character
sequence.

Syntax:- #define name text


where name implies symbolic name in caps. text implies value or the text.

Example:- #define MAX 50

Advantage:- They can be used to assign names to values.

Replacement of value has to be done at one place and wherever the name
appears in the text it gets the value by execution of the preprocessor.

This saves time. if the Symbolic Constant appears 20 times in the program; it
needs to be changed at one place only.

Variables:-
Variables are memory locations (storage area) in C programming
language. The main purpose of variables is to store data in memory for later use. Unlike
constants which do not change during the program execution, variables value may change during
execution. If you declare a variable in C, that means you are asking to the operating system for
reserve a piece of memory with that variable name.

Syntax:- type variable_name; or type variable_name, variable_name, variable_name;

Variable Definition and Initialization:-


Example:-

int width, height=5;


char letter='A';
float age, area;
double d;

/* actual initialization */
width = 10;
25 Manoj Pandya
+91-9460378169
26
Problem Solving Through C Programming

age = 26.5;

Variable Assignment:- Variable assignment is a process of assigning a value to a variable.


Example:- int width = 60;

There are some rules on choosing variable names:-


 Variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and the
underscore character.
 The first character must be a letter or underscore.
 Blank spaces cannot be used in variable names.
 Special characters like #, $ are not allowed.
 C keywords cannot be used as variable names.
 Variable names are case sensitive.
 Values of the variables can be numeric or alphabetic.
 Variable type can be char, int, float, double or void.

C Program to Print Value of a Variable:-

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
/* c program to print value of a variable */
int age = 33;
printf("I am %d years old.\n", age);
getch( );
}

Output: I am 33 years old.

Expressions:-

An expression is a combination of variables constants and


operators written according to the syntax of C language. In C every expression evaluates to a
value i.e., every expression results in some value of a certain type that can be assigned to a
variable. Some examples of C expressions are shown in the table given below.

26 Manoj Pandya
+91-9460378169
27
Problem Solving Through C Programming

Algebraic Expression C Expression

a x b – c a * b – c

(m + n) (x + y) (m + n) * (x + y)

(ab / c) a * b / c

3x2 +2x + 1 3*x*x+2*x+1

(x / y) + c x / y + c

Operators:-

C language offers many types of operators. They are-

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

Arithmetic Operators:-

C Arithmetic operators are used to perform mathematical


calculations like addition, subtraction, multiplication, division and modulus in C programs.

27 Manoj Pandya
+91-9460378169
28
Problem Solving Through C Programming

Program: In this program, two values “40” and “20” are used to perform arithmetic
operations such as addition, subtraction, multiplication, division, modulus and output is
displayed for each operation.

#include <stdio.h>
#include <conio.h>

void main( )
{
clrscr ( );
int a=40, b=20, add, sub, mul, div, mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);

28 Manoj Pandya
+91-9460378169
29
Problem Solving Through C Programming

printf("Modulus of a, b is : %d\n", mod);


getch( );
}

Output:-
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0

Assignment operators:-

 In C programs, values for the variables are assigned using assignment operators.
 For example, if the value “10” is to be assigned for the variable “sum”, it can be assigned
as “sum = 10;”
 There are 2 categories of assignment operators in C language. They are,
1. Simple assignment operator (Example: = )
2. Compound assignment operators ( Example: +=, -=, *=, /=, %=, &=, ^= )

29 Manoj Pandya
+91-9460378169
30
Problem Solving Through C Programming

Program: In this program, values from 0 – 9 are summed up and total “45” is displayed as
output. Assignment operators such as “=” and “+=” are used in this program to assign the values
and to sum up the values.

# include <stdio.h>
#include<conio.h
void main( )
{
int Total=0,i;
clrscr( );
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total = Total + i
}
printf("Total = %d", Total);
getch( );
30 Manoj Pandya
+91-9460378169
31
Problem Solving Through C Programming

Output:- Total = 45

Relational operators:-

Relational operators are used to find the relation between two variables.
i.e. to compare the values of two variables in a C program.

Program:
 In this program, relational operator (= =) is used to compare 2 values whether they are
equal are not.
 If both values are equal, output is displayed as ” values are equal”. Else, output is
displayed as “values are not equal”.
 Note: double equal sign (= =) should be used to compare 2 values. We should not single
equal sign (=).

#include <stdio.h>
#include <conio.h>

void main( )
{
int m=40, n=20;
31 Manoj Pandya
+91-9460378169
32
Problem Solving Through C Programming

clrscr( );
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
getch( );
}

Output:- m and n are not equal

Logical operators:-

These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).

32 Manoj Pandya
+91-9460378169
33
Problem Solving Through C Programming

Program:
#include <stdio.h>
int main( )
{
int m=40,n=20;
int o=20,p=30;
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. " \ "But, status is inverted as false\n");
}
}
Output:-
&& Operator: Both conditions are true 
|| Operator: Only one condition is true
! Operator: Both conditions are true. But, status is inverted as false

In this program, operators (&&, || and !) are used to perform logical operations on the
given expressions.
 && operator – “if clause” becomes true only when both conditions (m>n and m! =0) is
true. Else, it becomes false.
 || Operator – “if clause” becomes true when any one of the condition (o>p || p!=20) is
true. It becomes false when none of the condition is true.
 ! Operator – It is used to reverses the state of the operand.
 If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by
“!” operator.
 So, “! (m>n and m! =0)” returns false (0).

33 Manoj Pandya
+91-9460378169
34
Problem Solving Through C Programming

Bit wise operators:-

 These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
 Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^
(XOR), << (left shift) and >> (right shift).

Truth table for bit wise operation & Bit wise operators:

Below are the bit-wise operators and their name:-

1. & – Bitwise AND


2. | – Bitwise OR
3. ~ – Bitwise NOT
4. ^ – XOR
5. << – Left Shift
6. >> – Right Shift

Note:

 Bitwise NOT: Value of 40 in binary is 00000000000000000000000000000000


00000000000000000010100000000000. So, all 0’s are converted into 1’s in bit wise
NOT operation.
 Bitwise left shift and right shift: In left shift operation “x << 1 “, 1 means that the bits
will be left shifted by one place. If we use it as “x << 2 “, then, it means that the bits will
be left shifted by 2 places.

34 Manoj Pandya
+91-9460378169
35
Problem Solving Through C Programming

Program: In this example program, bit wise operations are performed as shown above and output
is displayed in decimal format.

#include <stdio.h>
#include<conio.h>
void main( )
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
clrscr( );
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
getch( );
}

Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20

Conditional or ternary operators:

 Conditional operators return one value if condition is true and returns another value is
condition is false.
 This operator is also called as ternary operator.

Syntax : (Condition? true_value: false_value);

35 Manoj Pandya
+91-9460378169
36
Problem Solving Through C Programming

Example : (A > 100 ? 0 : 1);

 In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal
to if else conditional statements.

Program:
#include <stdio.h>
#include<conio.h>
void main( )
{
int x=1, y ;
clrscr( );
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
getch( );
}

Output:
x value is 1
y value is 2

Increment/Decrement Operator:

 Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.

 Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;

 Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;

Program: In this program, value of “i” is incremented one by one from 1 up to 9 using “i++”
operator and output is displayed as “1 2 3 4 5 6 7 8 9”.

36 Manoj Pandya
+91-9460378169
37
Problem Solving Through C Programming

#include<stdio.h>
#include<conio.h>
void main( )
{
int i=1;
while(i<10)
{

printf("%d ",i);
i++;
}
getch( );
}
Output: - 1 2 3 4 5 6 7 8 9

Program: In this program, value of “I” is decremented one by one from 20 up to 11 using
i--” operator and output is displayed as “20 19 18 17 16 15 14 13 12 11”.

#include <stdio.h>
#include<conio.h>
int main( )
{
int i=20;
while(i>10)
{
printf("%d ",i);
i--;
}
}

Output:- 20 19 18 17 16 15 14 13 12 11

Difference between pre/post increment & decrement operators:


Below table will explain the difference between pre/post increment and decrement operators:

37 Manoj Pandya
+91-9460378169
38
Problem Solving Through C Programming

Special Operators:
Below are some of the special operators that the C programming language offers.

38 Manoj Pandya
+91-9460378169
39
Problem Solving Through C Programming

Precedence and Associativity of Operators:-

The precedence and associativity of C operators affect the grouping


and evaluation of operands in expressions. An operator's precedence is meaningful only if other
operators with higher or lower precedence are present. Expressions with higher-precedence
operators are evaluated first. Precedence can also be described by the word "binding." Operators
with a higher precedence are said to have tighter binding.

39 Manoj Pandya
+91-9460378169
40
Problem Solving Through C Programming

Input /Output Statements:


Input and Output statement are used to read and write the data in C
programming. These are embedded in stdio.h (standard Input/Output header file). There are
mainly two of Input/Output functions are used for this purpose. These are discussed as:

Unformatted I/O functions:-


There are mainly six unformatted I/O functions discussed as follows:

a) getchar()
b) putchar()
c) gets()
d) puts()
e) getch()
f) getche()

a) getchar( ):-

This function is an Input function. It is used for reading a single character from the
keyboard. It is buffered function. Buffered functions get the input from the keyboard and store it
in the memory buffer temporally until you press the Enter key.

The general syntax is as: v = getchar();

Where v is the variable of character type.

40 Manoj Pandya
+91-9460378169
41
Problem Solving Through C Programming

Program: A simple C-program to read a single character from the keyboard is as:

/*To read a single character from the keyboard using the getchar( ) function*/
#include<stdio.h>
#include<conio.h>
main( )
{
char n;
n = getchar( );
}

b) putchar():-
This function is an output function. It is used to display a single character on the
screen.

The general syntax is as: putchar(v);

where v is the variable of character type.

Program: A simple program is written as below, which will read a single character using
getchar() function and display inputted data using putchar() function:

/*Program illustrate the use of getchar() and putchar() functions*/


#include<stdio.h>
#include<conio.h>
main()
{
char n;
n = getchar();
putchar(n);
}

c) gets():-

This function is an input function. It is used to read a string from the


keyboad. It is also buffered function. It will read a string, when you type the string from the

41 Manoj Pandya
+91-9460378169
42
Problem Solving Through C Programming

keyboard and press the Enter key from the keyboard. It will mark null character ('\0') in the
memory at the end of the string, when you press the enter key.

The general syntax is as: gets(v); where v is the variable of character type.

Program: A simple C program to illustrate the use of gets( ) function:

/*Program to explain the use of gets( ) function*/


#include<stdio.h>
#include<conio.h>
main( )
{
char n[20];
gets(n);
}

d) puts():-

This is an output function. It is used to display a string inputted by gets()


function. It is also used to display an text (message) on the screen for program simplicity. This
function appends a newline ("\n") character to the output.

The general syntax is as: puts(v); or puts("text line");

where v is the variable of character type.

Program: A simple C program to illustrate the use of puts() function:

/*Program to illustrate the concept of puts( ) with gets( ) functions*/


#include<stdio.h>
#include<conio.h>
main( )
{
char name[20];
puts("Enter the Name");
gets(name);
puts("Name is :");
puts(name);
}

42 Manoj Pandya
+91-9460378169
43
Problem Solving Through C Programming

OUTPUT:
Enter the Name Laura
Name is: Laura

e) getch():-

This is also an input function. This is used to read a single character from the
keyboard like getchar() function. But getchar() function is a buffered is function, getchar()
function is a non-buffered function. The character data read by this function is directly assign to
a variable rather it goes to the memory buffer, the character data directly assign to a variable
without the need to press the Enter key. Another use of this function is to maintain the output on
the screen till you have not press the Enter Key.

The general syntax is as: v = getch( );

where v is the variable of character type.

Program: A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/


#include<stdio.h>
#include<conio.h>
main( )
{
char n;
puts("Enter the Char");
n = getch( );
puts("Char is :");
putchar(n);
getch( );
}

OUTPUT :
Enter the Char
Char is L

43 Manoj Pandya
+91-9460378169
44
Problem Solving Through C Programming

f) getche( ):-
All are same as getch() function execpt it is an echoed function. It
means when you type the character data from the keyboard it will visible on the screen.

The general syntax is as: v = getche( );

Where v is the variable of character type.

Program: A simple C program to illustrate the use of getch() function:

/*Program to explain the use of getch() function*/


#include<stdio.h>
#include<conio.h>
main( )
{
char n;
puts("Enter the Char");
n = getche();
puts("Char is :");
putchar(n);
getche();
}

OUTPUT:
Enter the Char L
Char is L

Formatted I/O functions:-

Formatted I/O functions which refer to an Input or Ouput data


that has been arranged in a particular format. There are mainly two formatted I/O functions
discussed as follows:
a) scanf()
b) printf()

44 Manoj Pandya
+91-9460378169
45
Problem Solving Through C Programming

a) scanf( ):-

The scanf() function is an input function. It used to read the mixed type of data
from keyboard. You can read integer, float and character data by using its control codes or
format codes.

The general syntax is as: scanf("control strings",arg1,arg2,..............argn);


or
scanf("control strings",&v1,&v2,&v3,................&vn);

Where arg1,arg2,..........argn are the arguments for reading and v1,v2,v3,........vn all are the
variables.

The scanf() format code (spedifier) is as shown in the below table:

45 Manoj Pandya
+91-9460378169
46
Problem Solving Through C Programming

Program:

/*Program to illustrate the use of formatted code by using the formatted scanf() function */
#include<stdio.h>
#include<conio.h>
main( )
{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch( );
}

b) printf( ):-

This ia an output function. It is used to display a text message and to display


the mixed type (int, float, char) of data on screen.

The general syntax is as: printf("control strings",&v1,&v2,&v3,................&vn);


Or
printf("Message line or text line");

Where v1,v2,v3,........vn all are the variables.

The control strings use some printf() format codes or format specifiers or conversion characters.
These all are discussed in the below table as:

46 Manoj Pandya
+91-9460378169
47
Problem Solving Through C Programming

Program:-
/*Below the program which show the use of printf () function*/
#include<stdio.h>
#include<conio.h>
main( ) {
int a;
float b;
char c;
printf("Enter the mixed type of data");
scanf("%d",%f,%c",&a,&b,&c);
getch( );
}

Control Structure (Decision making):


Decision making is about deciding the order of execution of statements
based on certain conditions or repeat a group of statements until certain specified conditions are
met.
C language handles decision-making by supporting the following statements,

 if statement
 switch statement
 conditional operator statement (Ternary Operator)
 goto statement

47 Manoj Pandya
+91-9460378169
48
Problem Solving Through C Programming

Decision making with if statement:-

The if statement may be implemented in different forms depending on the


complexity of conditions to be tested. The different forms are,

1. Simple if statement
2. If....else statement
3. Nested if....else statement
4. else if statement (Else if ladder)

1. Simple if statement:- The general form of a simple if statement is,


if( expression )
{
statement inside;
}
statement outside;

If the expression is true, then 'statement-inside' it will be executed, otherwise


'statement-inside' is skipped and only 'statement-outside' is executed.

Flow chart:

48 Manoj Pandya
+91-9460378169
49
Problem Solving Through C Programming

Program :

#include <stdio.h>
void main( )
{
int x,y;
x=15;
y=13;
if (x > y )
{
printf("x is greater than y");
}
}

Output:- x is greater than y

2. if...else statement:- The general form of a simple if...else statement is,


if( expression )
{
statement block1;
}
else
{
statement block2;
}
If the 'expression' is true, the 'statement-block1' is
executed, else 'statement-block1' is skipped and 'statement-block2' is
executed.

Flowchart:-

49 Manoj Pandya
+91-9460378169
50
Problem Solving Through C Programming

Program:

#include <stdio.h>
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}

Output:

y is greater than x

3. Nested if....else statement:- The general form of a nested if...else statement is,
if( expression )
{
if( expression1 )
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block3;
}

if 'expression' is false the 'statement-block3' will be executed, otherwise it


continues to perform the test for 'expression 1' . If the 'expression 1' is true the 'statement-block1'
is executed otherwise 'statement-block2' is executed.

50 Manoj Pandya
+91-9460378169
51
Problem Solving Through C Programming

Flowchart:

Program:

#include <stdio.h>
#include <conio.h>
void main( )
{
int a,b,c;
clrscr();
printf("enter 3 number");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if( a > c)
{
printf("a is greatest");
}
else
{
printf("c is greatest");
}
51 Manoj Pandya
+91-9460378169
52
Problem Solving Through C Programming

}
else
{
if( b> c)
{
printf("b is greatest");
}
else
{
printf("c is greatest");
}
}
getch();
}

4. else-if ladder:- The general form of else-if ladder is,


if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;

The expression is tested from the top(of the ladder) downwards. As soon as the true condition is
found, the statement associated with it is executed.

52 Manoj Pandya
+91-9460378169
53
Problem Solving Through C Programming

Flowchart:

Program:

#include <stdio.h>
#include <conio.h>
void main( ){
int a;
printf("enter a number");
scanf("%d",&a);
if( a%5==0 && a%8==0)
{
printf("divisible by both 5 and 8");
}
else if( a%8==0 )
{
printf("divisible by 8");
}
else if(a%5==0)
{
printf("divisible by 5");
}
else
{
printf("divisible by none");
}
getch(); }
53 Manoj Pandya
+91-9460378169
54
Problem Solving Through C Programming

Switch statement:-

When you want to solve multiple option type problems, for


example, menu like program, where one value is associated with each option and you need to
chose only one at a time, then , switch statement is used. Switch statement is a control statement
that allows us to choose only one choice among the many given choices. The expression in
switch evaluates to return an integral value, which is then compared to the values present in
different cases. It executes that block of code which matches the case value. If there is no match,
then default block is executed (If present).

The general form of switch statement is,

switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}

Rules for using switch:

1. The expression (after switch keyword) must yield an integer value i.e it can be an integer
or a variable or an expression that evaluates to an integer.
2. The case label i.e values must be unique.
3. The case label must end with a colon(:)
4. The following line, after case statement, can be any valid C statement.

54 Manoj Pandya
+91-9460378169
55
Problem Solving Through C Programming

Flowchart:

Program:

#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c,choice;
clrscr( );
while(choice!=3)
{
printf("\n 1. Press 1 for addition");
printf("\n 2. Press 2 for subtraction");
printf("\n Enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d",&a,&b);
c=a+b;
printf("%d",c);
break;
55 Manoj Pandya
+91-9460378169
56
Problem Solving Through C Programming

case 2:
printf("Enter 2 numbers");
scanf("%d%d",&a,&b);
c=a-b;
printf("%d",c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
getch();
}

Ternary Operator:- If any operator is used on three operands or variable is known as Ternary
Operator. It can be represented with ? : . It is also called as conditional operator.

Advantage of Ternary Operator: - Using ?: reduce the number of line codes and improve the
performance of application.
Syntax:- expression-1 ? expression-2 : expression-3

In the above symbol expression-1 is condition and expression-2 and expression-3 will be either
value or variable or statement or any mathematical expression. If condition will be true
expression-2 will be execute otherwise expression-3 will be executed.

Flow Chart

56 Manoj Pandya
+91-9460378169
57
Problem Solving Through C Programming

Program:- Find largest number among 3 numbers using ternary operator.

#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b, c, large;
clrscr( );
printf("Enter any three number: ");
scanf("%d%d%d",&a,&b,&c);
large=a>b ? (a>c?a:c) : (b>c?b:c);
printf("Largest Number is: %d",large);
getch( );
}

Output:-
Enter any three number: 5 7 2
Largest number is 7

Goto statement:-
A goto statement in C programming provides an unconditional jump
from the 'goto' to a labeled statement in the same function.

Flow Chart

57 Manoj Pandya
+91-9460378169
58
Problem Solving Through C Programming

Program:

#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}

Output:-

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

58 Manoj Pandya
+91-9460378169
59
Problem Solving Through C Programming

Unit - III

59 Manoj Pandya
+91-9460378169
60
Problem Solving Through C Programming

Loops (Iteration):-

Loop, in the context of computer programming, is a process wherein a set of


instructions or structures are repeated in a sequence a specified number of times or until a
condition is met. When the first set of instructions is executed again, it is called iteration.
A loop is a programming function that iterates a statement or condition
based on specified boundaries. The loop function uses almost identical logic and syntax in all
programming languages. Thus, a specific statement or a group of instructions is continuously
executed until a specific loop body or boundary condition is reached. The result of the entire
loop body’s first operation cycle serves as the next repetition’s starting point. A loop repeatedly
executes code in its body until the loop conditional statement becomes false.

A loop is divided into two parts:

 Loop Statement: This defines the time limit to be true for the continuous loop that is
contingent on the attached conditional statement.
 Loop Body: This holds the statement’s code or instruction; it is executed with each loop
cycle.

Types of Loop:-

 The for statement


 The while statement
 The do-while statement
 break and continue

While loop:-

A while loop in C programming repeatedly executes a target statement as long


as a given condition is true.

The syntax of a while loop :-

while(condition) {
statement(s);
}

Here, statement(s) may be a single statement or a block of


statements. The condition may be any expression, and true is any nonzero value. The loop
iterates while the condition is true. When the condition becomes false, the program control
passes to the line immediately following the loop.

60 Manoj Pandya
+91-9460378169
61
Problem Solving Through C Programming

Flow Diagram:-

Here, the key point to note is that a while loop might not execute at all.
When the condition is tested and the result is false, the loop body will be skipped and the first
statement after the while loop will be executed.

Program:-
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}
return 0;
}

61 Manoj Pandya
+91-9460378169
62
Problem Solving Through C Programming

Output:-

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Do While loop:-
Unlike for and while loops, which test the loop condition at the top of the
loop, the do...while loop in C programming checks its condition at the bottom of the loop. A
do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least
one time.

The syntax of a do...while is:-

do {
statement(s);
} while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in
the loop executes once before the condition is tested. If the condition is true, the flow of control
jumps back up to do, and the statement(s) in the loop executes again. This process repeats until
the given condition becomes false.
Flow Diagram:-

62 Manoj Pandya
+91-9460378169
63
Problem Solving Through C Programming

Program:-
#include <stdio.h>
int main ( ) {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}

Output:-

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

For Loop:-

A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.

The syntax of a for loop is:-

for ( init; condition; increment ) {

statement(s);
}

63 Manoj Pandya
+91-9460378169
64
Problem Solving Through C Programming

Here is the flow of control in a 'for' loop:-

 The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long
as a semicolon appears.
 Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and the flow of control jumps to the next
statement just after the 'for' loop.
 After the body of the 'for' loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the condition.
 The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes false, the 'for' loop terminates.

Flow Diagram:-

64 Manoj Pandya
+91-9460378169
65
Problem Solving Through C Programming

Program:-

#include <stdio.h>
int main () {
int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}
return 0;
}

Output:-

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Difference between while and do while loop:-

Both while and do-while loop are the iteration statement, if we want that
first, the condition should be verified, and then the statements inside the loop must execute then the while
loop is used. If you want to test the termination condition at the end of the loop, then the do-while loop is
used.

65 Manoj Pandya
+91-9460378169
66
Problem Solving Through C Programming

Nested Loops:

C programming allows to use one loop inside another loop. The following
section shows a few examples to illustrate the concept.

The syntax for a nested for loop statement is:-

for ( init; condition; increment ) {

for ( init; condition; increment ) {


statement(s);
}
statement(s);
}

66 Manoj Pandya
+91-9460378169
67
Problem Solving Through C Programming

The syntax for a nested while loop statement is:-

while(condition) {

while(condition) {
statement(s);
}
statement(s);
}

The syntax for a nested do...while loop statement is:-

do {
statement(s);

do {
statement(s);
}while( condition );

}while( condition );

A final note on loop nesting is that you can put any type of loop
inside any other type of loop. For example, a 'for' loop can be inside a 'while' loop or vice
versa.

Program:- nested for loop to find the prime numbers from 2 to 100 –

#include <stdio.h>
int main ()
{

/* local variable definition */


int i, j;

for(i = 2; i<100; i++) {

for(j = 2; j <= (i/j); j++)


if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
}

67 Manoj Pandya
+91-9460378169
68
Problem Solving Through C Programming

Output:-
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

Break & Continue:

It is sometimes desirable to skip some statements inside the loop or terminate


the loop immediately without checking the test expression. In such cases, break and continue
statements are used.

break Statement:-

The break statement terminates the loop (for, while and do...while loop) immediately
when it is encountered. The break statement is used with decision making statement such as if...else.

Syntax of break statement: - break;

68 Manoj Pandya
+91-9460378169
69
Problem Solving Through C Programming

Flow Chart:-

69 Manoj Pandya
+91-9460378169
70
Problem Solving Through C Programming

How break statement works:-

Program:- break statement


// Program to calculate the sum of maximum of 10 numbers
// Calculates sum until user enters positive number

# include <stdio.h>
int main() {
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i){
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If user enters negative number, loop is terminated
if(number < 0.0) {
break; }
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}

70 Manoj Pandya
+91-9460378169
71
Problem Solving Through C Programming

Output:-

Enter a n1: 2.4


Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3
Sum = 10.30

This program calculates the sum of maximum of 10 numbers. It's because, when the user enters negative
number, the break statement is executed and loop is terminated.

Continue statement: -

The continue statement skips some statements inside the loop. The continue statement is used with
decision making statement such as if...else.

Syntax of continue Statement: continue;

Flowchart:-

71 Manoj Pandya
+91-9460378169
72
Problem Solving Through C Programming

How continue statement works:-

Program:- continue statement


// Program to calculate sum of maximum of 10 numbers
// Negative numbers are skipped from calculation

# include <stdio.h>
int main(){
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i) {
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If user enters negative number, loop is terminated
if(number < 0.0)
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
72 Manoj Pandya
+91-9460378169
73
Problem Solving Through C Programming

Output:-

Enter a n1: 1.1


Enter a n2: 2.2
Enter a n3: 5.5
Enter a n4: 4.4
Enter a n5: -3.4
Enter a n6: -45.5
Enter a n7: 34.5
Enter a n8: -4.2
Enter a n9: -1000
Enter a n10: 12
Sum = 59.70

In the program, when the user enters positive number, the sum is
calculated using sum += number; statement. When the user enters negative number, the
continue statement is executed and skips the negative number from calculation.

C preprocessor:-

The C Preprocessor is not a part of the compiler, but is a separate step


in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it
instructs the compiler to do required pre-processing before the actual compilation. We'll refer to
the C Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be


the first nonblank character, and for readability, a preprocessor directive should begin in the first
column. The following section lists down all the important preprocessor directives-

#include #define #undef #ifdef


#ifndef #if #else #elif
#endif #error #pragma

73 Manoj Pandya
+91-9460378169
74
Problem Solving Through C Programming

Macro:-
A macro is a sort of abbreviation which you can define once and then
use later. There are many complicated features associated with macros in the C preprocessor.

Simple Macros:-

A simple macro is a kind of abbreviation. It is a name which stands for a


fragment of code. Some people refer to these as manifest constants. Before you can use a macro,
you must define it explicitly with the `#define' directive. `#define' is followed by the
name of the macro and then the code it should be an abbreviation for. For example,

#define BUFFER_SIZE 1020

Macros with Arguments:-

A simple macro always stands for exactly the same text, each time it is
used. Macros can be more flexible when they accept arguments. Arguments are fragments of
code that you supply each time the macro is used. These fragments are included in the expansion
of the macro according to the directions in the macro definition. A macro that accepts arguments
is called a function-like macro because the syntax for using it looks like a function call. To
define a macro that uses arguments, you write a `#define' directive with a list of argument
names in parentheses after the name of the macro. The argument names may be any valid C
identifiers, separated by commas and optionally whitespace. The open-parenthesis must follow
the macro name immediately, with no space in between.

For example, here is a macro that computes the minimum of two numeric values, as it is defined
in many C programs: #define min(X, Y) ((X) < (Y) ? (X) : (Y))

Nesting of Macros:- A macro may be used in the definition of another macro as illustrated
below.

#define A(x) x*x


#define cost(A,y) A*y

74 Manoj Pandya
+91-9460378169
75
Problem Solving Through C Programming

Unit - IV

75 Manoj Pandya
+91-9460378169
76
Problem Solving Through C Programming

Functions:-

A large C program is divided into basic building blocks called C function.


C function contains set of instructions enclosed by “{ }” which performs specific operation in a
C program. Actually, Collection of these functions creates a C program.

Uses of functions:-

 C functions are used to avoid rewriting same logic/code again and again in a program.
 There is no limit in calling C functions to make use of same functionality wherever
required.
 We can call functions any number of times in a program and from any place in a
program.
 A large C program can easily be tracked when it is divided into functions.
 The core concept of C functions are, re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability of very large C programs.

Type of functions:-

 Built in function or Library Functions


 User defined functions

Built in functions:-
Built in functions are the functions that are provided by C library. Many
activities in C are carried out using library functions. These functions perform file access,
mathematical computations, graphics, memory management etc.
A library function is accessed simply by writing the function name,
followed by an optional list of arguments and header file of used function should be included
with the program.
Definition of built in functions are defined in a special header file. A
header file can contain definition of more than one library function but the same function cannot
be defined in two header files.

Ex:-
main( ) gets( ) strlen( ) strcat( ) isdigit( )
printf( ) puts( ) strcmp( ) strstr( ) isupper( )
scanf( ) strcpy( ) stricmp( ) isalpha( ) islower( )

76 Manoj Pandya
+91-9460378169
77
Problem Solving Through C Programming

User defined function:-


Functions provided by library are not enough for user so to complete
their needs user has to define some functions themselves, these are called user defined functions.
Means except built in functions user can also define and write small programs as functions to do
a task relevant to their programs, there functions should be codified by the user, so that such
functions can perform the task as desired by user.

Program:- Here is an example to add two integers. To perform this task, we have created an user-
defined addNumbers().

#include <stdio.h>
int addNumbers(int a, int b); // function prototype

int main()
{
int n1,n2,sum;

printf("Enters two numbers: ");


scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call


printf("sum = %d",sum);

return 0;
}

int addNumbers(int a, int b) // function definition


{
int result;
result = a+b;
return result; // return statement
}

77 Manoj Pandya
+91-9460378169
78
Problem Solving Through C Programming

Function declaration, function call and function definition:-

There are 3 aspects in each C function. They are,

 Function declaration or prototype – This informs compiler about the function name,
function parameters and return value’s data type.
 Function call – This calls the actual function
 Function definition – This contains all the statements to be executed.

Function Declarations:-

A function declaration tells the compiler about a function name and


how to call the function. The actual body of the function can be defined separately.

A function declaration has the following parts −

return_type function_name( parameter list );

For the above defined function max(), the function declaration is as follows:-

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so the
following is also a valid declaration:-

int max(int, int);

Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling
the function.
78 Manoj Pandya
+91-9460378169
79
Problem Solving Through C Programming

Function Definition:-

The general form of a function definition in C programming language is as follows −

return_type function_name( parameter list ) {


body of the function
}

A function definition in C programming consists of a function header and a function body. Here
are all the parts of a function:-

 Return Type:- A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name:- This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters:- A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body:- The function body contains a collection of statements that define what
the function does.

Calling a Function:-

While creating a C function, you give a definition of what the function


has to do. To use a function, you will have to call that function to perform the defined task.

When a program calls a function, the program control is transferred to


the called function. A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the program control
back to the main program.

To call a function, you simply need to pass the required parameters


along with the function name, and if the function returns a value, then you can store the returned
value.

79 Manoj Pandya
+91-9460378169
80
Problem Solving Through C Programming

Advantages of user-defined functions:-

1. The subprogram are easier to write, understand and debug.


2. In C, a function can call itself again. It is called a recursive function. Many calculations
can be done easily by using recursive functions such as calculation of factorial of a
number, etc.
3. Reduction in size of program due to program code of a function can be used again and
again, by calling it.
4. The complexity of the entire program can be divided into simple subtask and then
function subprograms can be written for each subtask.
5. A library of a function can be designed and tested for use of every programmer.

Category of functions:-

There can be 4 different types of user-defined functions, they are:

1. Function with no arguments and no return value


2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and a return value

Function with no arguments and no return value:-

Such functions can either be used to display information or they are completely
dependent on user inputs.

Below is an example of a function, which takes 2 numbers as input from user, and display which
is the greater number.

#include<stdio.h>
void greatNum(); // function declaration
int main()
{
greatNum(); // function call
return 0;
}
void greatNum() // function definition
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {

80 Manoj Pandya
+91-9460378169
81
Problem Solving Through C Programming

printf("The greater number is: %d", i);


}
else {
printf("The greater number is: %d", j);
}
}

Function with no arguments and a return value:-

We have modified the above example to make the function greatNum() return
the number which is greater amongst the 2 input numbers.

#include<stdio.h>
int greatNum(); // function declaration

int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}

int greatNum() // function definition


{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
greaterNum = i;
}
else {
greaterNum = j;
}
// returning the result
return greaterNum;
}

Function with arguments and no return value:-

We are using the same function as example again and again, to


demonstrate that to solve a problem there can be many different ways.

This time, we have modified the above example to make the function greatNum() take two int
values as arguments, but it will not be returning anything.

81 Manoj Pandya
+91-9460378169
82
Problem Solving Through C Programming

#include<stdio.h>
void greatNum(int a, int b); // function declaration

int main()
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
greatNum(i, j); // function call
return 0;
}

void greatNum(int x, int y) // function definition


{
if(x > y) {
printf("The greater number is: %d", x);
}
else {
printf("The greater number is: %d", y);
}
}

Function with arguments and a return value:-

This is the best type, as this makes the function completely independent of
inputs and outputs, and only the logic is defined inside the function body.

#include<stdio.h>
int greatNum(int a, int b); // function declaration

int main()
{
int i, j, result;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // function call
printf("The greater number is: %d", result);
return 0;
}

int greatNum(int x, int y) // function definition


{
if(x > y) {
return x;
}
else {
return y;
}
}

82 Manoj Pandya
+91-9460378169
83
Problem Solving Through C Programming

Parameter passing:-

When a function gets executed in the program, the execution control


is transferred from calling-function to called function and executes function definition, and
finally comes back to the calling function. When the execution control is transferred from
calling-function to called-function it may carry one or number of data values. These data values
are called as parameters.

"Parameters are the data values that are passed from calling function to called function."

In C, there are two types of parameters and they are as follows...

 Actual Parameters
 Formal Parameters

The actual parameters are the parameters that are speficified in calling function. The formal
parameters are the parameters that are declared at called function. When a function gets
executed, the copy of actual parameter values are copied into formal parameters.

In C Programming Language, there are two methods to pass parameters from calling function to
called function and they are as follows...

 Call by Value
 Call by Reference

Call by Value:-

In call by value parameter passing method, the copy of actual


parameter values are copied to formal parameters and these formal parameters are used in
called function. The changes made on the formal parameters does not effect the values of
actual parameters. That means, after the execution control comes back to the calling function,
the actual parameter values remains same. For example consider the following program.

83 Manoj Pandya
+91-9460378169
84
Problem Solving Through C Programming

Program:-

#include<stdio.h>
#include<conio.h>

void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;

swap(num1, num2) ; // calling function

printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);


getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a = b ;
b = temp ;
}

84 Manoj Pandya
+91-9460378169
85
Problem Solving Through C Programming

Output:-

In the above example program, the variables num1 and num2 are called actual parameters and
the variables a and b are called formal parameters. The value of num1 is copied into a and the
value of num2 is copied into b. The changes made on variables a and b does not effect the values
of num1 and num2.

Call by Reference:-
In Call by Reference parameter passing method, the memory location
address of the actual parameters is copied to formal parameters. This address is used to access
the memory locations of the actual parameters in called function. In this method of parameter
passing, the formal parameters must be pointer variables. That means in call by reference
parameter passing method, the address of the actual parameters is passed to the called function
and is recieved by the formal parameters (pointers). Whenever we use these formal parameters in
called function, they directly access the memory locations of actual parameters. So the changes
made on the formal parameters effects the values of actual parameters.

85 Manoj Pandya
+91-9460378169
86
Problem Solving Through C Programming

Program:-

#include<stdio.h>
#include<conio.h>

void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;


swap(&num1, &num2) ; // calling function

printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);


getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}

Output:-

86 Manoj Pandya
+91-9460378169
87
Problem Solving Through C Programming

Recursion:-

Recursion is the process of repeating items in a self-similar way. In programming


languages, if a program allows you to call a function inside the same function, then it is called a
recursive call of the function.

A function to call itself. But while using recursion, programmers need to be careful
to define an exit condition from the function, otherwise it will go into an infinite loop. Recursive
functions are very useful to solve many mathematical problems, such as calculating the factorial
of a number, generating Fibonacci series, etc.

Number Factorial:- The following example calculates the factorial of a given number using a
recursive function:-

#include <stdio.h>
int factorial(unsigned int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main( ) {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}

Output:- Factorial of 12 is 479001600

87 Manoj Pandya
+91-9460378169
88
Problem Solving Through C Programming

Array:-

Arrays a kind of data structure that can store a fixed-size sequential


collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ...,


and number99, you declare one array variable such as numbers and use numbers[0], numbers[1],
and ..., numbers[99] to represent individual variables. A specific element in an array is accessed
by an index.

All arrays consist of contiguous memory locations. The lowest address


corresponds to the first element and the highest address to the last element.

One dimensional Array:-

In it each element is represented by a single subscript. The


elements are stored in consecutive memory locations. E.g. A [1], A [2], ….., A [N].

The declaration form of one dimensional array is :- Data_type array_name [size];

The following declares an array called ‘numbers’ to hold 5 integers and sets the first and last
elements. C arrays are always indexed from 0. So the first integer in ‘numbers’ array is
numbers[0] and the last is numbers[4].

int numbers [5];


numbers [0] = 1; // set first element
numbers [4] = 5; // set last element

88 Manoj Pandya
+91-9460378169
89
Problem Solving Through C Programming

This array contains 5 elements. Any one of these elements may be referred to by giving the name
of the array followed by the position number of the particular element in square brackets ([]).
The first element in every array is the zeroth element.Thus, the first element of array ‘numbers’is
referred to asnumbers[ 0 ], the second element of array ‘numbers’is referred to as numbers[ 1 ],
the fifth element of array ‘numbers’is referred to as numbers[ 4 ], and, in general, the n-th
element of array ‘numbers’is referred to as numbers[ n – 1 ].

Access array elements:-

An element is accessed by indexing the array name. This is done by


placing the index of the element within square brackets after the name of the array.

For example:- double salary = balance[9];

The above statement will take the 10th element from the array and assign the value to salary
variable. The following example Shows how to use all the three above mentioned concepts viz.
declaration, assignment, and accessing arrays-

#include <stdio.h>

int main () {

int n[ 10 ]; /* n is an array of 10 integers */


int i,j;

/* initialize elements of array n to 0 */


for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}

/* output each array element's value */


for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}

return 0;
}

When the above code is compiled and executed, it produces the following result −

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
89 Manoj Pandya
+91-9460378169
90
Problem Solving Through C Programming

Two dimensional Array:-

In it each element is represented by two subscripts. Thus a two


dimensional m x n array A has m rows and n columns and contains m*n elements. It is also
called matrix array because in it the elements form a matrix. E.g. A [2] [3] has 2 rows and 3
columns and 2*3 = 6 elements.

In C programming, We can create an array of arrays known as multidimensional array.

Example:- float x[3][4];

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array
as table with 3 row and each row has 4 column.

Declaration of two dimensional Array:-

We can declare an array in the c language in the following way.

data_type array_name[size1][size2];

A simple example to declare two dimensional array is given below.

int twodimen[4][3];

Here, 4 is the row number and 3 is the column number.

90 Manoj Pandya
+91-9460378169
91
Problem Solving Through C Programming

Initialization of 2D Array:-

A way to initialize the two dimensional array at the time of declaration is given below.

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Program:-

#include<stdio.h>
int main( ){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}

Output:-
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

91 Manoj Pandya
+91-9460378169
92
Problem Solving Through C Programming

92 Manoj Pandya
+91-9460378169
93
Problem Solving Through C Programming

Program:-

// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>

int main() {
int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}

Output:-
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3

Character array:-

String is a sequence of characters that is treated as a single data item and


terminated by null character '\0'. Remember that C language does not support strings as a data
type. A string is actually one-dimensional array of characters in C language. These are often
used to create meaningful and readable programs.

Example:- The string "hello world" contains 12 characters including '\0' character
which is automatically added by the compiler at the end of the string.
93 Manoj Pandya
+91-9460378169
94
Problem Solving Through C Programming

Declaring and Initializing a string variables:-

There are different ways to initialize a character array variable.

char name[13] = "StudyTonight"; // valid character array


initialization

char name[10] = {'L','e','s','s','o','n','s','\0'}; // valid


initialization

Remember that when you initialize a character array by listing all of its characters
separately then you must supply the '\0' character explicitly.

Some examples of illegal initialization of character array are,

char ch[3] = "hell"; // Illegal


char str[4];
str = "hell"; // Illegal

String Input and Output:-

Input function scanf() can be used with %s format specifier to read


a string input from the terminal. But there is one problem with scanf() function, it terminates
its input on the first white space it encounters. Therefore if you try to read an input string "Hello
World" using scanf() function, it will only read Hello and terminate after encountering white
spaces.

However, C supports a format specification known as the edit set conversion code %[..] that
can be used to read a line containing a variety of characters, including white spaces.

#include<stdio.h>
#include<string.h>

void main( )
{
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str); //scanning the whole string, including the white spaces
printf("%s", str);
}

94 Manoj Pandya
+91-9460378169
95
Problem Solving Through C Programming

String handling functions:-

string.h header file supports all the string functions in C language. All the string functions are
given below.

Strlen:- Syntax: - size_t strlen(const char *str)

size_t represents unsigned short, It returns the length of the string without including end character
(terminating char ‘\0’).

95 Manoj Pandya
+91-9460378169
96
Problem Solving Through C Programming

Program:-

#include <stdio.h>
#include <string.h>
int main( )
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}

Output:- Length of string str1: 13

Strcmp:- int strcmp(const char *str1, const char *str2)

It compares the two strings and returns an integer value. If both the strings are same (equal) then this
function would return 0 otherwise it may return a negative or positive value based on the comparison.

If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If
string1 > string2 then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for compare strings.

Program:-

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else{
printf("string 1 and 2 are different");}
return 0;
}

Output:- string 1 and 2 are different

Strcat:- char *strcat(char *str1, char *str2)

It concatenates two strings and returns the concatenated string.

96 Manoj Pandya
+91-9460378169
97
Problem Solving Through C Programming

Program:-

#include <stdio.h>
#include <string.h>
int main( )
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}

Output:- Output string after concatenation: HelloWorld

Strcpy:- char *strcpy( char *str1, char *str2)

It copies the string str2 into string str1, including the end character (terminator char ‘\0’).

Program:-

#include <stdio.h>
#include <string.h>
int main( )
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}

Output:- String s1 is: string 2: I’m gonna copied into s1

97 Manoj Pandya
+91-9460378169
98
Problem Solving Through C Programming

Unit-V

98 Manoj Pandya
+91-9460378169
99
Problem Solving Through C Programming

Pointers:-

A pointer is a variable which contains the address in memory of another


variable. The unary or monadic operator & gives the "address of a variable''. The indirection or
dereference operator * gives the "contents of an object pointed to by a pointer''.

Syntax: - type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is
the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used
for multiplication. However, in this statement the asterisk is being used to designate a variable as
a pointer. Take a look at some of the valid pointer declarations-

int *ip; /* pointer to an integer */


double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

 Pointers in C language is a variable that stores/points the address of another variable. A


Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable
might be belonging to any of the data type such as int, float, char, double, short etc.

 Pointer Syntax : data_type *var_name; Example : int *p; char *p;


 Where, * is used to denote that “p” is pointer variable and not a normal variable.

Key points to remember about pointers:-

 Normal variable stores the value whereas pointer variable stores the address of the
variable.
 The content of the C pointer always be a whole number i.e. address.
 Always C pointer is initialized to null, i.e. int *p = null.
 The value of null pointer is 0.

 & symbol is used to get the address of the variable.


 * symbol is used to get the value of the variable that the pointer is pointing to.
 If a pointer in C is assigned to NULL, it means it is pointing to nothing.
 Two pointers can be subtracted to know how many elements are available between these
two pointers.

 But, Pointer addition, multiplication, division are not allowed.


 The size of any pointer is 2 byte (for 16 bit compiler).

99 Manoj Pandya
+91-9460378169
100
Problem Solving Through C Programming

Pointer Arithmetic:-

We can perform arithmetic operations on the pointers like addition,


subtraction, etc. However, as we know that pointer contains the address, the result of an
arithmetic operation performed on the pointer will also be a pointer if the other operand is of
type integer. In pointer-from-pointer subtraction, the result will be an integer value. Following
arithmetic operations are possible on the pointer in C language:

 Increment
 Decrement
 Addition
 Subtraction
 Comparison

Increment:-

If we increment a pointer by 1, the pointer will start pointing to the


immediate next location. This is somewhat different from the general arithmetic since the value
of the pointer will get increased by the size of the data type to which the pointer is pointing.
We can traverse an array by using the increment operation on a pointer which will keep pointing
to every element of the array, perform some operation on that, and update itself in a loop.

The Rule to increment the pointer is: new_address= current_address + i * size_of(data type)

Where i is the number by which the pointer get increased.

 For 32-bit int variable, it will be incremented by 2 bytes.


 For 64-bit int variable, it will be incremented by 4 bytes.

Let's see the example of incrementing pointer variable on 64-bit architecture.

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p+1;
8. printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented
by 4 bytes.
9. return 0;
10. }

Output:-
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304

100 Manoj Pandya


+91-9460378169
101
Problem Solving Through C Programming

Decrement:-

Like increment, we can decrement a pointer variable. If we decrement a


pointer, it will start pointing to the previous location. The formula of decrementing the pointer is:

new_address= current_address - i * size_of(data type)

 For 32-bit int variable, it will be decremented by 2 bytes.


 For 64-bit int variable, it will be decremented by 4 bytes.

Let's see the example of decrementing pointer variable on 64-bit OS.

1. #include <stdio.h>
2. void main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-1;
8. printf("After decrement: Address of p variable is %u \n",p); // P will now point to the immidiate
previous location.
9. }

Output:-
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296

Addition:-

We can add a value to the pointer variable. The formula of adding value to
pointer is: new_address= current_address + (number * size_of(data type))

 For 32-bit int variable, it will add 2 * number.


 For 64-bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64-bit architecture.

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
101 Manoj Pandya
+91-9460378169
102
Problem Solving Through C Programming

7. p=p+3; //adding 3 to pointer variable


8. printf("After adding 3: Address of p variable is %u \n",p);
9. return 0;
10. }

Output:-
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312

As you can see, the address of p is 3214864300. But after adding 3 with p
variable, it is 3214864312, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it
increments 12. But if we were using 32-bit architecture, it was incrementing to 6 only, i.e.,
2*3=6. As integer value occupies 2-byte memory in 32-bit OS.

Subtraction:-

Like pointer addition, we can subtract a value from the pointer variable.
Subtracting any number from a pointer will give an address. The formula of subtracting value
from the pointer variable is: new_address= current_address - (number * size_of(data type))

 For 32-bit int variable, it will subtract 2 * number.


 For 64-bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from the pointer variable on 64-bit architecture.

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-3; //subtracting 3 from pointer variable
8. printf("After subtracting 3: Address of p variable is %u \n",p);
9. return 0;
10. }

Output:-
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288

102 Manoj Pandya


+91-9460378169
103
Problem Solving Through C Programming

Array of pointers:-

In computer programming, an array of pointers is an indexed set of


variables in which the variables are pointers (a reference to a location in memory).

Pointers are an important tool in computer science for creating, using,


and destroying all types of data structures. An array of pointers is useful for the same reason that
all arrays are useful: it allows you to numerically index a large set of variables.

Below is an array of pointers in C that sets each pointer in one array to


point to an integer in another and then print the values of the integers by dereferencing the
pointers. In other words, this code prints the value in memory of where the pointers point.

Program:-

#include <stdio.h>

const int ARRAY_SIZE = 5;

int main ()
{
/* first, declare and set an array of five integers: */
int array_of_integers[] = {5, 10, 20, 40, 80};

/* next, declare an array of five pointers-to-integers: */


int i, *array_of_pointers[ARRAY_SIZE];

for ( i = 0; i < ARRAY_SIZE; i++)


{
/* for indices 1 through 5, set a pointer to
point to a corresponding integer: */
array_of_pointers[i] = &array_of_integers[i];
}

for ( i = 0; i < ARRAY_SIZE; i++)


{
/* print the values of the integers pointed to
by the pointers: */
printf("array_of_integers[%d] = %d\n", i, *array_of_pointers[i] );
}

return 0;
}

Output:-

array_of_integers[0] = 5
array_of_integers[1] = 10
array_of_integers[2] = 20
array_of_integers[3] = 40
array_of_integers[4] = 80
103 Manoj Pandya
+91-9460378169
104
Problem Solving Through C Programming

Function of pointers:-
Pointer as a function parameter is used to hold addresses
of arguments passed during function call. This is also known as call by reference. When a
function is called by reference any change made to the reference variable will effect the original
variable.

Program:- Swapping two numbers using pointers.

#include <stdio.h>

void swap(int *a, int *b);

int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);

swap(&m, &n); //passing address of m and n to the swap function


printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}

/*
pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Output:-

m = 10
n = 20
After Swapping:
m = 20
n = 10

104 Manoj Pandya


+91-9460378169
105
Problem Solving Through C Programming

Structure of pointers:-

 Structure may contain the Pointer variable as member.


 Pointers are used to store the address of memory location.
 They can be de-referenced by ‘*’ operator.

struct Sample
{
int *ptr; //Stores address of integer Variable
char *name; //Stores address of Character String
}s1;

 s1 is structure variable which is used to access the “structure members”.

s1.ptr = &num;
s1.name = "Pritesh"

 Here num is any variable but it’s address is stored in the Structure member ptr
(Pointer to Integer)
 Similarly Starting address of the String “Pritesh” is stored in structure variable
name(Pointer to Character array)
 Whenever we need to print the content of variable num , we are dereferancing the
pointer variable num.

printf("Content of Num : %d ",*s1.ptr);


printf("Name : %s",s1.name);

Program:-

#include<stdio.h>

struct Student
{
int *ptr; //Stores address of integer Variable
char *name; //Stores address of Character String
}s1;

int main()
{

int roll = 20;


s1.ptr = &roll;
s1.name = "Pritesh";
105 Manoj Pandya
+91-9460378169
106
Problem Solving Through C Programming

printf("\nRoll Number of Student : %d",*s1.ptr);


printf("\nName of Student : %s",s1.name);

return(0);
}

Output:-

Roll Number of Student : 20


Name of Student : Pritesh

Dynamic memory allocation function:-

As we know, an array is a collection of a fixed number of values. Once the


size of an array is declared, you cannot change it.

Sometimes the size of the array you declared may be insufficient. To solve
this issue, you can allocate memory manually during run-time. This is known as dynamic
memory allocation in C programming.

To allocate memory dynamically, library functions are malloc(), calloc(),


realloc() and free() are used. These functions are defined in the <stdlib.h> header file.

malloc( ):- The name "malloc" stands for memory allocation.

The malloc() function reserves a block of memory of the specified number of


bytes. And, it returns a pointer of void which can be casted into pointers of any form.

Syntax:- ptr = (cast-type*) malloc(byte-size)

Example:- ptr = (int*) malloc(100 * sizeof(float));

106 Manoj Pandya


+91-9460378169
107
Problem Solving Through C Programming

calloc( ):- The name "calloc" stands for contiguous allocation.

The malloc() function allocates a single block of memory. Whereas, calloc()


allocates multiple blocks of memory and initializes them to zero.

Syntax:- ptr = (cast-type*)calloc(n, element-size);

Example:- ptr = (float*) calloc(25, sizeof(float));

free( ):-

Dynamically allocated memory created with either calloc() or malloc() doesn't


get freed on their own. You must explicitly use free() to release the space.

Syntax:- free(ptr);

realloc( ):-

If the dynamically allocated memory is insufficient or more than required, you


can change the size of previously allocated memory using the realloc() function.

Syntax:- ptr = realloc(ptr, x);

Program:- malloc() and free()

1. // Program to calculate the sum of n numbers entered by the user


2.
3. #include <stdio.h>
4. #include <stdlib.h>
5.
6. int main()
7. {
8. int n, i, *ptr, sum = 0;
9.
10. printf("Enter number of elements: ");
11. scanf("%d", &n);
12.
13. ptr = (int*) malloc(n * sizeof(int));
14.
15. // if memory cannot be allocated
16. if(ptr == NULL)
107 Manoj Pandya
+91-9460378169
108
Problem Solving Through C Programming

17. {
18. printf("Error! memory not allocated.");
19. exit(0);
20. }
21.
22. printf("Enter elements: ");
23. for(i = 0; i < n; ++i)
24. {
25. scanf("%d", ptr + i);
26. sum += *(ptr + i);
27. }
28.
29. printf("Sum = %d", sum);
30.
31. // deallocating the memory
32. free(ptr);
33.
34. return 0;
35. }

Here, we have dynamically allocated the memory for n number of int.

Program:- calloc( ) and free( )

1. // Program to calculate the sum of n numbers entered by the user


2.
3. #include <stdio.h>
4. #include <stdlib.h>
5.
6. int main()
7. {
8. int n, i, *ptr, sum = 0;
9. printf("Enter number of elements: ");
10. scanf("%d", &n);
11.
12. ptr = (int*) calloc(n, sizeof(int));
13. if(ptr == NULL)
14. {
15. printf("Error! memory not allocated.");
16. exit(0);
17. }
18.
19. printf("Enter elements: ");
20. for(i = 0; i < n; ++i)
21. {
22. scanf("%d", ptr + i);
23. sum += *(ptr + i);
24. }

108 Manoj Pandya


+91-9460378169
109
Problem Solving Through C Programming

25.
26. printf("Sum = %d", sum);
27. free(ptr);
28. return 0;
29. }

Program:- realloc( )

1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. int main()
5. {
6. int *ptr, i , n1, n2;
7. printf("Enter size: ");
8. scanf("%d", &n1);
9.
10. ptr = (int*) malloc(n1 * sizeof(int));
11.
12. printf("Addresses of previously allocated memory: ");
13. for(i = 0; i < n1; ++i)
14. printf("%u\n",ptr + i);
15.
16. printf("\nEnter the new size: ");
17. scanf("%d", &n2);
18.
19. // rellocating the memory
20. ptr = realloc(ptr, n2 * sizeof(int));
21.
22. printf("Addresses of newly allocated memory: ");
23. for(i = 0; i < n2; ++i)
24. printf("%u\n", ptr + i);
25. return 0;
26. }

Output:-

Enter size: 2
Addresses of previously allocated memory:26855472
26855476

Enter the new size: 4


Addresses of newly allocated memory:26855472
26855476
26855480
26855484
109 Manoj Pandya
+91-9460378169
110
Problem Solving Through C Programming

Structure and Union:-


In C programming, a struct (or structure) is a collection of
variables (can be of different types) under a single name.
Structure is a user-defined datatype in C language which allows us
to combine data of different types together. Structure helps to construct a complex data type
which is more meaningful. It is somewhat similar to an Array, but an array holds data of similar
type only. But structure on the other hand, can store data of any type, which is practical more
useful.

Defining a structure:-

struct keyword is used to define a structure. struct defines a new


data type which is a collection of primary and derived datatypes.

Syntax:

struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];

Example:-

struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};

Here struct Student declares a structure to hold the details of a student


which consists of 4 data fields, namely name, age, branch and gender. These fields are
called structure elements or members. Each member can have different datatype, like in this
case, name is an array of char type and age is of int type etc. Student is the name of the
structure and is called as the structure tag.

110 Manoj Pandya


+91-9460378169
111
Problem Solving Through C Programming

Declaration of structures:-
It is possible to declare variables of a structure, either along with
structure definition or after the structure is defined. Structure variable declaration is similar to
the declaration of any normal variable of any other datatype. Structure variables can be declared
in following two ways:

 Declaring Structure variables separately


 Declaring Structure variables with structure definition

Declaring Structure variables separately:-

struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};

struct Student S1, S2; //declaring variables of struct Student

Declaring Structure variables with structure definition:-

struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;

111 Manoj Pandya


+91-9460378169
112
Problem Solving Through C Programming

Structure Initialization:-
Like a variable of any other datatype, structure variable can also
be initialized at compile time.

struct Patient
{
float height;
int weight;
int age;
};

struct Patient p1 = { 180.75 , 73, 23 }; //initialization

Or

struct Patient p1;


p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;

Accessing structure members:-


Structure members can be accessed and assigned values in a
number of ways. Structure members have no meaning individually without the structure. In order
to assign a value to any structure member, the member name must be linked with the structure
variable using a dot . operator also called period or member access operator.

Program:-
#include<stdio.h>
#include<string.h>

struct Student
{
char name[25];
int age;
char branch[10];
112 Manoj Pandya
+91-9460378169
113
Problem Solving Through C Programming

//F for female and M for male


char gender;
};

int main()
{
struct Student s1;

/*
s1 is a variable of Student type and
age is a member of Student
*/
s1.age = 18;
/*
using string function to add name
*/
strcpy(s1.name, "Viraaj");
/*
displaying the stored values
*/
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);

return 0;
}

Output:-

Name of Student 1: Viraaj Age of Student 1: 18

Functions and Structures:-

Similar to variables of built-in types, you can also pass structure variables to a function.

Program:-

1. #include <stdio.h>
2. struct student
3. {
4. char name[50];
5. int age;
6. };
113 Manoj Pandya
+91-9460378169
114
Problem Solving Through C Programming

7.
8. // function prototype
9. void display(struct student s);
10.
11. int main()
12. {
13. struct student s1;
14.
15. printf("Enter name: ");
16. scanf("%[^\n]%*c", s1.name);
17.
18. printf("Enter age: ");
19. scanf("%d", &s1.age);
20.
21. display(s1); // passing struct as an argument
22.
23. return 0;
24. }
25. void display(struct student s)
26. {
27. printf("\nDisplaying information\n");
28. printf("Name: %s", s.name);
29. printf("\nAge: %d", s.age);
30. }

Ooutput:-

Enter name: Bond


Enter age: 13

Displaying information
Name: Bond
Age: 13

Here, a struct variable s1 of type struct student is created. The variable is


passed to the display( ) function using display(s1); statement.

114 Manoj Pandya


+91-9460378169
115
Problem Solving Through C Programming

Array of structure:-

We can also declare an array of structure variables. in which each


element of the array will represent a structure variable.

Program:-

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[30];
float percentage;
};

int main()
{
int i;
struct student record[2];

// 1st student's record


record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;

// 2nd student's record


record[1].id=2;
strcpy(record[1].name, "Surendra");
record[1].percentage = 90.5;

// 3rd student's record


record[2].id=3;
strcpy(record[2].name, "Raj");
record[2].percentage = 81.5;

for(i=0; i<3; i++)


{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
}

115 Manoj Pandya


+91-9460378169
116
Problem Solving Through C Programming

Output:-

Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000

Records of STUDENT : 2
Id is: 2
Name is: Surendra
Percentage is: 90.500000

Records of STUDENT : 3
Id is: 3
Name is: Raj
Percentage is: 81.500000

Self-referential Structure:-

Self Referential structures are those structures that have one or more
pointers which point to the same type of structure, as their member. Self Referential Structure is
the Data Structure in which the pointer refers (points) to the structure of the same type. It used in
the many of the data structures like in Linked List, Trees, Graphs, Heap etc.

Singly Linked List:-

Doubly Linked List:-

116 Manoj Pandya


+91-9460378169
117
Problem Solving Through C Programming

struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob;
return 0;
}

In the above example ‘link’ is a pointer to a structure of type ‘node’.


Hence, the structure ‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before accessing,
as by default it contains garbage value.

Types of Self Referential Structures:-

 Self Referential Structure with Single Link


 Self Referential Structure with Multiple Links

117 Manoj Pandya


+91-9460378169
118
Problem Solving Through C Programming

Self Referential Structure with Single Link:-

These structures can have only one self-pointer as their member. The
following example will show us how to connect the objects of a self-referential structure with the
single link and access the corresponding data members. The connection formed is shown in the
following figure-

Program:-

#include <stdio.h>

struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob1; // Node1

// Intialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;

struct node ob2; // Node2

// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;

// Linking ob1 and ob2


ob1.link = &ob2;

// Accessing data members of ob2 using ob1

118 Manoj Pandya


+91-9460378169
119
Problem Solving Through C Programming

printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}

Output:-

30
40

Self Referential Structure with Multiple Links:-

Self referential structures with multiple links can have more than one
self-pointers. Many complicated data structures can be easily constructed using these structures.
Such structures can easily connect to more than one nodes at a time. The following example
shows one such structure with more than one links. The connections made in the above example
can be understood using the following figure-

Program:-

#include <stdio.h>

struct node {
int data;
struct node* prev_link;
struct node* next_link;
};

int main()
{
struct node ob1; // Node1

// Intialization
ob1.prev_link = NULL;
ob1.next_link = NULL;

119 Manoj Pandya


+91-9460378169
120
Problem Solving Through C Programming

ob1.data = 10;

struct node ob2; // Node2

// Intialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;

struct node ob3; // Node3

// Intialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;

// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;

// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;

// Accessing data of ob1, ob2 and ob3 by ob1


printf("%d\t", ob1.data);
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);

// Accessing data of ob1, ob2 and ob3 by ob2


printf("%d\t", ob2.prev_link->data);
printf("%d\t", ob2.data);
printf("%d\n", ob2.next_link->data);

// Accessing data of ob1, ob2 and ob3 by ob3


printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", ob3.data);
return 0;
}

Output:-

10 20 30
10 20 30
10 20 30

120 Manoj Pandya


+91-9460378169
121
Problem Solving Through C Programming

Unions:-
Like Structures, union is a user defined data type. In union, all members share
the same memory location.

Proram:- both x and y share the same location. If we change x, we can see the changes being
reflected in y.

#include <stdio.h>

// Declaration of union is same as structures


union test {
int x, y;
};

int main()
{
// A union variable t
union test t;

t.x = 2; // t.y also gets value 2


printf("After making x = 2:\n x = %d, y = %d\n\n",
t.x, t.y);

t.y = 10; // t.x is also updated to 10


printf("After making y = 10:\n x = %d, y = %d\n\n",
t.x, t.y);
return 0;
}

121 Manoj Pandya


+91-9460378169
122
Problem Solving Through C Programming

Output:-

After making x = 2:
x = 2, y = 2

After making y = 10:


x = 10, y = 10

Enumeration ( enum):-
Enumeration (or enum) is a user defined data type in C. It is mainly
used to assign names to integral constants, the names make a program easy to read and maintain.

Syntax:- enum flag {const1, const2, ..., constN};

122 Manoj Pandya


+91-9460378169
123
Problem Solving Through C Programming

Program:-

// An example program to demonstrate working

// of enum in C
#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}

Output:- 2

In the above example, we declared “day” as the variable and the value
of “Wed” is allocated to day, which is 2. So as a result, 2 is printed.

File Handling:-

So far the operations using C program are done on a prompt / terminal


which is not stored anywhere. But in the software industry, most of the programs are written to
store the information fetched from the program. One such way is to store the fetched information
in a file. Different operations that can be performed on a file are:-

 Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
 Opening an existing file (fopen)
 Reading from file (fscanf or fgetc)
 Writing to a file (fprintf or fputs)
 Moving to a specific location in a file (fseek, rewind)
 Closing a file (fclose)

The text in the brackets denotes the functions used for performing those operations.

123 Manoj Pandya


+91-9460378169
124
Problem Solving Through C Programming

Why files are needed?

 When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using a few commands in C.
 You can easily move your data from one computer to another without any changes.

Types of Files:-

When dealing with files, there are two types of files you should know about:

 Text files
 Binary files

Text files:-

Text files are the normal .txt files. You can easily create text files using any
simple text editors such as Notepad. When you open those files, you'll see all the contents within
the file as plain text. You can easily edit or delete the contents. They take minimum effort to
maintain, are easily readable, and provide the least security and takes bigger storage space.

Binary files:-

Binary files are mostly the .bin files in the computer. Instead of storing
data in plain text, they store it in the binary form (0's and 1's). They can hold a higher amount of
data, are not readable easily, and provides better security than text files.

124 Manoj Pandya


+91-9460378169
125
Problem Solving Through C Programming

File Operations:-

1. Creating a new file


2. Opening an existing file
3. Reading from file
4. Writing in the file
5. Delete the file
6. Closing a file

Opening or creating file:-


For opening a file, fopen function is used with the required access
modes. Some of the commonly used file access modes are mentioned below.

File opening modes in C:

 “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and
sets up a pointer which points to the first character in it. If the file cannot be opened
fopen( ) returns NULL.
 “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist,
a new file is created. Returns NULL, if unable to open file.
 “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and
sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is
created. Returns NULL, if unable to open file.
 “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the first character in it. Returns NULL, if unable to open the file.
 “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t
exist a new file is created. Returns NULL, if unable to open file.
 “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and
sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file
is created. Returns NULL, if unable to open file.

As given above, if you want to perform operations on a binary file,


then you have to append ‘b’ at the last. For example, instead of “w”, you have to use “wb”,
instead of “a+” you have to use “a+b”. For performing the operations on the file, a special
pointer called File pointer is used which is declared as

FILE *filePointer;
So, the file can be opened as
filePointer = fopen(“fileName.txt”, “w”)

125 Manoj Pandya


+91-9460378169
126
Problem Solving Through C Programming

Reading from a file:-

The file read operations can be performed using functions


fscanf or fgets. Both the functions performed the same operations as that of printf and gets but
with an additional parameter, the file pointer. So, it depends on you if you want to read the file
line by line or character by character. And the code snippet for reading a file is as-

FILE * filePointer;
filePointer = fopen(“fileName.txt”, “r”);
fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);

Writing a file:-

The file write operations can be perfomed by the functions fprintf and fputs
with similarities to read operations. The snippet for writing to a file is as-

FILE *filePointer ;
filePointer = fopen(“fileName.txt”, “w”);
fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);

Closing a file:-

After every successful fie operations, you must always close a file. For
closing a file, you have to use fclose function. The snippet for closing a file is given as-

FILE *filePointer ;
filePointer= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(filePointer)

126 Manoj Pandya


+91-9460378169
127
Problem Solving Through C Programming

Program:- Program to Open a File, Write in it, And Close the File

// C program to Open a File,


// Write in it, And Close the File

# include <stdio.h>
# include <string.h>

int main( )
{

// Declare the file pointer


FILE *filePointer ;

// Get the data to be written in file


char dataToBeWritten[50]
= "GeeksforGeeks-A Computer Science Portal for Geeks";

// Open the existing file GfgTest.c using fopen()


// in write mode using "w" attribute
filePointer = fopen("GfgTest.c", "w") ;

// Check if this filePointer is null


// which maybe if the file does not exist
if ( filePointer == NULL )
{
printf( "GfgTest.c file failed to open." ) ;
}
else
{

printf("The file is now opened.\n") ;

// Write the dataToBeWritten into the file


if ( strlen ( dataToBeWritten ) > 0 )
{

// writing in the file using fputs()


fputs(dataToBeWritten, filePointer) ;
fputs("\n", filePointer) ;
}

// Closing the file using fclose()


fclose(filePointer) ;

printf("Data successfully written in file GfgTest.c\n");


printf("The file is now closed.") ;
}
return 0;
}
127 Manoj Pandya
+91-9460378169
128
Problem Solving Through C Programming

Program:- Program to Open a File, Read from it, And Close the File

// C program to Open a File,


// Read from it, And Close the File

# include <stdio.h>
# include <string.h>

int main( )
{

// Declare the file pointer


FILE *filePointer ;

// Declare the variable for the data to be read from file


char dataToBeRead[50];

// Open the existing file GfgTest.c using fopen()


// in read mode using "r" attribute
filePointer = fopen("GfgTest.c", "r") ;

// Check if this filePointer is null


// which maybe if the file does not exist
if ( filePointer == NULL )
{
printf( "GfgTest.c file failed to open." ) ;
}
else
{
printf("The file is now opened.\n") ;

// Read the dataToBeRead from the file


// using fgets() method
while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
{
// Print the dataToBeRead
printf( "%s" , dataToBeRead ) ;
}

// Closing the file using fclose()


fclose(filePointer) ;
printf("Data successfully read from file GfgTest.c\n");
printf("The file is now closed.") ;
}
return 0;
}

128 Manoj Pandya


+91-9460378169

You might also like