Problem Solving Through C Programming
Problem Solving Through C Programming
.056
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
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
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
Flowchart Symbols:-
6 Manoj Pandya
+91-9460378169
7
Problem Solving Through C Programming
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.
7 Manoj Pandya
+91-9460378169
8
Problem Solving Through C Programming
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.
10 Manoj Pandya
+91-9460378169
11
Problem Solving Through C Programming
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.
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 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
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:-
2. Problem Analysis:-
3. Algorithm Development:-
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:
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.
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:-
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.
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.
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
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”
24 Manoj Pandya
+91-9460378169
25
Problem Solving Through C Programming
Symbolic Constants:-
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.
/* actual initialization */
width = 10;
25 Manoj Pandya
+91-9460378169
26
Problem Solving Through C Programming
age = 26.5;
#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( );
}
Expressions:-
26 Manoj Pandya
+91-9460378169
27
Problem Solving Through C Programming
a x b – c a * b – c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a * b / c
(x / y) + c x / y + c
Operators:-
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:-
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
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( );
}
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
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:
Note:
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 operators return one value if condition is true and returns another value is
condition is false.
This operator is also called as ternary operator.
35 Manoj Pandya
+91-9460378169
36
Problem Solving Through C Programming
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
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
39 Manoj Pandya
+91-9460378169
40
Problem Solving Through C Programming
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.
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.
Program: A simple program is written as below, which will read a single character using
getchar() function and display inputted data using putchar() function:
c) gets():-
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.
d) puts():-
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.
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.
OUTPUT:
Enter the Char L
Char is L
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.
Where arg1,arg2,..........argn are the arguments for reading and v1,v2,v3,........vn all are the
variables.
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( ):-
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( );
}
if statement
switch statement
conditional operator statement (Ternary Operator)
goto statement
47 Manoj Pandya
+91-9460378169
48
Problem Solving Through C Programming
1. Simple if statement
2. If....else statement
3. Nested if....else statement
4. else if statement (Else if ladder)
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");
}
}
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;
}
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();
}
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:-
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;
}
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
#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 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:-
While loop:-
while(condition) {
statement(s);
}
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.
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.
statement(s);
}
63 Manoj Pandya
+91-9460378169
64
Problem Solving Through C Programming
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
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.
66 Manoj Pandya
+91-9460378169
67
Problem Solving Through C Programming
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
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 ()
{
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 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.
68 Manoj Pandya
+91-9460378169
69
Problem Solving Through C Programming
Flow Chart:-
69 Manoj Pandya
+91-9460378169
70
Problem Solving Through C Programming
# 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:-
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.
Flowchart:-
71 Manoj Pandya
+91-9460378169
72
Problem Solving Through C Programming
# 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:-
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:-
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 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.
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:-
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 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
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;
return 0;
}
77 Manoj Pandya
+91-9460378169
78
Problem Solving Through C Programming
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:-
For the above defined function max(), the function declaration is as follows:-
Parameter names are not important in function declaration only their type is required, so the
following is also a valid declaration:-
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:-
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:-
79 Manoj Pandya
+91-9460378169
80
Problem Solving Through C Programming
Category of functions:-
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
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;
}
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;
}
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;
}
82 Manoj Pandya
+91-9460378169
83
Problem Solving Through C Programming
Parameter passing:-
"Parameters are the data values that are passed from calling function to called function."
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:-
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 ;
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 ;
Output:-
86 Manoj Pandya
+91-9460378169
87
Problem Solving Through C Programming
Recursion:-
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;
}
87 Manoj Pandya
+91-9460378169
88
Problem Solving Through C Programming
Array:-
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].
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 ].
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 () {
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
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.
data_type array_name[size1][size2];
int twodimen[4][3];
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];
Output:-
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3
Character array:-
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
Remember that when you initialize a character array by listing all of its characters
separately then you must supply the '\0' character explicitly.
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.h header file supports all the string functions in C language. All the string functions are
given below.
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;
}
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;
}
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;
}
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;
}
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:-
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-
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.
99 Manoj Pandya
+91-9460378169
100
Problem Solving Through C Programming
Pointer Arithmetic:-
Increment
Decrement
Addition
Subtraction
Comparison
Increment:-
The Rule to increment the pointer is: new_address= current_address + i * size_of(data type)
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
Decrement:-
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))
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
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))
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
Array of pointers:-
Program:-
#include <stdio.h>
int main ()
{
/* first, declare and set an array of five integers: */
int array_of_integers[] = {5, 10, 20, 40, 80};
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.
#include <stdio.h>
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
/*
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
Structure of pointers:-
struct Sample
{
int *ptr; //Stores address of integer Variable
char *name; //Stores address of Character String
}s1;
s1.ptr = #
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.
Program:-
#include<stdio.h>
struct Student
{
int *ptr; //Stores address of integer Variable
char *name; //Stores address of Character String
}s1;
int main()
{
return(0);
}
Output:-
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.
free( ):-
Syntax:- free(ptr);
realloc( ):-
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. }
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
Defining a structure:-
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;
};
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:
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;
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;
};
Or
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
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:-
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:-
Displaying information
Name: Bond
Age: 13
Array of structure:-
Program:-
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
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.
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
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;
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}
Output:-
30
40
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;
ob1.data = 10;
// Intialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;
// 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;
Output:-
10 20 30
10 20 30
10 20 30
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>
int main()
{
// A union variable t
union test t;
Output:-
After making x = 2:
x = 2, y = 2
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.
Program:-
// of enum in C
#include<stdio.h>
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:-
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.
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.
File Operations:-
“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.
FILE *filePointer;
So, the file can be opened as
filePointer = fopen(“fileName.txt”, “w”)
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)
Program:- Program to Open a File, Write in it, And Close the File
# include <stdio.h>
# include <string.h>
int main( )
{
Program:- Program to Open a File, Read from it, And Close the File
# include <stdio.h>
# include <string.h>
int main( )
{