PPS Course File
PPS Course File
COURSE FILE
B.Tech (CSE,IT,AI&ML,CS,DS) I Year – I Semester
R22 Regulation
REGULATION: R22
3 0 0 3
Course Objectives:
● To learn the fundamentals of computers.
● To understand the various steps in program development.
● To learn the syntax and semantics of the C programming language.
● To learn the usage of structured programming approaches in solving problems.
Introduction to C Programming Language: variables (with data types and space requirements),
Syntax and Logical Errors in compilation, object and executable code, Operators, expressions and
precedence, Expression evaluation, Storage classes (auto, extern, static and register), type conversion,
The main method and command line arguments Bitwise operations: Bitwise AND, OR, XOR and NOT
operators Conditional Branching and Loops: Writing and evaluation of conditionals and consequent
branching with if, if-else, switch-case, ternary operator, goto, Iteration with for, while, do- while loops
I/O: Simple input and output with scanf and printf, formatted I/O, Introduction to stdin, stdout and stderr.
Command line arguments
Arrays: one and two dimensional arrays, creating, accessing and manipulating elements of arrays
Strings: Introduction to strings, handling strings as array of characters, basic string functions available
in C (strlen, strcat, strcpy, strstr etc.), arrays of strings
Structures: Defining structures, initializing structures, unions, Array of structures
Programming For Problem Solving
Pointers: Idea of pointers, Defining pointers, Pointers to Arrays and Structures, Use of Pointers in self-
referential structures, usage of self referential structures in linked list (no implementation) Enumeration
data type
Preprocessor: Commonly used Preprocessor commands like include, define, undef, if, ifdef, ifndef
Files: Text and Binary files, Creating and Reading and writing text and binary files, Appending data to
existing files, Writing and reading structures using binary files, Random access using fseek, ftell and
rewind functions.
Recursion: Simple programs, such as Finding Factorial, Fibonacci series etc., Limitations of Recursive
functions Dynamic memory allocation: Allocating and freeing memory, Allocating memory for arrays of
different data types
Basic searching in an array of elements (linear and binary search techniques), Basic algorithms to sort
array of elements (Bubble, Insertion and Selection sort algorithms), Basic concept of order of complexity
through the example programs
TEXT BOOKS:
1. Jeri R. Hanly and Elliot B.Koffman, Problem solving and Program Design in C 7th Edition,
Pearson
2. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage Learning, (3rd
Edition)
REFERENCE BOOKS:
1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall of
India
2. E. Balagurusamy, Computer fundamentals and C, 2nd Edition, McGraw-Hill
3. Yashavant Kanetkar, Let Us C, 18th Edition, BPB
4. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
5. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
6. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition
7. Byron Gottfried, Schaum’s Outline of Programming with C, McGraw-Hill
Programming For Problem Solving
UNIT -1
COMPUTER :
It is a high speed electronic device that accepts and stores input data and instructions, processes
the data and produces the desired output.
Input Output
(raw data / Instructions) (Information i.e. processed
data)
Characteristics of computers
Speed: the computer process data at an extremely fast rate, at millions of instructions
per second.
Reliability: computer provide very high speed accompanied by an equally high level of
reliability.
Accuracy: the level of accuracy depends on the instrucations and the type of processor
used in the computer
Storage capacity: computers are capable of storing enormous amounts of data that can
be located and retrieved very quickly
COMPUTER SYSTEMS
* It is made up of 2 major components
Computer Hardware :
These are the physical components of a computer
It consists of 5 Parts
1) Input Devices 2) Output Devices 3) CPU 4) Primary Storage 5) Secondary Storage
Programming For Problem Solving
ALU CU
Input Output
Devices Devices
Primary Memory
These are used to enter data and programs into the computer
These are for man to machine communication
egs: Keyboard, mouse, scanner, touch screen, audio input.
Output Devices
These are used to get the desired output from the computer
These are for machine to man communication
egs: Printer, Monitor, Speakers
If the output is shown on monitor then it is called “Soft copy”
If the output is printed on a paper using printer then it is called “hard copy”
CPU (Central Processing Unit)
It is responsible for processing the instructions
It consists of 3 parts
1) ALU – Arithmetic & Logic Unit
2) CU- Control Unit
3) Memory
ALU performs arithmetic operations like addition,subtraction,multiplication,division and
logical operations like comparisons among data
CU is responsible for movement of data inside the system
Programming For Problem Solving
Memory is used for storage of data and programs. It is divided into 2 parts.
1) Primary Memory/ Main Memory
2) Secondary Memory/ Auxilary Memory
1) Primary Memory
It is also called main memory
Data is stored temporarily i.e. data gets erased when computer is turned off
Eg: RAM
2) Secondary Memory
It is also called as auxilary memory
Data is stored permanently so that user can reuse the data even after power loss.
Eg: Hard disk, CD, DVD, Floppy etc.
Operating System
It acts as an interface between the user and the hardware
It makes the system to operate in an efficient manner
Egs: MS DOS, Windows, UNIX, LINUX, etc.
System Support
They provide some utilities and other operating services
eg: Sort utilities, disk formatting utilities, Security monitors
COMPUTER LANGUAGES
Computer programming languages are used to give instructions to the computer in a
language which computer understands
Computer languages are classified into 3 types
1) Machine languages
2) Symbolic languages
3) High level languages
1) Machine languages
Computer is a machine and since its memory can store only 1‟s and 0‟s, instructions must
be given to the computer in streams of 1‟s and 0‟s i.e. binary code.
These are easily understandable by the machine
Programming For Problem Solving
Programs written in binary code can be directly fed to computer for execution and it is
known as machine language.
Advantage :
Execution is very fast since there is no need of conversion
Disadvantage :
Writing and reading programs in machine language is very difficult
Machine instructions are difficult to remember
2) Symbolic Languages
It is also called as assembly language
An assembly program contains “Mnemonics”
“Mnemonic” means information can be memorized easily and is generally in the form of
abbreviations.
Advantage :
Easy to read and write programs in assembly language when compared to machine
language
Mnemonics are easy to remember
Disadvantage :
Assembly programs are machine dependent
Execution is slow since it needs conversion into machine language
“Assembler” is used to convert assembly language program into machine language.
Assembler
Assembly language program Machine Language
code
3) High level languages
A set of languages which are very close to our native languages are called “ high-level
languages”.
High level languages have control structures, I/O facilities, hardware independence
eg: FORTRAN, COBOL, PASCAL, C, C++ etc..
Advantage :
Machine independence i.e. programs are “Portable” i.e. programs can be moved from one
system to another
Programming For Problem Solving
Compiler /
High level language program Interpreter Machine Language code
C file
#include<stdio.h>
Programmer Text Editor Source file main ( )
{
-----
-----
-----
}
Programming For Problem Solving
Preprocessor
Source File translation unit
B) Translator
It does the actual work of converting the program into machine language
It reads the translation unit and results in „object module‟ i.e., code in machine language
But it is not yet executable because it does not have the „C‟ and other functions included.
Translator
Translation unit Object Module .obj file
00110 100
10101 010
3) Linking programs
„Linker‟ assembles input /output functions, mathematical library functions and some of
the functions that are part of source program into final executable program
It is called as executable file that it is ready for execution .exe file
1011001100
Linker 110111011
Object file executable file 1100101010
Programming For Problem Solving
4) Executing Programs
„Loader‟ is the software that gets the program that is ready for execution into the
memory
When everything is loaded, the program takes control and the „Runner‟ begins its
execution.
In the process of execution, the program reads the data from the user, processes the data
and prepares the output
Main objective of this phase is to eliminate unimportant aspects and identify the root
problem
2) Analysis
It involves identifying the problem inputs, outputs, that the program must produce
It also determines the required format in which results should be displayed
3) Design
It involves designing algorithms, flowcharts (or) GUI‟s (Graphical User Interfaces)
Designing the „algorithm‟ is to develop a list of steps called algorithm to solve the
problem and then verify that the algorithm solves the problem intended.
“Top – down design” is followed i.e. list the major steps (or) sub problems that need to
be solved
“Flow charts” are used to get the pictorial representation of the algorithm.
Algorithm for a programming problem consists of at least the following sub problems
1. Get the data
2. Perform the computations
3. Display the results
4) Coding / Implementation
This step involves writing algorithm as a program by selecting any one of the high – level
languages that is suitable for the problem.
Each step of the algorithm is converted into one (or) more statements in a programming
language.
5) Testing
Checking / verifying whether the completed program works as desired is called “
Testing”
Running the program several times using different sets of data verifies whether a program
works correctly for every situation provided in the algorithm.
After testing, the program must be free from the following errors.
a) Syntax errors
Programming For Problem Solving
b) Logical errors
c) Run-time errors
6) Maintenance
It involves modifying a program to remove previously undetected errors and to keep
it up-to-date as government regulations (or) company polices change.
Many organizations maintains a program for some period of time i.e. 5 years
System
requirements
Analysis
Design
Coding
Testing
b b 2 4ac
Procedure : r1
2a
Programming For Problem Solving
b b 2 4ac
r2
2a
3) Design
Algorithm
1. start
2. Read a,b,c values
3. Compute d = b2 4ac
4. if d > 0 then
a) r1 = b+ sqrt (d)/(2*a)
b) r2 = b sqrt(d)/ (2*a)
5. otherwise if d = 0 then
a) compute r1 = -b/2a
r2=-b/2a
b) print r1,r2 values
6. otherwise if d < 0 then print roots are imaginary
7. Stop
4. Implementation
# include<stdio.h>
# include<conio.h>
# include<math.h>
main ( )
{
float a,b,c,r1,r2,d;
clrscr ( );
printf (“enter a,b,c values”);
scanf (“ %f %f %f”, &a, &b, &c);
d= b*b – 4*a*c;
if (d>0)
{
Programming For Problem Solving
ALGORITHM:
It is a step – by – step procedure for solving a problem
If algorithm is written in English like sentences then it is called as „PSEUDO CODE‟
Properties of an Algorithm
An algorithm must posses the following 5 properties. They are
1. Input
2. Output
Programming For Problem Solving
3. Finiteness
4. Definiteness
5. Effectiveness
1. Input : An algorithm must have zero (or) more number of inputs
2. Output: Algorithm must produce one (or) more number of outputs
3. Finiteness : An algorithm must terminate in countable number of steps
4. Definiteness: Each step of the algorithm must be stated clearly
5. Effectiveness: Each step of the algorithm must be easily convertible into program
statements
Example
Algorithm for finding the average of 3 numbers
1. start
2. Read 3 numbers a,b,c
3. Compute sum = a+b+c
4. compute avg = sum/3
5. Print avg value
6. Stop
FLOW CHART
Diagramatic representation of an algorithm is called flow chart
Advantages of flow chart
It is very easy to understand because the reader follows the process quickly from the
flowchart instead of going through the text.
Arrows are used for connecting the symbols and show the flow of execution
Programming For Problem Solving
oval
Input / output Input/output of data
Parallelogram
Process Any processing to be
performed can be represented
Rectangle
Decision box Decision operations that
determine which of the
alternative paths to be
Diamond followed
Connector Used to connect different
parts of flowchart
Circle
Flow Joins 2 symbols and also
represents flow of execution
Arrows
Pre defined process Modules (or)subroutines
specified else where
Pentagon
For loop symbol Shows initialization,
condition and incrementation
of loop variable.
Hexagon
Document Shows the data that is ready
for printout
Printout
Programming For Problem Solving
Example
Flowchart for finding the average of 3 numbers
Start
Stop
Example:
/* Author : Ramu
Aim : Program for finding circumference of circle*/
#include<stdio.h>
#include<conio.h>
#define PI 3.1415
main ( )
{
float c, r;
clrscr ( );
printf (“enter radius of circle”);
scanf (“%f”, &r);
c = 2 * PI * r;
Programming For Problem Solving
2. Preprocessor directives
It consists of a) link section
b) Definition Section
The link section provides instructions to the compiler to link functions from the system
library
eg : #include < stdio.h>
The definition section defines all symbolic constants
eg : #define PI 3.1415
Preprocessor directive must start with „#‟ (hash) symbol.
3. Variable declaration & data types
Variable
It is the name given to a memory location that may be used to store a data value
A variable may take different values at different times during execution
Programming For Problem Solving
Integral Type
Integer
character
Signed Unsigned
signed char
int unsigned int
short int unsigned short int unsigned char
long int unsigned long int
„local declaration‟ is declaring a variable inside the main block and its value is available
within that block
„global declaration‟ is declaring a variable outside the main block and its value is available
through out the program.
Eg :
int a, b; /* global declaration*/
main ( )
{
int c; /* local declaration*/
- - -
}
EXECUTABLE STATEMENTS:
A „C‟ program contains executable statements
The „C‟ compiler translates the executable statements into machine language
The machine language versions of these statements are executed by the compiler when a
user runs program
Types
1) Input – output statements
2) Assignment statements
1. Input – output statements
Storing a value into memory is called „ input operation‟.
After executing the computations, the results are stored in memory and the results can be
displayed to the user by „output operation‟
All input / output operations in „C‟ are performed using input / output functions
The most common I/O functions are supplied as part of the „C‟ standard I/O library
through the preprocessor directive # include<stdio.h>
Most commonly used I/O functions are
a) printf ( )
b) scanf ( )
a) printf ( ) function:
Programming For Problem Solving
Syntax:
printf(“format string”, print list);
e.g.: printf (“average of 3 numbers = %f”,avg);
* The printf ( ) function displays the value of its format string after substituting the
values of the expressions in the print list.
* It also replaces the escape sequences such as „\n‟ by their meanings.
b) scanf ( ) function
Syntax:
scanf (“format string”, input list);
e.g.: scanf (“%d %f”, &a, &b);
The scanf ( ) function copies into memory data typed at the keyboard by the program user
during program execution.
The input list must be preceded by ampersand ( &)
2) Assignment statements
The assignment statements stores a value (or) a computational result in a variable and is
used to perform most arithmetic operations in a program.
Syntax: variable=expression
e.g.:
1. c = a+b;
2. avg = sum/3;
3. r1 = (b*b – 4 * a*c);
The variable before the assignment operator is assigned the value of the expression after
it.
The previous value of variable is destroyed
EXPRESSIONS
Def: An expression is a combination of operators and operands which reduces to a single
value
An operand is a data item on which an operation is performed.
An operator indicates an operation to be performed on data
Programming For Problem Solving
eg; z = 3+2*1
z=5
Types Expression
1. Primary expressions
The operand in the primary expression can be a name, a constant or any parenthesized expression
E.g.: c = a+ (5*b);
2. Postfix expressions:
The operator will be after the operands in a postfix expression
Eg:
ab+
3. Prefix expressions
The operator is before the operand in a prefix expression.
Eg:
+ab
4. unary expression:
It contains one operator and one operand
eg: a++, --b
5. Binary expression
It contains 2 operands and one operator
Eg: a+b, c-d
6. Ternary expression
It contains 3 operands and one operator
Eg ; Exp1? Exp2 :Exp3
If Exp1 is true ,Exp2 is executed. otherwise Exp3 is executed.
Programming For Problem Solving
Program:
main ( )
{
int a= 20, b = 10; Output
printf (“ %d”, a+b); 30
The output of a relational expression is either true (1) (or) false (0)
Program
main ( )
{
int a= 10, b = 20; Output
printf (“ %d”, a<b); 1
printf (“ %d”, a<=b); 1
printf (“ %d”, a>b); 0
printf (“ %d”, a>=b); 0
printf (“ %d”, a = =b); 0
printf (“ %d”, a ! =b); 1
} 1
1
3. Logical Operators
These are used to combine 2 (or) more expressions logically
Programming For Problem Solving
They are logical AND (&&) logical OR ( || ) and logical NOT (!)
Logical AND ( && )
exp1 exp2 exp1&&exp2
T T T
T F F
F T F
F F F
Logical OR( || )
exp1 exp2 exp1||exp2
T T T
T F T
F T T
F F F
Program:
main ( )
{
int a= 10, b = 20, c= 30;
Output
printf (“ %d”, (a>b) && (a<c)); 0
printf (“ %d”, (a>b) | | (a<c)); 1
1
Programming For Problem Solving
Program:
main ( )
{ int a= 10,; Output
printf (“ %d”, a); 10
}
5. Increment and decrement operator:
a) Increment operator (++):
It is used to increment the value of a variable by 1
2 types : i) pre increment
ii) post increment
increment operator is placed before the operand in preincrement and the value is first
incremented and then operation is performed on it.
eg: z = ++a; a= a+1
z=a
increment operator is placed after the operand in post increment and the value is
incremented after the operation is performed
eg: z = a++; z=a
a= a+1
Program main ( )
{
int a= 10, z;
z= a++;
Output
Output printf (“z= %d”, z); z=10
z=11
Programming For Problem Solving
main ( )
{
int a= 10, z;
z= ++a ;
printf (“z= %d”, z);
printf (“ a=%d”, a);
}
b) Decrement operator : (- -)
It is used to decrement the values of a variable by 1
2 types : i) pre decrement
ii) post decrement
decrement operator is placed before the operand in predecrement and the value is first
decremented and then operation is performed on it.
eg: z = - - a; a= a-1
z=a
decrement operator is placed after the operand in post decrement and the value is
decremented after the operation is performed
eg: z = a--; z=a
a= a-1
Program:
main ( ) main ( )
{ {
z= --a; z= a--;
Output
printf (“z= %d”, z);
Output printf (“z= %d”, z); z=10
z=9
printf (“ a=%d”, a); printf (“a=%d”, a); a=9
a =9
} }
Programming For Problem Solving
6. Bitwise Operator
Unlike other operators, bitwise operators operate on bits (i.e. on binary values of on operand)
Operator Description
8 4 2 1 8 4 2 1
a =12 1 1 0 0 a =12 1 1 0 0
b =10 1 0 1 0 b =10 1 0 1 0
a &b 1 0 0 0 a|b 1 1 1 0
a&b = 8 a | b = 14
8 4 2 1
Programming For Problem Solving
a =12 1 1 0 0 a^b
b =10 1 0 1 0
a ^b 0 1 1 0
a^b=6
Program
main ( )
{
int a= 12, b = 10; Output
printf (“ %d”, a&b); 8
Left Shift
If the value of a variable is left shifted one time, then its value gets doubled
eg: a = 10 then a<<1 = 20
32 16 8 4 2 1
a=10
1 0 1 0
a<<1 = 20
Right shift
If the value of a variable is right shifted one time, then its value becomes half the original value
eg: a = 10 then a>>1 = 5
8 4 2 1
a=10
1 0 1 0
Programming For Problem Solving
a>>1 0 Discard it
1 0 1
a>>1 = 5
Ones complement
It converts all ones to zeros and zeros to ones
Eg: a = 5 then ~a=2 [only if 4 bits are considered]
8 4 2 1
a=5
1 0 1
~a
0 1 0
~a = 2
Program
main ( ) Output
40
{
5
int a= 20, b = 10,c=10;
11
printf (“ %d”, a<<1);
printf (“ %d”, b>>1);
printf (“ %d”, ~c);
}
Signed
1‟s complement = - [ give no +1]
Eg : ~10 = - [10+1] = -11
~-10 = - [-10+1] = 9
unsigned
1‟s complement = [65535 – given no]
7. Conditional operator (? :)
It is also called ternary operator
Syntax:
exp1 ? exp2 : exp3
if exp1 is true exp2 is evaluated, otherwise exp3 is evaluated
Programming For Problem Solving
}
8) Special operations
Some of the special operations are comma, ampersand(&), size of operators.
a) Comma: ( , )
It is used as separator for variables
eg; a=10, b=20
b) Address:(&)
It is used to get the address of a variables.
c) Size of ( ) ;
It is used to get the size of a data type of a variable in bytes.
Program:
main ( )
{
int a=10;
float b=20 ;
printf (“ a= %d b=%f”, a,b );
printf (“ Address of a =%u “ , &a ) ;
printf (“ Address of b =%u” ,&b ) ;
printf (“Size of a = %d ” , sizeof (a) ) ;
printf ( “Size of b = %d ”, sizeof (b) ) ;
} a b
10 20.00
Programming For Problem Solving
Out Put :
a=10 b=20.00 1234 5678
Address of a =1 2 3 4
Address of b = 5 6 7 8 Only for this example
Size of a = 2 bytes
Size of b = 4 bytes
Eg: C = 30 - 10 * 2
20
2
10
3
Here, 10*2 is evaluated first since „*‟ has more priority than „-„ and „=‟
If an expression contains same priority then assoiciativity rules are considered i.e. left
right (or right to left)
eg: z= a*b/c
z = 40 * 20 / 10 Here „*‟ and „/‟ have same priority so, left to
right associativity is
considered
800
2
z
80
3
Programming For Problem Solving
Eg: x =5 *4 + 8/2 x = 5 * 4 + 8 / 2
1 2
x = 24
Parenthesis has highest priority and comma has least priority among operators
Type Conversions
Converting one data type into another is the concept of type conversion
2 types
1. Implicit type conversion
2. Explicit type conversion
Implicit type conversion is automatically done by the compiler by converting smaller data
type into a larger data type.
Eg: int i,x;
float f;
double d;
long int l;
x = l / i + x - f - d
long float
long float
float
`
Float
Double
Programming For Problem Solving
int double
int float
float
int
Here, the resultant of „a+b‟ is converted into „int‟ explicitty and then assigned to „c‟
Program:
main ( )
{
Output
printf (“%d”, 5/2); 2
printf (“%f”, 5.5/2); 2.75
printf (“%f”, (float) 5/2); 2.5
}
STORAGE CLASSES
There are 4 storage classes (or) storage class specifiers supported in „C‟ They are:
1) auto
2) extern
3) static
4) register
1. automatic variables / Local variables.
Keyword : auto
These are also called local variables
Scope
o Scope of a local variable is available within the block in which they are declared.
Programming For Problem Solving
eg:
extern int i =1; /* this „i‟ is available throughout program */
main ( )
{
int i = 3; /* this „i' available only in main */
printf (“%d”, i);
fun ( );
} Output
3
1
Programming For Problem Solving
fun ( )
{
printf (“%d”, i);
}
3) Static variables
Keyword : static
Scope
Scope of a static variable is that it retains its value throughout the program and in
between function calls.
Static variables are initialized only once.
o Default value: zero
eg:
main ( ) main ( )
{ {
inc ( ); inc ( );
inc ( ); inc ( );
inc ( ); inc ( );
} }
inc ( ) inc ( )
{ {
static int i =1; auto int i=1;
printf (“%d”, i); printf (“%d”, i);
i++; i++;
} }
Output Output
1 2 3 1 1 1
4. Register variables
Keyword : register
Register variable values are stored in CPU registers rather than in memory where
normal variables are stored.
Registers are temporary storage units in CPU
They allow faster access time for register variables than normal variables
eg:
Programming For Problem Solving
main ( )
{
register int i;
for (i=1; i< =5; i++)
printf (”%d ”,i);
}
Output
1 2 3 4 5
Scope rules
Scope rules relate to the accessibility, period of existence and boundary of usage of
variables.
1) Scope rules related to statement Blocks :
Block is set of statement enclosed in curly braces
Variables declared in a block are accessible and usable within that block and doesnot
exist outside it
eg: main ( )
{
{
„i' is available within this
int i = 1;
block only
printf (“%d”,i);
}
{
int j=2; „j' is available within this
}
}
output
1 2
Even if the variables are redeclared in their respective blocks and with the same name,
they are considered differently
main ( )
Programming For Problem Solving
{
{
/* Both i‟s are declared in different
int i = 1;
blocks so, they are treated differently
printf (“%d”,i);
even though they have same name */
}
{
int i =2;
printf (“%d”,i);
}
}
Output
1 2
redeclaration of variables within the blocks bearing the same names as those in the outer
block masks the outer block variables while executing the inner blocks.
eg:
main ( )
{
int i = 1;
/* inner block variable dominates
{
outer block variable with same name
int i = 2;
*/
printf (“%d”,i);
}
}
Output : 2
Variables declared outside the inner blocks are accessible to the nested blocks, provided
these variable are not declared within the inner block
main ( )
{
int i = 1;
/* „i‟ is available within the inner
{
block also */
int j = 2;
Programming For Problem Solving
printf (“%d”,j);
printf (“%d”,i);
}
}
Output
2 1
2. Scope rules related to functions
Function is a self contained block that performs a particular task.
Variables declared within the function body are called local variables
These variables only exist inside the specific function that creates them. They are
unknown to other functions and to the main functions also
The existence of local variables ends when the function completes its specific task and
returns to the calling point.
eg:
main ( )
{
int a=10, b = 20;
printf (“before swapping a=%d, b=%d”, a,b);
swap (a,b);
printf (“after swapping a=%d, b=%d”, a,b);
}
swap (int a, int b)
{
int c;
c=a;
a=b;
b=c;
}
Output:
Before swapping a=10, b=20
After swapping a = 10, b=20
Programming For Problem Solving
Variables declared outside the function body are called global variables.
These variables are accessible by any of the functions
eg:
include<stdio.h>
int a=10, b = 20;
main()
{
printf (“before swapping a=%d, b=%d”, a,b);
swap ( );
printf (“after swapping a=%d, b=%d”, a,b);
}
swap ( )
{
int c;
c=a;
a=b;
b=c;
}
Output
Before swapping a = 10, b =20
After swapping a = 20, b = 10
CONTROL STATEMENTS :
Decision statements :
These are used to make a decision among the alternative paths
They are
1. simple – if statement
2. if – else statement
Programming For Problem Solving
1. Simple – if statement
„if‟ keyword is used to execute a set of statements when the logical condition is true
Syntax :
if (condition)
{
Statement (s)
}
Flow chart
True False
Cond
ition?
Statement (s)
Output
1) enter a number 60 2) enter a number 20
60 is greater than 50 no output.
2. if else statement
If –else statement takes care of true as well as false conditions
„true block‟ is executed when the condition is true and „false block‟ (or) „else block‟ is
executed when the condition is false.
Syntax:
if (condition)
{
True block statement(s)
}
else
{
False block statement(s)
}
Flow chart
True False
Cond
ition?
Program
/* checking for even (or) odd number */
main ( )
{
int n;
Programming For Problem Solving
Flow chart
True Cond False
ition1
if (b>c)
printf (“%d is largest”, b);
else
printf (“%d is largest”, c);
}
}
Output
enter 3 numbers = 10 20 30
30 is largest
4. Else – if ladder
This is the most general way of writing a multi-way decision
Syntax
if (condition1)
stmt1;
else if (condition2)
stmt2;
-----
-----
else if (condition n)
stmtn;
else
stmt x;
flow chart
True False
Stmt n Stmt x
Flow chart
Switch
(expressi
on)
| Exp =value2
Stmt2
default Stmt-x
Program
main ( )
{
int n;
printf (“enter a number”);
Programming For Problem Solving
Output
enter a number
1
one
Loop control statements
These are used to repeat set of statements
They are
1) for loop
2) while loop
3) do-while loop
1) for loop
Syntax
for (initialization ; condition ; increment / decrement)
{
body of the loop
}
Flow chart
False
Initialization Increment/
condition decrement
True
{ 3
printf (”%d”,k); 4
} 5
}
2) while loop
Syntax
while (condition)
{
body of the loop
}
Programming For Problem Solving
Flow chart
initialization
Is False
expression?
True
Incr/ dec
Program
main( )
{
int k; Output
k = 1; 1
while (k< = 5) 2
{
printf (”%d”,k); 3
k++; 4
}
} 5
3) do-while loop
Syntax
Initialization
do
{
body of the loop
Programming For Problem Solving
inc/ dec
} while (condition);
Flow chart
initialization
Incr/ dec
True Is
expression?
Program
main( )
{ Output
int k; 1
k = 1; 2
do 3
{ 4
printf (”%d”,k); 5
k++;
} while (k <= 5);
}
Nested for loops
Programming For Problem Solving
In nested for loops one (or) more for statements are included in the body of the loop
The number of iterations in this type of structure will be equal to number of iterations in
the outer loop multiplied by the number of iterations in the inner loop
Program
main( )
{
int i,j; Output
for (i=1; i<=2; i++) 1
{ 2
for (j=1;j<=2; j++)
{ 2
printf (”%d”, i*j); 4
}
} 3
} 6
Execution i*j
i=1 j=1 1
j=2 2
i=2 j=1 2
j=2 4
i=3 j=1 3
j=2 6
Other related statements
1) break
2) continue
3) goto
1) break
It is a keyword used to terminate the loop (or) exit from the block
The control jumps to next statement after the loop (or) block
„break is used with for, while, do-while and switch statement
When break is used in nested loops then only the innermost loop is terminated
Syntax
{ Stmt1;
Stmt2;
Programming For Problem Solving
break;
Stmt3;
Stmt4;
}
Program
main( )
{ int i; Output
for (i=1; i<=5; i++) 1
{ 2
if (i= =3)
break;
}
}
2) continue
It is a keyword used for continuing the next iteration of the loop
It skips the statements after the continue statement
It is used with for, while and do-while
Syntax
{
Stmt1;
Stmt2;
continue;
Stmt3;
Stmt4;
}
Program
main( ) Output
1
{
3
int i;
4
5
Programming For Problem Solving
3) goto
It is used to after the normal sequence of program execution by transferring the control to
some other part of program
Program
main( ) Output
Hello
{
you
printf(‟Hello”);
goto l1;
printf(”How are”);
l1: printf(”you”);
}
Command line arguments :
An executable program that performs a specific task for operating system is called as
command
These commands are issued from the prompt of operating system.
Some arguments are to be associated with the commands and hence these are called “
command” line arguments. They are
Programming For Problem Solving
ARRAYS
Array: An array is a group of related data items that share a common name
(or) Homogenous collection of data items that share a common name.
A particular value in an array is identified using its “index number” or “subscript”
Advantage
The ability to use a single name to represent a collection of items and to refer to an item
by specifying the item number enables the user to develop concise and efficient programs
Declaring for declaring array
Syntax : for declaring array:
Eg:
1. float height [50]
This declares „height‟ to be an array containing 50 float elements
2. int group[10]
This declares the „group‟ as an array to contain a maximum of 10 integer constants
Individual elements are identified using “ array subscripts”
While complete set of values are referred to as an array, individual values are called
“elements”
Eg: To represent a set of 5 numbers by an array, it can be declared as follows
int a[5];
Then computer reserves 5 storage locations each of 2 bytes.
a[0]
a[1]
a[2]
a[3]
a[4]
First element is identified by subscript „zero‟ i.e., a[0] represents first element of the
array.
If there are „n‟ elements in array then subscripts range from 0 to n-1
Programming For Problem Solving
Initialization
To store values into an array it can be done as follows.
a[0] = 10; 10 a[0]
a[1] = 20; 20 a[1]
a[2] = 30; 30 a[2]
a[3] = 40; 40 a[3]
a[4] = 50; 50 a[4]
{ a[4] 50
int a[5] = {10,20,30,40,50};
int i;
clrscr ( );
printf (“elements of the array are”);
for ( i=0; i<5; i++)
printf (“%d, a[i]);
getch ( );
}
accessing
Output: Elements of the array are
{
10 20 30 40 50
Int a=
Program for runtime initialization and sequential access using for loop
10, z;
main ( )
z= a++;
{
printf
int a[5],i;
(“z= %d”, z);
clrscr ( );
printf
printf (“enter 5 elements”);
(“a=%d”, a);
for ( i=0; i<5; i++)
} Storing / assigning values to element of an
scanf(”%d”, &a[i]);
array
printf(“elements of the array are”);
for (i=0; i<5; i++)
Accessing the elements of the aray
printf(”%d ”, a[i]);
getch ( );
}
output
enter 5 elements 10 20 30 40 50
elements of the array are : 10 20 30 40 50
Note :
The output of compile time initialized program will not change during different runs of the
program
Programming For Problem Solving
The output of run time initialized program will change for different runs because user is
given a chance of accepting different values during execution.
2. Two – dimensional arrays
These are used in situations where a table of values have to be stored (or) in matrices
applications
Syntax :
datatype array_ name [rowsize] [column size];
Eg: int a[5] [5];
No of elements in array = rowsize *columnsize = 5*5 = 25
Initialization :
Program for compile time initialization and sequential access using nested for loop
main ( )
{
int a[3][3] = {10,20,30,40,50,60,70,80,90}; a[0] [0] a[0] [1] a[0] [2]
int i,j; 10 20 30
clrscr ( );
a[1] [0] a[1] [1] a[1] [2]
printf (“elements of the array are”);
40 50 60
for ( i=0; i<3; i++)
a[2] [0] a[2] [1] a[2] [2]
{
70 80 90
for (j=0;j<3; j++)
{
printf(“%d \t”, a[i] [j]);
}
printf(“\n”);
}
getch ( );
}
output
elements of the array are:
10 20 30
40 50 60
Programming For Problem Solving
70 80 90
Program for runtime initialization and sequential access using nested for loop
main ( )
{
int a[3][3] ,i,j;
clrscr ( );
printf (“enter elements of array”);
for ( i=0; i<3; i++)
{
for (j=0;j<3; j++)
{
scanf(“%d ”, &a[i] [j]); a[0] [0] a[0] [1] a[0] [2]
} 10 20 30
} a[1] [0] a[1] [1] a[1] [2]
printf(“elements of the array are”); 40 50 60
for ( i=0; i<3; i++) a[2] [0] a[2] [1] a[2] [2]
{ 70 80 90
for (j=0;j<3; j++)
{
printf(“%d\t ”, a[i] [j]);
}
printf(“\n”)
}
getch( );
}
output
Enter elements of array : 1 2 3 4 5 6 7 8 9
Elements of the array are
1 2 3
4 5 6
7 8 9
Programming For Problem Solving
o n e \0 t w o \0 t h r e e \0
a [0] 1234
a [1] 1238
a [2] 1242 Array of pointers
Advantage :
Unlink the two dimensional array of characters. In (array of strings), in array of pointers
to strings there is no fixed memory size for storage.
The strings occupy only as many bytes as required hence, there is no wastage of space.
Program
main ( )
{
char *a[5] = {“one”, “two”, “three”, “four”, “five”};
int i;
clrscr ( );
printf ( “the strings are”)
for (i=0; i<5; i++)
Programming For Problem Solving
STRINGS
Strings basics:
String : array of characters (or) collection of characters is called a string
Declaration :
char stringname [size];
eg: char a[50]; string of length 50 characters
Initialization
a) using single character constant:
char a[10] = { „H‟, „e‟, „l‟, „l‟, „o‟ ,„\0‟}
„H‟ „e‟ „l‟ „l‟ „o‟ „\0‟
b) using string constants :
char a[10] = “Hello”:;
„H‟ „e‟ „l‟ „l‟ „o‟ „\0‟
„\0‟ is called null character.
It marks the end of the string
„\0‟ is automatically placed by the compiler if a string constant is given as input.
User must take care of placing „\0‟ at the end if single character constants are given.
Accessing:
There is a control string “%s” used for accessing the string till it encounters „\0‟
Program
main ( )
{
char a[10] = “Hello”;
clrscr ( );
printf ( “ given string is %s”,a)
Programming For Problem Solving
getch ( );
}
I/o functions
Output : Given string is Hello
Input and output for strings
char a[30];
printf(“enter your name”);
scanf ( “%s”,a);
printf (“your name is %s”,a);
getch ( );
}
Output
1. Enter your name : Ramu 2. Enter your name : Ram kumar
Your name is Ramu Your name is Ram
Note :
1. „&‟ is not used for accepting string because name of the string itself specifies the base
address of the string
2. space is not accepted as a character by scanf( )
3. „\0‟ is automatically placed by the compiler at the end.
Program : Using gets ( ) and puts ( ) for reading and writing strings.
main ( )
{
char a[30];
printf ( “enter your name”);
gets (a);
printf(“Your name is”);
Programming For Problem Solving
puts (a);
}
Out put
1. Enter your Name : Ramu 2) Enter your name : Ram kumar
Your name is Ramu Your name is Ram kumar
Note : Space is also accepted as a character by gets ( )
String Library functions
There are some predefined functions designed for handling strings which are available in
the library “string.h”
They are :
1) strlen ( ) 6. strcmp ( )
2) strcpy ( ) 7. strncmp ( )
3) strncpy ( ) 8. strrev ( )
4) strcat ( ) 9.strstr()
5) strncat ( )
1). strlen ( )
This function gives the length of the string i.e. the number of characters in a
string.
Syntax:
int strlen (string name)
program
#include <string.h>
main ( )
{
char a[30] = “Hello”;
int l;
l = strlen (a);
printf (“length of the string = %d”, l);
getch ( );
}
Output
Programming For Problem Solving
Output
Enter a source string : Hello
Copied string = Hello
3) strncpy ( )
This function is used for copying „n‟ characters of source string into destination string
Programming For Problem Solving
The length of the destination string must be greater than (or) equal to that of the source
string
Syntax:
strncpy (Destination string, Source String, n);
program
#include <string.h>
main ( )
a
{
H E l l o \o
char a[50], b[50];
clrscr ( ) b
H E l \o
printf (“enter a string”);
gets (a);
strncpy (b,a,3);
b[3] = „\0‟;
printf (“copied string = %s”,b);
getch ( );
}
Output
Enter a string : Hello
Copied string = Hel
s1
It is also used for extracting substrings; J a n 1 0 2 0 1 0 \0
Eg: char result[10], s1[15] = “Jan 10 2010”;
strncpy (result, &s1[4], 2);
result[2] = „\0‟ result
1 0 \o
o/p :Result = 10
4) strcat ( ):
Programming For Problem Solving
Syntax:
strncat (Destination String, Source string,n);
program
#include <string.h>
main ( )
{
char a [30] = “Hello”;
clrscr ( );
strncat (a,b,4);
a [9] = „\0‟;
printf(“concatenated string = %s”, a);
getch ( );
}
Output
Concatenated string = Hello Good.
String comparison
6) strcmp
This function compares 2 strings
It returns the ASCII difference of the first two non – matching characters in both the
strings.
Syntax
int strcmp (string1, string2);
If the difference is equal to zero string1 = string2
If the difference is positive string1> string2
If the difference is negative string1 <string2
eg:
1) char a[10]= “there”
char b[10] = “their” t h e r e \0
strcmp (a,b);
t h e i r \0
Output: string1 >string2
„r‟ > „i‟
strcmp (a,b);
t h e r e \0
Programming For Problem Solving
strcmp (a,b);
Output: string1 =string2 t h e r e \0
strcmp (a,b)
t h e \0
Output: string1 >string2
„r‟ > „\0‟
5) char a[10]= “the”
char b[10] = “there” t h e \0
strcmp (a,b);
t h e r e \0
Output: string1 <string2
„\0‟ < „r‟
Program
main ( )
{
char a[50] b [50];
int d;
clrscr( );
printf (“enter 2 strings”);
scanf (“%s %s”, a,b);
d = strcmp (a,b);
if (d==0)
printf(“%s is equal to %s”, a,b);
else if (d>0)
Programming For Problem Solving
7. strncmp ( )
This function is used for comparing first „n‟ characters of 2 strings
Syntax :
strncmp ( string1, string2, n)
Eg: char a[10] = “the”;
char b[10] = “there”
strncmp (a,b,3);
Output : Both strings are equal
8. strrev( )
The function is used for reversing a string
The reversed string will be stored in the same string
Syntax : strrev (string)
Program
main ( )
{
char a[50] ;
clrscr( );
printf (“enter a string”);
gets (a);
strrev (a);
printf(“reversed string = %s”,a)
getch ( );
}
Output : enter a string Hello
Programming For Problem Solving
clrscr();
printf("Enter a string:\t");
gets(a);
found=strstr(a,b);
if(found)
printf("%s is found in %s in %d position",a,b,found-a);
else
printf("-1 since the string is not found");
getch();
}
Output:
Structure variables
There are 3 ways of declaring structure variables
1) struct book
{
int pages;
char author[30];
float price;
}b;
2) struct
Note : Tagname can be ignored if the
{
variable is declared of the time of defining
int pages;
structure
char author[30];
float price;
}b;
3) struct book
{
int pages;
char author[30];
float price;
};
struct book b;
Initialization and accessing of structures
The link between a member and a structure variable is established using member operator
(or) dot operator
Initialization can be done in the following ways
1. struct book
{
int pages;
char author[30];
float price;
Programming For Problem Solving
{
struct book b;
clrscr ( );
printf ( “enter no of pages, author, price of book”);
scanf (“%d%s%f”, &b.pages, b.author, &b.price);
printf(“ Details of book are”);
printf(“pages =%d, author = %s, price = %f”, b.pages, b.author, b.price);
getch();
}
Structure within structure (or) Nested structures
Creating a structure inside another structure is called nested structure
Consider the following example
struct emp
{
int eno;
char ename[30];
float sal;
float da;
float hra;
float ea;
}e;
This is structure defines eno, ename, sal and 3 kinds of allowances. All the items related
to allowances can be grouped together and declared under a sub – structure as shown
below.
stuct emp
{
int eno;
char ename[30];
float sal;
struct allowance
Programming For Problem Solving
{
float da;
float hra;
float ea;
}a;
}e;
The inner most member in a nested structure can be accessed by changing all the
concerned structure variables (from outer most to inner most) with the member using dot
operator
Eg :
e.eno; e.ename e.sal;
e.a.da; e.a.hra; e.a.ea;
Program
struct emp
{
int eno;
char ename[30];
float sal;
struct allowance
{
float da;
float hra;
float ea;
}a;
}e;
main ( )
{
clrscr ( );
printf(“enter eno, ename, salary”);
scanf (“%d%s%f”, &e.eno, e.ename, &e.sal);
Programming For Problem Solving
struct student
{
int sno;
char sname[30];
float marks;
};
main ( )
{
struct student s[10];
int i;
clrscr ( );
for (i=0; i<10; i++)
{
Programming For Problem Solving
{
struct student s;
struct student *st;
clrscr ( );
printf(“enter sno, sname, marks”);
scanf (“%d%s%f”, & s.sno, s.sname, &s. marks);
st = &s;
printf (“details of the student are”);
printf (“Number = %d”, st sno);
printf (“name = %s”, stsname);
printf (“marks =%f”, st marks);
getch ( );
}
Union
Def : A union is a memory location that is shared by several variables of different data types.
Syntax:
union uniontag
{
datatype member 1;
datatype member 2;
----
----
datatype member n;
};
Eg:
union sample
{
int a;
float b;
Programming For Problem Solving
char c;
};
Declaration of union variable
1) union sample
{
int a;
float b; 4bytes
char c; s
}s;
a
2) union b
{ c
int a;
float b;
char c;
}s;
3) union sample
{
int a;
float b;
char c;
};
union sample s;
when a union is declared, the compiler automatically creates a variable large enough to
hold the largest variable type in the union.
At any time only one variable can be referred.
The arrow operator ( ) is used for accessing the members using pointer
program
union sample
{
int a;
float b;
char c;
}
main ( )
{
union sample s = {10, 20.5, „A‟};
clrscr( );
printf(“a=%d”,s.a);
printf(“b=%f”,s.b);
printf(“c=%c”,s.c);
getch ( );
}
Output
a = garbage value Only the variable that is stored at last will
b = garbage value retain its value
c=A
2. syntax; 2. syntax;
struct tagname union tagname
{ {
Programming For Problem Solving
Union of structures
A structure can be nested inside a union and it is called union of structures
It is also possible to create a union inside a structure
Program
struct x
{
int a;
float b;
};
union z
{
struct x s;
};
main ( )
{
union z u;
clrscr ( );
u.s.a = 10;
u.s.b = 30.5;
printf(“a=%d”, u.s.a);
printf(“b=%f”, u.s.b);
getch ( );
}
Output
a= 10
b = 30.5
Typedef ;
„C‟ allows to define new datatype names using the „typedef‟ keyword
Using „typedef‟, user will not actually create a new datatype but define a new name for
an existing type.
Syntax :
Programming For Problem Solving
unsigned a : 2;
unsigned b : 3;
};
Here, count will be in 2 bytes. „a‟ and „b‟ will be packed into next 1 byte
2) struct pack
{
unsigned a : 2;
int count;
unsigned b : 3;
};
Here, „a‟ will be in 1 byte, „count‟ in 2 bytes and „b‟ in 1 bytes.
Note ;
1. Bit Fields are packed into words as they appear in the definition
2. All unsigned bit fields must be placed in order for effectively using the memory
Program
struct vehicle
{
unsigned type : 3; Note: Instead of 6 bytes only 1 byte of
memory
unsigned fuel : 2; will be allocated
unsigned model : 3;
};
main ( )
{
struct vehicle v;
v.type = 4;
v. fuel = 2;
v. model = 5;
printf (“type of vehicle =%d”, v.type);
printf (“fuel =%d”, v.fuel);
Programming For Problem Solving
Program :
main ( )
{
enum week {mon, tue, wed, thu, fri, sat, sun};
clrscr ( );
printf (“Monday = %d”, mon);
printf (“Thursday = %d”, thu);
printf (“Sunday = %d”, sun);
}
Output : Monday = 0
Thursday =3
Sunday =6
Programming For Problem Solving
qty Variable
179 value
5000 Address
Programming For Problem Solving
Declaring a pointer
int *p;
It means „p‟ is a pointer variable that holds the address of another integer variable.
Initialization of a pointer
Address operator (&) is used to initialize a pointer variable.
Eg: int qty = 175;
int *p; Variable value Address
qty 175 5000
p= &qty;
p 5000 5048
p = &qty;
n = *p;
{
int x,y;
int *p; x y
10 25 10
clrscr ( );
x= 10; p 5000
p = &x;
y= *p;
printf (“Value of x = %d”, x);
printf (“x is stored at address %u”, &x);
printf (“Value of x using pointer = %d”, *p);
printf (“address of x using pointer = %u”, p);
printf (“value of x in y = %d”, y);
*p = 25;
printf (“now x = %d”, x)
getch ( );
}
Output
Value of x = 10
x is stored at address = 5000
Address of x using pointer = 10
Address of x using pointer = 5000
Value of x in y = 10
Now x = 25
Pointers and arrays
Continuous memory locations are allocated for all the elements of the array by the
compiler
The base address is the location of the first element (index 0) of the array.
Eg : int a [5] = {10, 20,30,40,50};
The five elements are stored as follows
Elements a[0] a[1] a[2] a[3] a[4]
Value 10 20 30 40 50
Programming For Problem Solving
base address
a= &a[0]=1000
if „p‟ is declared as integer pointer, then the array „a‟ can be pointed by the following assignment
p = a;
(or) p = &a[0];
Every value of „a‟ can be accessed by using p++ to move from one element to another.
When a pointer is incremented, its value is increased by the size of the datatype that it
points to. This length is called the “scale factor”
The relationship between „p‟ and „a‟ is shown below
P = &a[0] = 1000
P+1 = &a[1] = 1002
P+2 = &a[2] = 1004
P+3 = &a[3] = 1006
instead of using array indexing, pointers can be used to access array elements.
*(p+3) gives the value of a[3]
a[i] = *(p+i)
Programming For Problem Solving
Program
main ( )
{
int a[5];
int *p,i;
clrscr ( );
printf (”Enter 5 lements”);
for (i=0; i<5; i++)
scanf (“%d”, &a[i]);
p = &a[0];
printf (“Elements of the array are”);
for (i=0; i<5; i++)
printf(“%d”, *(p+i));
getch( );
}
Output
Enter 5 elements : 10 20 30 40 50
Elements of the array are : 10 20 30 40 50
Array of pointers
It is collection of addresses (or) collection of pointers
Declaration
datatype *pointername [size];
eg: int *p[5]; It represents an array of pointers that can hold 5 integer element addresses
p[0] p[1] p[2] p[3] p[4]
Initialization
„&‟ is used for initialization
Eg : int a[3] = {10,20,30};
int *p[3], i;
for (i=0; i<3; i++) (or) for (i=0; i<3,i++)
p[i] = &a[i];
Programming For Problem Solving
p[i] = a+i;
Accessing
Indirection operator (*) is used for accessing
Eg: for (i=0, i<3; i++)
printf (”%d”, *p[i]);
Program
main ( )
{
int a[3] = {10,20,30};
int *p[3],i;
for (i=0; i<3; i++)
p[i] = &a[i];
printf (elements of the array are”)
for (i=0; i<3; i++)
printf (”%d \t”, *p[i]);
getch();
}
Output elements at the array are : 10 20 30
Programming For Problem Solving
Preprocessor commands
„preprocessor‟ is a program that processes the source code before it passes through the
compiler
It operates under the control of preprocessor directives which begin with the symbol #
3 types
1) Macro substitution directives
2) File inclusion directives
3) compiler control directives
1) Macro substitution directives
It replaces every occurence of the identifier by a predefined string.
Syntax for defining a macro
# define identifier string
Eg: #define PI 3.1415
#define f(x) x *x
#undef PI
Program Program
#define wait getch( ) #define wait getch( )
main ( ) main ( )
{ {
clrscr ( ); #undef wait;
printf (“Hello”); clrscr ( );
wait ; printf (“Hello”);
} wait ;
Output: }
Hello Output
Error since wait is undefined before using it
2. File inclusion directives:
An external file containing functions (or) macro definitions can be included using
#include directive
Programming For Problem Solving
Syntax
# include <filename> (or) #include “filename”
Eg:
#include <stdio.h>
Output
main ( )
Hello
{
printf (“hello”);
}
The definition of the function printf ( ) is present in <stdio.h>header file.
3. Compiler control directives
C pre processor offers a feature known as conditional compilation, which can be used to
switch ON (or) OFF a particular line (or) group of lines in a program.
Eg: #if, #else, #endif etc.
#define LINE 1
main ( )
{ Output
#ifdef LINE This is line number one
printf (”this is line number one”);
#else
printf(„This is line number two”);
#endif
}
FILE :
Definition :It is collection of records (or) It is a place on hard disk where data is stored
permanently.
Types of Files: (1)Text file
(2)Binary File
1. Text File : It contains alphabets and numbers which are easily understood by human beings.
2. Binary file : It contains 1‟s and 0‟s which are easily understood by computers.
Based on the data that is accessed, files are classified in to
Programming For Problem Solving
FILE *fp;
fp = fopen (“sample.txt”, “w”);
I/O STREAMS:
Stream : flow of data
scanf( )
Keyboard Input stream „C‟
Program
printf()
Monitor Output stream
I/0 functions:
2) fscanf ( )
Syntax : fscanf(file pointer, “control string”, & variable list);
Eg: FILE *fp;
fscanf (fp, “%d%c”, &a,&b);
Program for storing the details of an employee in a file and print the same
main ( )
{
FILE *fp;
int eno;
char ename [30];
float sal;
clrscr ( );
fp =fopen (“emp.txt”, “w”);
printf (“enter the details of eno, ename, sal”);
scanf (“%d%s%f”, &eno, ename, &sal);
fprintf (fp, “%d%s%f”, eno, ename, sal);
fclose (fp);
fp = fopen (“emp.txt”, “r”);
fscanf (fp, “%d%s%f”, &eno, ename, &sal);
Programming For Problem Solving
Program :
main ( )
{
FILE *fp;
char ch;
clrscr ( );
fp = fopen (“characters.txt”, “w”);
Programming For Problem Solving
num = getw(fp);
putw ( )
Keyboard scanf (“%d”)
File
char ch;
clrscr ( );
fp1 = fopen (“file1.txt”, “w”);
printf (“enter text press ctrl+z at the end”);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp1);
}
fclose (fp1);
fp1 =fopen (“file1. txt”, “r”);
fp2 =fopen (“file2. txt”, “w”);
while ((ch = getc (fp1))! = EOF)
{
putc(ch,fp2);
}
fclose (fp1);
fclose (fp2);
fp2 = fopen (“file2.txt”, “r”);
printf (“File2 contents are”);
while ((ch = getc(fp2))! = EOF)
putchar (ch);
fclose (fp2);
getch ();
}
Program for displaying the contents of a file
main ( )
{
FILE *fp;
char ch ;
clrscr ( );
fp = fopen (“file1.txt”,”r”);
Programming For Problem Solving
if (fp = = NULL)
{
printf (“File does not exist”);
}
else
{
printf (“file content is”)
while ((ch = getc(fp))! = EOF)
putchar (ch);
}
fclose (fp);
getch ( );
}
Program to merge two files into a third file. (the contents of file1, file2 are placed in file3)
main ( )
{
FILE *fp1, *fp2, *fp3;
char ch;
clrscr ( );
fp1 = fopen (“file1.txt”, “w”);
printf (“enter text into file1”);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp1);
}
fclose (fp1);
fp2 = fopen (“file2.txt”, “r”);
printf (“enter text into file2”);
while ((ch = getchar ( ))! = EOF)
putc(ch, fp2);
fclose (fp2);
Programming For Problem Solving
ch = fgetc(fp);
puts ( )
Monitor fgets ( )
Program :
main ( )
{
FILE *fp;
char str [30];
int i,n;
clrscr ( );
printf (“enter no of strings”);
scanf (“%d”, & n);
fp = fopen („strings.txt”, “w”);
for (i=1; i<=n; i++)
{
Programming For Problem Solving
Eg : FILE *fp;
char str[30] = ”Error is”;
perror (str);
O/P : Error is : error 0
Program :
main ( )
{
FILE *fp;
char str[30] = “error is”;
int i = 20;
clrscr ( );
fp = fopen (“sample. txt”, “r”);
if (fp = = NULL)
{
printf (“file doesnot exist”);
}
else
{
fprintf (fp, “%d”, i);
if (ferror (fp))
{
perror (str);
printf (“error since file is opened for reading only”);
}
fclose (fp);
getch ( );
}
O/P: Error is : Error1 compiler generated.
Error since file is opened for reading by us.
3. feof ( )
Programming For Problem Solving
It is used for checking whether end of the file has been reached (or) not.
Syntax :
int feof ( file pointer);
Eg : FILE *fp;
if (feof (fp))
printf (“reached end of the file”);
If returns a non zero if success and zero otherwise.
Program:
main ( )
{
FILE *fp;
int i,n;
clrscr ( );
fp = fopen (“number. txt”, “w”);
for (i=0; i<=100;i= i+10)
{
putw (i, fp);
}
fclose (fp);
fp = fopen (“number. txt”, “r”);
printf (“file content is”);
for (i=0; i<=100; i++)
{
n = getw (fp);
if (feof (fp))
{
printf (“reached end of file”);
break;
}
else
{
Programming For Problem Solving
2. rewind ( )
It makes the file pointer move to the beginning of the file.
Syntax: rewind (file pointer);
Eg : FILE *fp;
-----
Programming For Problem Solving
-----
rewind (fp);
n = ftell (fp);
printf (“%d”, n);
o/p: 0 (always).
3. fseek ( )
It is used to make the file pointer point to a particular location in a file.
Syntax: fseek(file pointer,offset,position);
offset :
The no of positions to be moved while reading or writing.
If can be either negative (or) positive.
Positive - forward direction.
Negative – backward direction .
position :
it can have 3 values.
0 – Beginning of the file
1 – Current position
2 – End of the file
Eg :
1. fseek (fp,0,2) - fp is moved 0 bytes forward from the end of the file.
2. fseek (fp, 0, 0) – fp is moved 0 bytes forward from beginning of the file
3. fseek (fp, m, 0) – fp is moved m bytes forward from the beginning of the file.
4. fseek (fp, -m, 2) – fp is moved m bytes backward from the end of the file.
Errors :
1. fseek (fp, -m, 0);
2. fseek(fp, +m, 2);
Write a program for printing some content in to the file and print the following ?
1. Number of characters entered into the file.
2. Reverse the characters entered into the file.
Programming For Problem Solving
main ( )
{
FILE *fp;
char ch;
int n;
clrscr ( );
fp = fopen (“reverse. txt”, “w”);
printf (“enter text press ctrl+z of the end”);
while ((ch = getchar( ) ) ! EOF)
{
putc (ch, fp);
}
n = ftell (fp)
printf ( “No. of characters entered = %d”, n);
rewind (fp);
n = ftell (fp);
printf (“fp value after rewind = %d”,n);
fclose (fp);
fp = fopen (“reverse.txt”, “r”);
fseek (fp, -1, 2);
printf (“reversed content is”);
do
{
ch = getc (fp);
printf (“%c”, ch);
} while (!fseek (fp, -2, 1);
fclose (fp);
getch ( );
}
Output : Enter text press ctrl z at the end.
How are you ^z
Programming For Problem Solving
UNIT-IV
Page 123
Programming For Problem Solving
FUNCTIONS
Def : A function is a self contained block that carries out a specific well defined task.
Advantages
1. Reusability i.e. a function may be used by many other programs.
2. The length of the source program can be reduced.
3. It is easy to locate and isolate a faulty function.
4. It facilitates top-down modular programming.
The splitting of a problem into its related sub problems is analogous to the process of
refining an algorithm.
e.g. Performing arithmetic operations on 2 numbers
1. find sum
2. find difference
3. find product
4. find quotient
Page 124
Programming For Problem Solving
Structure chart
Types of functions
Functions are broadly classified into 2 types
They are
1) predefined functions
2) user defined functions
1) predefined (or) library functions
These functions are already defined in the system libraries
Programmer can reuse the existing code in the system libraries to write error free code.
But to use the library functions, user must be aware of syntax of the function.
Page 125
Programming For Problem Solving
Page 126
Programming For Problem Solving
clrscr ( );
printf (“enter 2 numbers”);
scanf (“ %d %d”, &a ,&b)
c = sum (a,b);
printf(“sum = %d”, c);
getch();
}
int sum (int a, int b)
{
int c;
c=a+b;
return c;
}
Output
Enter 2 numbers 10 20
Sum = 30
Communications Among functions
Functions communicate among themselves using arguments and return value.
Farm of „C‟ function
return-datatype function name (argument list)
{
local variable declarations;
executable statements(s);
return (expression);
}
eg: void mul (int x, int y)
{
int p;
p=x*y;
printf(“product = %d”,p);
Page 127
Programming For Problem Solving
}
Return values and their types
A function may (or) may not send back any value to the calling function
If it does, it is done through the return statement
A called function can only return one value per call
The return types are void, int, float, char and double.
If a function is not returning any value then its return type is „void‟
Function name
A function must follow the same rules of formation as other variables name in „C‟
A function name must not duplicate library routine names (or) predefined function
names.
Argument list
The argument list contains valid variable names separated by commas
The argument variables receive values from the calling function, thus providing a means
for data communication from the calling function to the called function.
Calling a function
A function can be called by simply using the function name in a statement
Function definition
When the compiler encounters a function call, the control is transferred to the function
definition.
All the statements ,in the called function, are together called as function definition
Function header
The first line in the function definition is called function header.
Actual parameter
All the variables inside the function call are called actual parameters.
Formal parameters
All the variables inside the function header are called formal parameters
Program
#include<stdio.h>
#include<conio.h>
Page 128
Programming For Problem Solving
main ( )
{
int mul (int, int); function prototype
int a,b,c;
clrscr( );
printf (“enter 2 numbers”);
scanf(“%d %d”, &a, &b);
c = mul (a,b); function call
printf(“product =%d”,c); Actual parameters
getch ( );
}
int mul (int a, int b) Formal parameters
{ function header
int c;
c = a *b; Function definition
return c;
}
Output
Enter 2 numbers: 10 20
Product = 200
Categories of functions:
Depending on whether arguments are present (or) not and whether a value is returned
(or) not, functions are categorized into:
1) functions without arguments and without return values
2) functions without arguments and with return values
3) Functions with arguments and without return values
4) Functions with arguments and with return values.
Page 129
Programming For Problem Solving
eg:
main ( )
{
void sum ( );
clrscr ( );
sum ( );
getch ( );
}
void sum ( )
{
int a,b,c;
printf(“enter 2 numbers”); Output
Enter 2 numbers
scanf (“%d%d”, &a, &b);
10 20
c = a+b;
Sum=30
printf(“sum = %d”,c);
}
Page 130
Programming For Problem Solving
eg:
main ( )
{
int sum ( );
int c;
clrscr ( );
c= sum ( );
printf(“sum = %d”,c);
getch ( );
}
int sum ( )
{
int a,b,c;
printf(“enter 2 numbers”); Output
enter 2 numbers
scanf (“%d%d”, &a, &b);
10 20
c = a+b;
Sum = 30
return c;
}
3) Functions with arguments and without return values
eg:
main ( )
{
void sum (int, int );
int a,b;
Page 131
Programming For Problem Solving
clrscr ( );
printf(“enter 2 numbers”);
scanf(“%d%d”, &a,&b);
sum (a,b);
getch ( );
}
void sum ( int a, int b) Output
{ enter 2 numbers
int c; 10 20
c= a+b; sum = 30
Page 132
Programming For Problem Solving
}
int sum ( int a, int b )
Output
{ enter 2 numbers
int c; 10 20
c= a+b; Sum = 30
return c;
}
Scope
“scope” of a variable determines the part of the program where it is visible
2 types
1. local scope 2. global scope
1. local scope
Local scope specifies that variables defined within the block are visible only in that block
and invisible outside the block.
2. global scope
Global scope specifies that variables defined outside the block are visible upto end of the
program.
eg:
int c= 30; /* global area */
main ( )
{
int a = 10;
printf (“a=%d, c=%d” a,c);
fun ( );
} Local function area
fun ( )
{
printf (“c=%d”,c);
}
output
a =10, c = 30
c = 30
Page 133
Programming For Problem Solving
Recursive Functions
“recursion” is the process of defining something in terms of it self.
“recursive function” is a function that calls itself again in the body of the function
Eg:
A function fact ( ), which computes the factorial of an integer „N‟ ,which is the product of
all whole numbers from 1 to N
When fact ( ) is called with an argument of 1 (or) 0, the function returns 1. otherwise, it
returns the product of n*fact (n-1), this happens until „n‟ equals 1.
Fact (5) =5* fact (4)
=5*4*3* fact (3)
=5*4*3*2* fact (2)
=5*4*3*2*1 fact (1)
=5*4*3*2*1
= 120.
main ( )
{
int n,f;
int fact (int);
clrscr ( );
printf (“enter a number”);
scanf (“%d”, &n);
f= fact (n);
printf (factorial value = %d”,f);
}
int fact (int n)
{
int f;
if ( ( n==1) || (n==0))
return 1;
else
Page 134
Programming For Problem Solving
f= n*fact (n-1);
return f;
}
Output
Enter a number 5
Factorial value = 120
Preprocessor commands
„preprocessor‟ is a program that processes the source code before it passes through the
compiler
It operates under the control of preprocessor directives which begin with the symbol #
3 types
1) Macro substitution directives
2) File inclusion directives
3) compiler control directives
1) Macro substitution directives
It replaces every occurence of the identifier by a predefined string.
Syntax for defining a macro
# define identifier string
Eg: #define PI 3.1415
#define f(x) x *x
#undef PI
Program Program
#define wait getch( ) #define wait getch( )
main ( ) main ( )
{ {
clrscr ( ); #undef wait;
printf (“Hello”); clrscr ( );
wait ; printf (“Hello”);
} wait ;
Output: }
Hello Output
Page 135
Programming For Problem Solving
Page 136
Programming For Problem Solving
Page 137
Programming For Problem Solving
int yr;
};
main ( )
{
struct date d= {02,01,2010};
display (d);
getch ( );
}
Page 138
Programming For Problem Solving
Page 139
Programming For Problem Solving
} b = a – b;
a = a – b;
o/p:
enter 2 numbers 10 20
Before swapping a=10 b=20
After swapping a=10 b=20
Page 140
Programming For Problem Solving
Pointer to functions:
It holds the base address of function definition in memory
Declaration
datatype (*pointername) ( );
The name of the function itself specifies the base address of the function. So,
initialization is done using function name.
Eg: int (*p) ( );
p = display; if display ( ) is a function that is defined.
Program for calling a function using pointer to function
Program main ( )
main ( ) {
{ clrscr ( );
int (*p) ( ); display ( );
clrscr ( ); getch( );
p = display; }
*(p) ( ); display ( )
getch ( ); {
} printf (“Hello”);
display ( ) }
{
printf(“Hello”);
}
Output
Hello
Page 141
Programming For Problem Solving
ALGORITHM
ALGORITHM:
It is a step – by – step procedure for solving a problem
If algorithm is written in English like sentences then it is called as „PSEUDO CODE‟
Properties of an Algorithm
An algorithm must posses the following 5 properties. They are
6. Input
7. Output
8. Finiteness
9. Definiteness
10. Effectiveness
6. Input : An algorithm must have zero (or) more number of inputs
7. Output: Algorithm must produce one (or) more number of outputs
8. Finiteness : An algorithm must terminate in countable number of steps
9. Definiteness: Each step of the algorithm must be stated clearly
10. Effectiveness: Each step of the algorithm must be easily convertible into program 1.
statements
1. Example
Algorithm for finding the average of 3 numbers
7. start
8. Read 3 numbers a,b,c
9. Compute sum = a+b+c
10. compute avg = sum/3
11. Print avg value
12. Stop
2. EXAMPLE: Finding the roots of a quadratic equation, ax2+bx+c
There will be 2 roots for such quadratic equation
Input : a,b,c values
Output: r1, r2 values
Page 142
Programming For Problem Solving
b b 2 4ac
Procedure : r1
2a
b b 2 4ac
r2
2a
Algorithm:
1. start
2. Read a,b,c values
3. Compute d = b2 4ac
4. if d > 0 then
a) r1 = b+ sqrt (d)/(2*a)
b) r2 = b sqrt(d)/ (2*a)
5. otherwise if d = 0 then
a) compute r1 = -b/2a
r2=-b/2a
b) print r1,r2 values
6. otherwise if d < 0 then print roots are imaginary
7. Stop
ALGORITHM:
Step 1: start
Step 2: initialize the a=0, b=1
Step 3: read n
Step 4: if n== 1 print a go to step 7. else goto step 5
Step 5: if n== 2 print a, b go to step 7 else print a,b
Step 6: initialize i=3
Step 7: if i<= n do as follows. If not goto step 7
c=a+b
print c
a=b
b=c
increment i value
goto step 7
Step 8: stop
Page 143
Programming For Problem Solving
ALGORITHM:
Step 1: start
Step 2: read n
Step 3: initialize i=1,c=0
Step 4:if i<=n goto step 5
If not goto step
10 Step 5: initialize j=1
Step 6: if j<=1 do as the follow. If no goto step 7
i)if i%j==0 increment c
ii) increment j
iii) goto Step 6
Step 7: if c== 2 print i
Step 8: increment i
Step 9: goto step 4
Step 10: stop
5.EXAMPLE : The total distance travelled by vehicle in 't' seconds is given by distance =
ut+1/2at2 where 'u' and 'a' are the initial velocity (m/sec.) and acceleration (m/sec2).
ALGORITHM:
Step 1:Start
Step2 : Read t ,dt
Step 3: Set i to 1
Step 4:Set k to dt
Step 5: Read u,a
Step 6: set s to u*k+0.5*d*k*k
Step 7: Write s
Step 8: If(k<=t) and i=1 then
Begin
go to step 6
Else
Begin
read j
if(j=0)
then Begin
Set I to 0
End
Else
Begin
Set I to 1
go to step 4
End
End
Step 9: Stop
Page 144
Programming For Problem Solving
ALGORITHM:
Main Program:
Step 1: Start
Step 2:Read the value of n
Step 3:for i=1 to n increment in steps of 1
STEP 4 :Read the value of ith element into array
STEP5 : Read the element(x) to be search<--binary(a,n,x)
Step 6: if search equal to 0 goto step 7 otherwise goto step 8
Step 7: print unsuccessful search
Step 8: print successful search
Step 9: stop
Step 1: start
Step 2: initialise low to 1 ,high to n, test to 0
Step 3: if low<= high repeat through steps 4 to 9 otherwise goto step 10
Step 4: assign (low+high)/2 to mid
Step 5: if m<k[mid] goto step 6 otherwise goto step 7
Step 6: assign mid-1 to high goto step 3
Step 7: if m>k[mid] goto step 8 otherwise goto step 9
Step 8: assign mid+1 to low
Step 9: return mid
Step 10: return 0
Step 11:stop
ALGORITHM:
Step 1:Start
Step 2:Initiliaze the variables I,j,temp and arr[]
Step 4:Read the loop and check the condition. If the condition is true print the
array elements and increment the I value. Else goto step 4
Step 4:Read the loop and check the condition. If the condition true then
goto next loop.
Step 5:Read the loop and check the condition. If the condition true then
goto if condition
Page 145
Programming For Problem Solving
ALGORITHM:
Main Program:
1. start
2. read the value of n
3. for i= 1 to n increment in steps of 1
Read the value of ith element into array
4. call function to sort (bubble_sort(a,n))
5. for i= 1 to n increment in steps of 1
print the value of ith element in the array
5. stop
Page 146