C Programming Notes
C Programming Notes
Especially
For
B.E. First semester
Students
Notes on
Programming in C
Based on syllabus of Pokhara University
Prepared By:
Er.Pradip Paudel
Lecturer, Everest Engineering college, sanepa-2 Lalitpur
Email: pradippaudel89@gmail.com
CMP 103.3 Programming in C (3-0-3)
Evaluation:
Theory Practical Total
Sessional 30 20 50
Final 50 - 50
Total 80 20 100
Course Objectives:
The object of this course is to acquaint the students with the basic principles of programming and development of
software systems. It encompasses the use of programming systems to achieve specified goals, identification of
useful programming abstractions or paradigms, the development of formal models of programs, the formalization of
programming language semantics, the specification of program, the verification of programs, etc. the thrust is to
identify and clarify concepts that apply in many programming contexts:
1 Introduction 3
History of computing and computers, programming, block diagram of computer, generation
of computer, types of computer, software, Programming Languages, Traditional and
structured programming concept
2 Programming logic 5
Problems solving(understanding of problems, feasibility and requirement analysis) Design
(flow Chart & Algorithm), program coding (execution, translator), testing and debugging,
Implementation, evaluation and Maintenance of programs, documentation
4 Control Structures 6
Introduction, types of control statements- sequential, branching- if, else, else-if and switch
statements, case, break and continue statements; looping- for loop, while loop, do—while
loop, nested loop, goto statement
6 Functions 6
Introduction, returning a value from a function, sending a value to a function, Arguments,
parsing arrays and structure, External variables, storage classes, pre-processor directives,
C libraries, macros, header files and prototyping
Textbooks:
1. Programming with C, Byran Gottfried
2. C Programming, Balagurusami
References
1. A book on C by A L Kely and Ira Pohl
2. The C Programming Language by Kerighan, Brain and Dennis Ritchie
3. Depth in C, Shreevastav
Characteristics Effects
Size Decrease
Speed Increase
Power consumption Decrease
Processing capability Increase
Storage capacity Increase
Reliability and accuracy Increase
Based on the period of development and the features incorporated, the computers are
classified into different generations- First generation to Fifth generation. This is called the
computer generation.
1) First Generation (1940-1956)
Aims to solve highly complex problems, which require reasoning, intelligence and expert
knowledge.
Based on Parallel processing architecture.
Will use natural language rather than high level language. Processing with quantum
computation and molecular technology will radically change the computing in future.
Computer Software
What is a software? Differentiate tailored and packaged software.
What is computer software? Explain the different type of software used in today’s
life.[PU:2018 fall]
What do you mean by Instructions and software? Explain various types of
software.[PU:2019 spring]
Tailored software: These kind of software are developed for solving particular problem.
eg. A software for payroll of an organization, attendance system for student, software for
ticket reservation etc.
Packaged software: These software that is often used together, performs similar
functions, or includes similar features, and is bundled together as a set of software
programs. For example, Microsoft Office is packaged software, including multiple
software programs used in a home or office, such as Microsoft Excel, Microsoft Word, and
Microsoft PowerPoint. Video and audio editing software may be available as packaged
software as well, as they may be used together for editing music and video files used in a
movie.
Utility software: These are special types of application software which help us to fine
tune the performance of a computer, prevent unwanted actions or perform system
related tasks such as checking for virus and removing virus, system utilities which provide
information about current state of the use of files, memory, users and peripherals eg disk
info, check disk, debuggers for removing “bugs” from program.
Types of computers
How does digital computer differ from analog computer? Define Hybrid computer.
i) Analog computer
Analog computer is one which operates on continuous data, usually of a physical nature such as
length, voltage or current, etc. An analog machine is usually a special purpose device dedicated
to a single task. Analog computers are based on analog signals that are continuous signals. These
types of computers were widely used in scientific and industrial applications.
Presley, thermometer, speedometer, barometer, lactometer, etc are the example of an analog
computer. An example of analog devices is a thermometer, barometer, speedometer and
ammeter.
ii) Digital computer
The computer which works on discrete data or discontinuous data is known as a digital computer.
It works on a binary system where 0 represent off and 1 represents on. It is based on digital
signals i.e discrete signals.
A computer, which has a combination best feature of both analog and digital computers is called
a hybrid computer. It helps the user to process discrete and continuous data. The hybrid
computer can convert the analog signal into digital signals and digital signal into analog signal.
Hybrid computers are used mainly in specialized applications where both kinds of data need to
be processed. Therefore, they help the user to process both continuous and discrete data.
They have usually the speed of digital computers and the accuracy of analog computers. They
can perform the task of both analog and digital computer. They are usually used for special
problems, as it is a special purpose computer in which input data are derived and measurement
are converted into digits and processed by a computer.
It is mostly used in radar communication, rocket launching, weather forecasting and in other
fields.
i) Super computers: Supercomputers are very expensive, very fast, and the most
powerful computers we have in the world. It has multiuser, multi -processing, very
high efficiency and large amount of capacity. They are used in scientific research
centers like NASA. These computer types are also very large in size due to the
numerous parts and components involved in their design.
A good example of a Supercomputer is Tianhe-2.
ii) Mainframe computers: These are large and expensive computer types capable of
supporting hundreds, or even thousands, of users simultaneously. Thus, they are
mostly used by governments and large organizations for bulk data processing, critical
applications, transaction processing, census, industry and consumer statistics among
others. They are ranked below supercomputers
Examples. IBM 4300 series, ICL 39 series,IBM-1401.
iii) Mini Computer
Minicomputers are used by small businesses & firms. Minicomputers are also called
as “Midrange Computers”. These are small machines and can be accommodated on
a disk with not as processing and data storage capabilities as super-computers &
Mainframes. These computers are not designed for a single user. Individual
departments of a large company or organizations use Mini-computers for specific
purposes. For example, a production department can use Mini-computers for
monitoring certain production process.
Popular Minicomputers
K-202
Texas Instrument TI-990
SDS-92
Desktop computers, laptops, personal digital assistant (PDA), tablets & smartphones
are all types of microcomputers. The micro-computers are widely used & the fastest
growing computers. These computers are the cheapest among the other three types
of computers. The Micro-computers are specially designed for general usage like
entertainment, education and work purposes. Well known manufacturers of Micro-
computer are Dell, Apple, Samsung, Sony & Toshiba.
Primary storage: They stores data and programs while the program is being executed.
They are temporary in nature. The data is lost when computer is switched off. They are
faster, expensive and occupy less space as compared to secondary storage unit. eg RAM
Secondary storage: They stores the data and program permanently. The program that
run on a computer are first transferred to primary memory before it actually run.
Control Unit: The control coordinates or controls all the activities performed in a
computer system. It transfers data and instructions to the ALU for arithmetic
operations. It tells the computer's memory, arithmetic and logic unit and input
and output devices how to respond to the instructions that have been sent to
the processor. As well, It directs the operation of the other units by providing
timing and control signals.
Arithmetic and Logic unit: They performs Arithmetic and logical operations on
data. Arithmetic operations performed by them are Addition, Subtraction,
Multiplication, Division etc. Similarly logical operations perform by them are
AND, OR, NOT etc.
Whenever calculations are required, the control unit transfers the data from
memory unit to ALU, once computations are done, the results are transferred to
the Memory unit by the control unit and then it is send to the output unit for
displaying data.
Output Unit
They are set of output devices used for providing the output of a program that is obtained after
performing the operations specified in a program. Commonly used output devices are monitor,
printer etc.
Language Translator
What do you mean by language translation? Differentiate compiler and interpreter.
Explain the significance of compiler and interpreter.
A programmer write a program in high level language that is to be translated into machine
language equivalent code. This task is achieved by using language translator.
The common language translator are:
Compiler
Interpreter
Assembler
Compiler Interpreter
1. A compiler translates the entire 1. An interpreter translates one
source code to object code and then statement at a time, executes it and
only object code is executed. continues for another statement.
2. Compiler is faster than interpreter. 2. Interpreter is slower than compiler.
3. It generates the error message only 3. It continuously translates the program
after scanning the whole program. until the first error is met, in which
Hence debugging is comparatively case it stops. Hence debugging is
hard. easy.
4. A compiler is a complex program. 4. Interpreter is less complex program
than compiler.
5. As compared to an interpreter 5. As compared to a compiler
developing a compiler is difficult. developing interpreter is easier.
6. Programming language like 6. Python use interpreter.
C,C++,FORTAN use compiler.
Assembler
An assembler is a program (software) which translates the program written in assembly
language to machine language. It takes the basic commands and operations from assembly
code and converts them into binary code that can be recognized by a specific type of processor.
Assemblers are similar to compilers in that they produce executable code. However, assemblers
are more simplistic since they only convert low-level code (assembly language) to machine
code. Since each assembly language is designed for a specific processor, assembling a program
is performed using a simple one-to-one mapping from assembly code to machine code in that
they produce executable code.
Programs developed using low level languages are fast and memory efficient.
There is no need of any compiler or interpreters to translate the source to machine
code. Thus, cuts the compilation and interpretation time.
It can directly communicate with hardware devices.
Programs developed using low level languages are machine dependent and are not
portable.
It is difficult to develop, debug and maintain.
Programmer must have additional knowledge of the computer architecture of particular
machine, for programming in low level language.
In traditional Programming we start with a problem to solve. We figure out how to break the
problem into smaller parts, and then each part into smaller parts. At each stage we think about
how to do things, then another, then yet another. So divide and conquer with an emphasize on
doing things.
Structured programming is a subset of procedural programming that enforces a logical
structure on the program being written to make it more efficient and easier to understand and
modify.
Structured programming frequently employs a top down top-down design model, in which
developers map out the overall program structure into separate subsections. A defined
function or set of similar function is coded in a separate module or sub-module, which means
that code can be loaded into memory more efficiently and that module can be reused in
another programs. After a module has been tested individually, it is then integrated with other
modules into the overall program structure.
Characteristics Effects
Size Decrease
Speed Increase
Power consumption Decrease
Processing capability Increase
Storage capacity Increase
Reliability and accuracy Increase
Due to this reason ,higher generations computer are better.
2) Discuss briefly about the history of computing and computers. [Assignment]
Problem Analysis
Coding
Documenataion
1) Problem Analysis: It is important to give a clear and precise problem Statement .It is
also called Problem definition. In this step, we should specify the following things.
i. Objectives: The problem should be stated clearly.
ii. Input requirements: To get desired output it is required to define the input data
and source of input data.eg. In student information system, input data may be
students records and source may be college administration.
iii. Output Requirements: We must know what exactly we are expecting out of the
system.
EXAMPLES
Step 1: Start
Step 2: Declare variables a ,b and sum
Step 3: Read value of a and b
Step 4: calculate sum=a+b
Step 5: Display sum
Step 6: Stop
Algorithm for calculating the simple interest using the formula i=p*t*r/100
Step 1: Start
Step 2: Declare variables p, t, r and i
Step 3: Read value of p, t, r
Step 4: i=p*t*r/100
Step 5: Display i
Step 6: Stop
Step 1: Start
Step 2: Declare variables f and c
Step 3: Read value of c
Step 4: calculate f=1.8*c+32
Step 5: Display f
Step 6: Stop
Step 1: Start
Step 2: Declare variables l, b and area
Step 3: Read value of l and b
Step 4: calculate area=l*b
Step 5: Display area
Step 6: Stop
Advantages of Algorithms:
Disadvantages of Algorithms:
Start
Declare variables
a, b and sum
Read a and b
Sum=a + b
Display Sum
Stop
If there is no syntax error, we need to find logical and runtime error. After removing
these errors, it is required to run program with test data to check whether program is
producing correct result or not.
Semantic Error:
This error occurs when the statements written in the program are not meaningful to the
compilers.
eg. a+b=c
Runtime Error:
Error which occur during program execution after successful compilation are called runtime
error.one of the most common run-time error is
Division by zero
Null pointer assignment
Trying to open file that was not created
Logical Error
Logical errors are the errors in the output of the program. The presence of logical errors to
undesired or incorrect output and are caused due to error in logic applied in the program to
produce desired output.
Latent Error:
Latent Errors are the hidden errors that occur only when a particular set of data is used.
Consider below example.
result=(a+b)/(c-d);
An error occurs only when c and d are equal because that make remainder zero (divide by zero
error).Such error can be detected only by using all possible combinations of data.
2) User documentation
Provides the support to user who use the software.
It provides guidelines for installation of program and use it efficiently.
Implementation
After a program has been written and tested it need to be implemented to target
environment to solve problem. Various needs of physical hardware and accessories
required by the program to solve the intended problem needs to be present upon
implementation.
The Evaluation of the performance of program is need to be done at frequent interval once the
program software is implemented. Evaluation can be done by various parameters such as
quality assurance, user friendliness, flexibility and functionality.
Tokens
Tokens are the smallest individual units of program. C has six types of tokens .They are as
follows:
C tokens
special
Keywords Identifiers constants strings Operators
symbols
Keywords are predefined words whose meaning has already defined to c compilers. These
keywords are used for pre-defined purposes and cannot be used as identifier.
The standard keywords are:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue signed void for
default goto sizeof volatile
do if static while
Identifiers
Identifiers are the names given by user to various program elements such as variables, function
and arrays.
What are the rules for naming identifier? [PU: 2014 spring]
Rules of naming Identifiers
Definition:
Data type is a classification of type of data that a variable can hold in programming. The data
type specifies the range of values that can be used and size of memory needed for that value.
Generally data type can be categorized as:
Example
typedef int integer ;
integer symbolizes int data type Now, we can declare int variable “a” as integer a
rather than int a .
Variable is defined as a meaningful name given to the data storage location in computer
memory. It is a medium to store and manipulate data. The value of variable can change
during execution of program.
Variable declaration
Naming a variable along with its data type for programming is known as variable
declaration.
The declaration deals with two things:
It tells the compiler what the variable name is
It specifies what type of data the variable can hold
Syntax:
data_type variable_name ;
eg. int roll;
roll is a variable of type integer. roll can only store integer variable only.
Explain the necessary rules to define the variable name is C programming.[PU:2012 fall]
Which of the following are invalid variable name and why?[PU:2019 fall]
Minimum First.name Row total &name
Doubles rd
3 _row column_total float
2) Runtime initialization
In runtime initialization the value is assigned by using scanf() function.
Syntax:
scanf(“format specifier”,list of address of variable);
eg. scanf(“%d%d”,&a,&b);
Program to illustrate runtime initialization:
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
printf("Entered numbers are %d and %d",a,b);
getch();
return 0;
}
Constants
Constant refers to fixed values that do not change during the execution of program. These fixed
values are also called literals. The C constants are as shown in figure. Number associated
constant are numeric constant and character associated constant are character constants.
Numeric Character
constant constant
Single
Integer String
Real constant character
constant constant
constant
Fractional Exponential
Decimals Octals Hexadecimals
form form
1) Numeric Constant
It consist of:
1.1 Integer constant
It refers to sequence of digits.
There are three types of integer constants.
Decimals: Decimal Integer consist of set of digits, 0 through 9, preceded by an optional +ve or –
ve sign.eg.124,-321,678, 654343 etc.
Octal: An octal Integer constant consist of any combination of digits from the set 0 to 7, with a
leading 0. eg 037, 075, 0664, 0551
Hexadecimal: Hexadecimal are sequence of digits 0-9 and alphabet A-F with preceding 0x or 0X.
eg. 0x5567, 0X53A, 0xFF etc.
1.2. Real or floating point constant
They are numeric constant with decimal points. The real constant are further categorized as
Fractional real constant
They are the set of digits from 0 to 9 with decimal points.eg.394.7867,-0.78676
Exponential real constant
In the exponential form the constants are represented in following form:
mantissa e exponent
where, the mantissa is either a real number expressed in decimal notation or an integer but
exponent is always in integer form. eg.
21565.32=2.156532E4, Where E4=104
2) Character Constant
Statements
A statement is a command given to the computer that instructs the computer to take a specific
action, such as display to the screen, or collect input. A computer program is made up of a
series of statements. Such as:
1) Selection statements (if statements)
2) Iteration Statements (for ,while, etc.)
3) Jump statements ( goto etc.)
Preprocessor directive
Preprocessor directives is a collection of special statement that are executed at the beginning
of compilation process. They are placed in a source program before the main function and
begains with #(Hash).
Some examples of preprocessor directives are
#include<stdio.h> //used for standard input and output
#define PI 3.1416 //used for defining symbolic constant PI as 3.1416
#define TRUE 1 //used for defining True as 1
We use preprocessor directive for
File inclusion
Conditional compilation
Macro expansion
Converting an expression of a given type into another type is known as type casting.
Here, it is best practice to convert lower data type to higher data type to avoid data loss.
1. Implicit Conversion
Implicit conversions do not require any operator for conversion. They are automatically
performed when a value is copied to a compatible data type in the program.
Here, the value of i has been promoted from int to float and we have not had to specify any
type-casting operator
.Program
#include<stdio.h>
int main()
{
int i=20;
float result;
result=i; // implicit conversion
printf("value=%f", result);
return 0;
}
output
Result=20.000000
2) Explicit conversion
In this type of conversion one data type is converted forcefully to another data type by the
user.
The general rule for cast is
(type-name) expression
Where type-name is one of the standard c data types. The expression may be constant ,
variable or an expression.
Example Action
Output
Result=2.50000
Escape sequences
\b Backspace
\n Newline
\r carriage return
\t Horizontal tab
\v Vertical tab
\\ Backslash
Symbolic constant is simply a identifier used in place of constants. They are usually defined as
the start of the program. When the program is compiled each occurrence of symbolic constant
is replaced by corresponding character sequence. Preprocessor directive like #define allow an
identifier to have constant value throughout the program.
The syntax for defining symbolic constant is
#define symbolic_constant_name value
eg .#define PI 3.14159
Advantages:
Modifiability
Understandability
#include<stdio.h>
#include<conio.h>
#define PI 3.1416
int main()
{
float r,area;
printf("\nEnter the value of r\n");
scanf("%f",&r);
area=PI*r*r;
printf("Area=%f",area);
getch();
return 0;
}
Delimiters
Print "passed"
else
Print "failed"
Endif
Advantages:
A beginner can develop the logic to used to solve particular problem without knowing
the syntax of computer language.
Easy to understand and modify.
Can be easily converted into program.
A non-technical professional can easily understand
Disadvantages:
Not recognized by computer
No any fix and standard rules to write pseudocode.so one can misunderstand the
pseudo-code written by other programmer.
ASCII
ASCII is the American Standard Code for Information Interchange. It defines an encoding
standard for the set of characters and unique code for each character in the ASCII chart.
A character variable holds ASCII value (an integer number between 0 and 127) rather than that
character itself in c programming. That value is known as ASCII value.
for example ASCII value of ‘A’ is 65
what this means is that, if you assign ‘A’ to a character variable,65 is stored in that variable
rather than ‘A’ itself.
Characters ASCII values
A-Z 65-90
a-z 97-122
0-9 48-57
C programming language provides many built-in functions to read any given input and to
display data on screen when there is need to output the result. The header file for input/output
functions is <stdio.h>
The input/output function is classified into two types.
1) Formatted I/O functions
2) Unformatted I/O functions
Format specifier
Format specifier is used during input and output. It is the way to tell the compiler what type of
data is in variable during taking input using scanf() or printing using printf().In format specifier
the percentage(%) is followed by conversion character. This indicates the corresponding data
item.
Example:
printf(“%d”,a);
Here %d is format specifier and it tells the compiler that we want to print an integer value that
is present in variable a.
In this way there are several format specifiers in c. Like %c for character, %f for float, etc.
The getchar() reads a character from a standard input device. It buffers the input until the
‘ENTER’ key is pressed and then assigns this character to character variable.
Syntax is :
character_variable=getchar();
where character_variable refers to some previously declared character variable.
Eg.
char c;
c=getchar();
putchar() function displays a character to standard output device.
The function getch() and getche() both reads a single character in a instant. It is typed
without pressing the ENTER key. The difference between them is that getch() reads a
character typed without echoing it on a screen, while getche() reads the character and
echoes (displays) it onto the screen.
Syntax:
character_variable=getch();
characher_varibale=getche();
The function putch() prints a character onto the screen.
Syntax:
putch(character_variable);
Program
#include<stdio.h>
#include<conio.h>
int main()
{
char ch1,ch2;
printf("Enter First character:");
ch1=getch();
printf("\nEnter Second character:");
ch2=getche();
printf("\n Firstcharacter is:");
putch(ch1);
printf("\nSecond character is:");
putch(ch2);
getch();
return 0;
}
At first input getch() function read the character input from the user but that the entered
character was not displayed. But in second input getche() function read the a character from
the user input and entered character was echoed to the user without pressing any key.
Program
#include<stdio.h>
#include<conio.h>
int main()
{
char name[20];
printf("Enter your name:\n");
gets(name);
printf("Your name is:");
puts(name);
getch();
return 0;
}
Operator
Operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
Operators are used in program to manipulate data and variables.
Operand
The data items on which operators are act upon are called operands.
eg. a + b
Here, symbol + is known as operator
a and b are operands
Expression
The combination of variables, constants and operators written according to syntax of
programming language is known as Expression.
eg. a+b*c-5
Types of operators
Types of Operators are classified as:
1. On the basis of no of operands
2. On the basis of function/utility
i) Unary operator
The operator which operates on single operand known as unary operator.
(++) increment Operator
(--) Decrement operator
+ Unary plus
- Unary minus
eg . ++x, -5, +8 , y- - etc.
ii) Binary operator
The operator which operates on two operands are known as binary operator.
eg. +(addition), – (subtraction) , /(division) , * (multiplication) , <(less than) >(greater than)
etc.
eg 3+3, 5>2 , 6*7 , 15-4
Syntax:
expression1? expression2:expression3
The expression1 is evaluated first,
if it is true then expression2 is evaluated and its value becomes value of the expression
If it is false expression3 is evaluated and its value becomes value of the expression.
Eg .Let us consider the program statement
int a=15;b=10,max;
max = (a>b)?a: b;
Here, The value of a will assigned to max.
1) Arithmetic Operators
They are used to perform Arithmetic/Mathematical operations on operands.
Operator Meaning Example
If a=20 and b=10
+ Addition a+b=30
- Subtraction a-b=10
* Multiplication a*b=200
/ Division a/b=2
% Modulo Division a%b=0
2) Relational Operators
These are used to compare two quantities and depending on their relation take certain
decision. The value of relational operator is either 1(if the condition is true) and 0 (if the
condition is false).
4) Assignment Operators
Assignment Operators are used to assign the result of an expression to a variable. The mostly
used assignment operator is “=”.
Operator Name Example
= Assignment c=a+b will assign value of
a+b into c
+= Add AND assignment c+=a is equivalent to c=c+a
6) Conditional Operator
The ternary Operator pair “?:” is available in c to construct condtional expressions of the
form.
expression1? expression2: expression3
The expression1 is evaluated first,
if it is true then the expression 2 is evaluated and its value becomes the value of the
expression.
If expression1 is false expression3 is evaluated and its value becomes the value of the
expression.
Example:
Consider the following statements.
int a, b;
a=10;
b=15;
max= (a>b)? a: b;
In this example value of b will be assigned to max.
Program to find the maximum number between two numbers using conditional operator.
#include<stdio.h>
#include<conio.h>
int main( )
{
int num1,num2,max;
printf("\nEnter the two numbers:\n");
scanf("%d%d",&num1,&num2);
max=(num1>num2)?num1:num2;
printf("\nThe largest number is %d",max);
getch();
return 0;
}
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
8) Special operators
C supports some special operators. Some of them are
i. Sizeof operator
The sizeof is a compile time operator and when used with an operand, it returns the number of
bytes the operand occupies. The operand may ne variable, constant or data type qualifier.
Examples:
m=sizeof(sum);
n=sizeof(long int);
k=sizeof(235L);
Program
#include<stdio.h>
#include<conio.h>
int main()
{
float num;
printf("Number of bytes allocated =%d",sizeof(num));
getch();
return 0;
}
Write a short notes on: Operator precedence and associativity [PU:2018 fall]
Output Output
Output output
Output output
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
char name[20]; float r,area,circum;
printf("Enter your name:"); printf("Enter the radious of circle");
gets(name); scanf("%f",&r);
printf("\nYour name is:"); area=3.1416*r*r;
puts(name); circum=2*3.1416*r;
getch(); printf("\nArea of circle=%f",area);
return 0; printf("\nCircumference of circle is %f",circum);
} getch();
return 0;
}
3) WAP to swap two numbers 4) WAP to swap two numbers without using third
variable.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int a,b,temp; int a,b;
a=5; a=5;
b=10; b=10;
printf("Number before swapping a=%d printf("\nNumber before swappig a=%d and
and b=%d",a,b); b=%d",a,b);
temp=a; a=b+a;
a=b; b=a-b;
b=temp; a=a-b;
printf("\nNumber after swapping a=%d printf("\nNumber after swappig a=%d and b=%d",a,b);
and b=%d",a,b); getch();
getch(); return 0;
return 0;} }
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() #include<math.h>
{ int main()
float centi,fah; {
printf("\nEnter the temperature in int num,a,b,c,arm;
centigrade"); printf("\nEnter the number");
scanf("%f",¢i); scanf("%d",&num);
fah=1.8*centi+32; c=num%10;
printf("\nThe equivalent temperature in b=(num/10)%10;
fahrenheit is %f",fah); a=num/100;
getch(); arm=pow(a,3)+pow(b,3)+pow(c,3);
return 0; if(num==arm)
} {
printf("Entered number is armstrong number");
}
else
{
printf("Entered number is not armstrong
number");
}
getch();
return 0;
}
7) WAP to find the reverse of a given 8) WAP to find the sum of digit of given
(3 digit) number. (3 digit) number.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int num,a,b,c,rev; int num,a,b,c,sum;
printf("Enter the number"); printf("Enter the number");
scanf("%d",&num); scanf("%d",&num);
c=num%10; c=num%10;
b=(num/10)%10; b=(num/10)%10;
a=num/100; a=num/100;
rev=c*100+b*10+a; sum=a+b+c;
printf("Reverse of given number is %d",rev); printf("Sum of digit of given number is %d",sum);
getch(); getch();
return 0; return 0;
} }
What is the purpose of qualifiers register and volatile? [PU: 2013 spring]
A volatile keyword is a qualifier which prevents the objects, from the compiler optimization and
tells the compiler that the value of the object can be change at any time without any action
being taken by the code. It prevents from the cache a variable into a register and ensures that on
every access variable is fetched from the memory.
The volatile keyword is mainly used where we directly deal with GPIO, interrupt or flag Register.
It is also used where a global variable or buffer is shared between the threads
Similary, register is a storage class specifier.The variables which are most frequently used in a C
program can be put in registers using register keyword. The keyword register hints to compiler
that a given variable can be put in a register because register are faster than memory to access.
Flowchart
#include<stdio.h>
#include<conio.h>
int main()
{
int num1,num2,sum;
printf("Enter the two numbers");
scanf("%d%d",&num1,&num2);
sum=num1+num2;
printf("Sum of two numbers is %d",sum);
getch();
return 0
}
They are used when we have a number of situations where we may need to change the order
of execution of statements based on certain conditions.
i. simple if statement
ii. if else statement
iii. nested if else statement
iv. else if ladder
i) Simple if statement
Evaluates the expression first then:
If the value of expression is true , it executes the statement within the block
Otherwise it skips the statements within its block and continues from the first statement
outside the block.
if(test expression)
{
statement-block;
}
statement-x;
WAP to input the average marks of a student and add 10% bonus marks if his/her average
marks is greater than or equal to 65.
#include<stdio.h>
#include<conio.h>
int main()
{
float marks;
printf("Enter the marks\n") ;
scanf("%f",&marks);
if(marks>=65)
{
marks=marks+marks*0.1;
}
printf("Final marks=%f",marks);
getch();
return 0;
}
Syntax Flowchart
if(test_expression)
{
true-block statements
}
else
{
false-block statements
}
statement-x;
#include<stdio.h>
#include<conio.h>
int main()
{
int num1,num2;
printf("Enter the first number\n");
scanf("%d",&num1);
printf("Enter the second number\n");
scanf("%d",&num2);
else
{
printf("Maximum number=%d",num2);
}
getch();
return 0;
}
iii) Nested if-else statement
When a series of decisions are involved, we may have to use more than one if. . . . else
statement in nested form as shown below.
Syntax Flowchart
If(test condition-1)
{
If(test condtion-2)
{
Statement -1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
}
Statement x;
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
printf("Enter three number\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("The largest number is %d",a);
}
else
{
printf("The largest number is %d",c);
}
}
else
{
if(b>c)
{
printf("Largest number is %d",b);
}
else
{
printf("largest number is %d",c);
}
}
It is used when multiple decisions are involved. Here, the condition expression is evaluated in
order.
If any of these expression is true, the statement associated with it is executed and this
terminates the whole chain.
If none of the expression is true then statement associated with final else is executed.
Flowchart
Describe the working of loop and while loop with flowcharts and examples.[PU:2013
fall]
Differentiate between while loop and do while loop. [PU: 2016 spring]
What do you mean by selective and repetitive statement? [PU: 2017 spring]
[Hint for solution: if,if-else,else-if ladder are selective statement and loop statement
such as for,while,do-while are repeatative statement]
Explain entry controlled and exit controlled loops with examples.[PU:2016 fall]
Differentiate between while and do while loops with suitable examples.[PU:2017 fall]
Differentiate pre-test and post-test loop.[PU:2018 spring]
[Hint for solution: while and for loop are pre-test loop and do while is post-test loop]
Why do you mean by entry controlled loop and exit controlled loop ?Explain the
different types of looping constructs available in C with suitable examples.[PU:2014
spring]
What is entry controlled and exit controlled loop?[PU:2019 fall]
Loop control instructions causes a program to execute the certain block of code until some
conditions for termination of loop are satisfied.
Basically there are three types of loop control instructions.
i) while Loop (Entry Controlled loop)
ii) do while loop (Exit Controlled loop)
iii) for loop
i) While loop
Test condition is evaluated first
Syntax:
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
i=1;
while(i<=10)
{
printf("%d\n",i);
i++;
}
getch();
return 0;
}
If test condition is true, the body of the loop is executed again. This process goes on
until the test condition is false.
When test condition is false, loop is terminated and control goes to the statement that
appears immediately after the while statement.
Syntax
do
{
Body of the loop
} while(test condition);
Flowchart
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
i=1;
do
{
printf("%d\n",i);
i++;
}while(i<=10);
getch();
return 0;
}
Differentiate Entry controlled loop (While loop) and Exit controlled loop (Do- While loop)
with examples.
Test condition is evaluated at beginning of the Test condition is evaluated at the end of
loop execution. the body of the loop.
The body of the loop will execute only if the test The body of the loop will execute at least
condition is true. once without depending on the test
condition.
Syntax: Syntax:
while(test condition) do
{ {
Body of the loop Body of the loop
} }while(test condition);
int main()
int main()
{
{
int i=0; int i=0;
while(i>=4) do
{ {
printf(“Hello\n”); printf(“Hello\n”);
i++; i++;
} }while(i>=4);
return 0; return 0;
} }
#include<stdio.h>
#include<conio.h>
int main()
{
int i,sum=0;
for(i=200;i<=500;i++)
{
if(i%5==0)
{
printf("%d\n",i);
sum=sum+i;
}
}
printf("The sum is %d",sum);
getch();
return 0;
}
It have definite number of iterations. It may or may not have definite number of iterations.
In 'for' loop the initialization once done is never In while loop if initialization is done during condition
repeated. checking, then initialization is done each time the loop
iterate.
In 'for' loop iteration statement is written at top, In 'while' loop, the iteration statement can be written
hence, executes only after all statements in loop are anywhere in the loop
executed.
Syntax: Syntax:
for(initialization; test-condition;increment/decrement) while(test condition)
{ {
body of the loop Body of loop
} }
A loop inside another loop is called nesting of loops. There can be any number of loops inside
one another with any combinations depending on the complexity of program.eg. A for loop
inside a while loop or while loop inside a for loop.
Nested while loop Nested do-while loop
while(test-condition1) do
{ {
Statement(s); Statement(s);
while(test-condition2) do
{ {
statement(s); Statement(s);
.............. ............
} }while(test-condition2);
.............. .........
} }while(test-condition1);
for(initialization;testcondition;increment/decrement)
{
Statement(s);
for(initialization;testcondition;increment/decrement)
{
Statement(s);
}
}
Jump statements
Jump Statement makes the control jump to another section of the program unconditionally
when encountered. It is usually used to terminate the loop or switch-case instantly. It is also
used to escape the execution of a section of the program. There are basically three types of
jump statements.
Break
Continue
Goto
i) Break statement
The break statement is used inside the loop or switch statement.
The execution of break statement will abort the loop and continue to execute
statements followed by loop.
Flowchart:
Example
int main()
{
int i;
for(i=1;i<=5;i++)
{
printf("%d\t",i);
if(i==3)
break;
}
printf(“\n loop terminates here.”);
return 0;
}
Output:
1 2 3
Loop terminates here.
while(test condition) do
{ {
statement/s; statement/s;
break; break;
statement/s; statement/s;
} } while(test condition);
statement/s;
if(test condition)
break;
statement/s;
while(test condition) do
{ {
statement/s; statement/s;
continue; continue;
statement/s; statement/s;
} } while(test condition);
statement/s;
if(test condition)
continue;
statement/s;
Write a short nots on: Goto statement [PU:2014 spring][PU:2014 fall][PU:2016 fall]
The goto statement is used to alter the program execution sequence by transferring the control
to some other parts of the program.
Syntax:
. ...........
................
.............
................
goto label;
label:
Statement;
Statement;
Forward jump
Backward jump
where ,label is an identifier that is used to label the target statement to which control will be
transferred.
Note: Use of goto statement is highly discouraged in any programming language because it
makes difficult to trace the control flow of program, making the program hard to modify and
understand.
Program to illustrate the working of goto statement
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
if(a>b)
goto label1;
else
goto label2;
label1:
printf("Greatest number=%d",a);
label2:
printf("Greatest number=%d",b);
getch();
return 0;
}
The control statement that allows us to make a decision from number of choices is called switch
case statement.
The switch case statement successively test the value of a given variables (an expression) with a
list of case value (integer or character constants)
When match is found, the statement associated with that case is executed.
If none of the case value matches the expression then default statement is executed.
General form:
switch(expression)
{
case value-1:
block-1;
break;
Case value-2:
block-2;
break;
...............
default:
default-block;
break;
}
statement-x;
for example, consider the program to display the corresponding days of a week according to
the numbers entered.
#include<stdio.h>
#include<conio.h>
int main()
{
int day;
printf("Enter the numeric day of week\n");
scanf("%d",&day);
switch (day)
{
case 1:
printf("Day is Sunday") ;
break;
case 2:
printf("Day is Monday");
break;
case 3:
printf("Day is Tuesday");
break;
case 4:
printf("Day is Wednesday");
break;
case 5:
printf("Day is Thursday");
break;
case 6:
printf("Day is Friday");
break;
WAP to display the following menu and perform the following operations.
1. Find the simple interest
2. Convert degree Celsius to Fahrenheit
3. Convert character into ASCII code
4. Find the area of circle
5. Exit from the program
and perform above operation until user want to exit.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int choice;
float p,t,r,i,c,f,area;
char ch;
while(1)
{
printf("\nMenu");
printf("\n1.Find simple intrest");
printf("\n2.convert celcius of fahreheit");
printf("\n3.convert character to ASCII code");
printf("\n4.Find area of circle");
printf("\n5.Exit from program");
printf("\nEnter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter Principal,Time and Rate\n");
scanf("%f%f%f",&p,&t,&r);
i=(p*t*r)/100;
printf("simple intrest is %f",i);
break;
If-else Switch
4. Either if statement will be executed or 4. switch statement execute one case after
else statement is executed. another till a break statement is appeared or
the end of switch statement is reached.
5. It does not require break statement 5. It needs the involvement of break statement
because only one of the blocks of code to avoid execution of block just below the
is executed. current executing block.
Differentiate between switch and nested if else statements with a suitable example.[PU:2017 spring]
It is easy to understand for multiple selections. It becomes complicated for multiple selections.
It uses a single expression for all cases,but each case It uses an independent expression for each case.
must have a constant value of integer type or character
type.
Only a single expression is given in the switch The test condtion can be given in a special range of
statement which retruns a single value.The test value.If the given condtion matches then the
condtion cannot be given in a specified range. staements under it will be executed.
Assignment:
What is menu driven structure explain with suitable examples.[PU:2016 spring]
Describe the different types of decision control statements used in C programming with their syntax.
[PU: 2012 fall]
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int a,b,c; int a,b,c,d;
printf("Enter three numbers\n"); printf("Enter the four numbers\n");
scanf("%d%d%d",&a,&b,&c); scanf("%d%d%d%d",&a,&b,&c,&d);
if(a>b&&a<c||a>c&&a<b) if(a>b&&a>c&&a>d)
{ {
printf("second largest(middle) number=%d",a); printf("max=%d",a);
} }
else if(b>a&&b<c||b>c&&b<a) else if(b>c&&b>d)
{ {
printf("second largest(middle) number=%d",b); printf("max=%d",b);
} }
else else if(c>d)
{ {
printf("second largest(middle) number=%d",c); printf("max=%d",c);
} }
getch(); else
return 0; {
} printf("max=%d",d);
}
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
int units;
float amount,total;
printf("Enter the number of units\n");
scanf("%d",&units);
if(units<=20)
{
amount=80;
}
else if(units<=100)
{
amount=80+(units-20)*7.5;
}
else if(units<=200)
{
amount=80+80*7.5+(units-100)*8.5;
}
else
{
amount=80+80*7.5+100*8.5+(units-200)*9.5;
}
total=amount+amount*0.15;
printf("Total charges=%f",total);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
float a,b,c,s,area;
printf("Enter the three sides of traingle\n");
scanf("%f%f%f",&a,&b,&c);
if(a>=(b+c)||b>=(a+c)||c>=(a+b))
{
printf("Invalid Data");
}
else
{
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of traingle=%f",area);
}
getch();
return 0;
}
Income Tax
< RS.10,000 Nil
Rs. 10,000 to Rs.19,999 10%
RS 20,000 to Rs.29,999 15%
RS 30,000 to Rs.49,999 20%
> =Rs.50,000 25%
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int year; char ch;
printf("Enter the year\n"); printf("Enter the character\n");
scanf("%d",&year); scanf("%c",&ch);
if (((year % 4 == 0) && (year % 100!= 0)) || if(ch>=65&& ch<=90)
(year%400 == 0)) {
printf("%d is a leap year", year); printf("The character is uppercase\n");
else ch=ch+32;
printf("%d is not a leap year", year); printf("The equivalent lowercase character is %c",ch);
getch(); }
return 0; else if(ch>=97&&ch<=122)
} {
printf("The character is lowercase\n");
ch=ch-32;
printf("The equivalent uppercase character is %c",ch);
}
else
{
printf("Invalid Input\n");
}
getch();
return 0;
}
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int temp; char ch;
printf("Enter the temperature in Fahrenheit\n"); printf("Enter the character\n");
scanf("%d",&temp); scanf("%c",&ch);
if(temp<=60) if(ch>=97&&ch<=122)
{ {
printf("Cold Day"); printf("You Entered lowercase character");
} }
else if(temp<80) else if(ch>=65&&ch<=90)
{ {
printf("Nice day"); printf("You Entered Uppercase character");
} }
else else if(ch>=48&&ch<=57)
{ {
printf("Hot day"); printf("You Entered Digit");
} }
getch(); else
return 0; {
} printf("You Entered special symbol");
}
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
float sa,sb,ca,cb,nc;
printf("Enter the sales of a and b\n");
scanf("%f%f",&sa,&sb);
if(sa<=2000)
{
ca=sa*0.05;
}
else
{
ca=2000*0.05+(sa-2000)*0.06;
}
if(sb<=4000)
{
cb=sb*0.1;
}
else
{
cb=4000*0.1+(sa-4000)*0.12;
}
nc=ca+cb;
printf("The net commission of these items is %f",nc);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
float salary,netsalary,tax;
printf("Enter the salary\n");
scanf("%f",&salary);
if(salary>=9000)
{
tax=salary*0.4;
}
else if(salary>=7500)
{
tax=salary*0.3;
}
else
{
tax=salary*0.2;
}
netsalary=salary-tax;
printf("Income tax=%f\n",tax);
printf("Net salary=%f",netsalary);
getch();
return 0;
}
13. Write a program and draw a flowchart to read a positive integer value and compute the
following sequence .If the number is even, half it ,if it is odd ,multiply 3 and add 1 print the
result. If the input value is less than 1, print a message containing word “ERROR”.
#include<stdio.h>
#include<conio.h>
int main()
{
int i,sum;
for(i=101;i<200;i++)
{
if(i%5==0)
{
printf("%d\t",i);
sum=sum+i;
}
}
printf("\nThe sum of numbers =%d",sum);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
int sec, h, m, s;
printf("Input seconds: ");
scanf("%d", &sec);
h = (sec/3600);
m = (sec -(3600*h))/60;
s = (sec -(3600*h)-(m*60));
printf("H:M:S - %d:%d:%d\n",h,m,s);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h> #include<stdio.h>
int main() #include<conio.h>
{ int main()
int num,rem,rev=0; {
printf("Enter the number\n"); int num,rem,sum=0;
scanf("%d",&num); printf("Enter the number\n");
while(num!=0) scanf("%d",&num);
{ while(num!=0)
rem=num%10; {
rev=rev*10+rem; rem=num%10;
num=num/10; sum=sum+rem;
}
num=num/10;
printf("Reverse of number=%d",rev);
}
getch();
return 0; printf("sum of digits of number= %d",sum);
} getch();
return 0;
}
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
#include<conio.h>
#include<stdlib.h>
int main()
int main()
{
{
int n,i,sum=0;
int i,num;
printf("Enter the value of n\n");
printf("Enter the number\n");
scanf("%d",&n);
scanf("%d",&num);
for(i=1;i<=n;i++)
if (num <= 1)
{
{
sum=sum+i;
printf("Entered number is not a prime
}
number\n");
printf("The sum natural number is %d",sum);
exit(1);
getch();
}
return 0;
for(i=2;i<num;i++)
}
{
if(num%i==0)
{
printf("Entered number is not prime
number");
break;
}
}if(num==i)
{
printf("Entered number is a prime number");
}
getch();
return 0;
}
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int num,i,sum=0,rem; int num,i,fact,rem,sum=0,temp;
printf("Enter a number: \n"); printf("Enter a number: ");
scanf("%d",&num); scanf("%d",&num);
for(i=1;i<num;i++) temp=num;
{ while(num!=0)
if (num % i == 0) {
{ i=1,fact=1;
sum=sum+i; rem=num%10;
} while(i<=rem)
} {
if(sum==num) fact=fact*i;
{ i++;
printf("The given number is perfect }
number"); sum=sum+fact;
} num=num/10;
else }
{ if(sum==temp)
printf("The given number is not perfect printf("%d is a strong number",temp);
number"); else
} printf("%d is not a strong number",temp);
getch(); getch();
return 0; return 0;
} }
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
char choice; int sum=0,count=0,i;
float m1,m2,m3,total,per; for(i=101;i<200;i++)
do {
{ if(i%5==0)
printf("\nEnter the marks in 3 subjects\n"); {
scanf("%f%f%f",&m1,&m2,&m3); sum=sum+i;
total=m1+m2+m3; count =count+1;
per=(total/3); }
printf("percentage=%f",per); }
printf("\nDo you want to continue\n"); printf("The sum is %d\n",sum);
fflush(stdin); printf("Number of integers greater than 100 and less
scanf("%c",&choice) ; than 200 that are divisible by 5 are %d",count);
system("cls"); getch();
}while(choice=='y'||choice=='Y'); return 0;
getch(); }
return 0;
}
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i,sum=0; int n1,n2,esum=0,osum=0,i;
for(i=1;i<=100;i++) printf("Enter the values of n1 and n2\n");
{ scanf("%d%d",&n1,&n2);
if(i%2==0) for(i=n1;i<=n2;i++)
{ { if(i%2==0)
sum=sum+i; {
} esum=esum+i;
} }
printf("%d\t",sum); else
getch(); {
return 0; osum=osum+i;
} }
}
printf("sum of even number is %d\n",esum);
printf("sum of odd number is %d",osum);
getch();
return 0;
}
13. WAP to find factorial of a given number 14. Write a program to enter numbers until user press
zero(0) and find the sum of supplied numbers.
#include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> int main()
int main() {
{ int sum=0,num;
int num,i,fact = 1; do
printf("Enter a number \n"); {
scanf("%d", &num); printf("Enter number");
for (i= 1; i <= num; i++) scanf("%d",&num);
{ sum=sum+num;
fact = fact * i; }while(num!=0);
{ printf("Total sum of Entered number=%d",sum);
printf("Factorial of given number= %d \n", fact); getch();
getch(); return 0;
return 0; }
}
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i,n, a,b,c; int i,n, a,b,c;
a=0; printf("Enter the values of a and b\n");
b=1; scanf("%d%d",&a,&b);
printf("\nEnter the value of n\n"); printf("\nEnter the value of n\n");
scanf("%d",&n); scanf("%d",&n);
printf("%d\t%d\t",a,b); printf("%d\t%d\t",a,b);
for (i= 1; i <= n-2; i++) for (i= 1; i <= n-2; i++)
{ {
c=a+b; c=a+b;
printf("%d\t",c); printf("%d\t",c);
a=b; a=b;
b=c; b=c;
} }
getch(); getch();
return 0; return 0;
} }
17. WAP to print prime number from 1 to 18. WAP to convert decimal number to binary
200. [PU:2017 spring] number
#include<stdio.h>
#include<conio.h> #include<stdio.h>
int main() #include<conio.h>
{ int main()
int i,j; {
for(i=1;i<=200;i++) int num,i,base=1,sum=0,rem;
{ printf("Enter the number\n");
for(j=2;j<i;j++) scanf("%d",&num);
{ i=num;
if(i% j==0) while(num!=0)
{ {
break; rem=num%2;
} sum=sum+rem*base;
} base=base*10;
if(i==j) num=num/2;
{ }
printf("%d\n",i); printf("Binary equivalent of %d is %d",i,sum);
} }
}
getch();
return 0;}
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
#include<conio.h>
int main()
int main()
{
{
int num,i,pro;
int i,rem,sum,num;
printf("Enter the number\n");
for(i=100;i<=999;i++)
scanf("%d",&num);
{
for(i=1;i<=10;i++)
num=i;
{
sum=0;
pro=num*i;
while(num!=0)
printf("%d*%d=%d",num,i,pro);
{
printf("\n");
rem=num%10;
sum=sum+rem*rem*rem;
}
num=num/10;
getch();
}
return 0;
if(sum==i)
}
{
printf("%d\t",sum);
}
}
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int choice;
float p,t,r,i,c,f,area;
char ch;
printf("Menu\n");
printf("1.Find simple interest\n");
printf("2.convert Celsius of Fahrenheit\n");
printf("3.convert character to ASCII code\n");
printf("4.Find area of circle\n");
printf("5.Exit from program\n");
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter Principal,Time and Rate\n");
scanf("%f%f%f",&p,&t,&r);
i=(p*t*r)/100;
printf("simple intrest is %f",i);
break;
case 2:
printf("Enter the temperature in celcius\n");
scanf("%f",&c);
f=1.8*c+32;
printf("Converted temp is %f",f);
break;
case 3:
printf("Enter a character\n");
scanf("%c",&ch);
printf("The corresponding ASCII code is %d",ch);
break;
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str1[20],str2[20];
int choice,i,j;
printf("Menu\n");
printf("1.check whether the given string is palindrome or not\n");
printf("2.Find all prime numbers from 100 to 200\n");
printf("3.Display all ascii characters from 0 to 255\n");
printf("4.Exit from program\n");
printf("Enter your choice\n");
scanf("%d",&choice);
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int choice,i,rem,sum=0,rev=0,num;
printf("Menu\n");
printf("1.Reverse a number\n");
printf("2.Find sum of individual unit\n");
printf("3.Check for prime\n");
printf("4.Exit from program\n");
printf("Enter the number\n");
scanf("%d",&num);
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
while(num!=0)
{
rem=num%10;
rev=rev*10+rem;
num=num/10;
}
printf("Reverse of number=%d",rev);
break;
case 2:
while(num!=0)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
printf("The sum of digits of number=%d",sum);
break;
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int choice,n,sum=0,i,code;
while(1)
{
printf("\nMenu\n");
printf("1.Conversion of ASCII code to char\n");
printf("2.Find sum of n natural numbers\n");
printf("3.Exit from program\n");
printf("Enter your choice\n");
scanf("%d",&choice);
case 2:
printf("Enter the value of n\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf("sum=%d",sum);
break;
case 3:
exit(0);
break;
default:
printf("Wrong choice!");
}
}
getch();
return 0;
}
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i,j; int i,j;
for(i=1;i<=3;i++) for(i=1;i<=5;i++)
{ {
for(j=1;j<=i;j++) for(j=1;j<=i;j++)
{ {
printf("%d\t",j); printf("%d\t",j);
} }
printf("\n"); printf("\n");
} }
getch(); getch();
return 0; return 0;
} }
2 2 1 1
3 3 3 1 1 1
4 4 4 4 1 1 1 1
5 5 5 5 5 1 1 1 1 1
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i,j; int i,j;
for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ {
for(j=1;j<=i;j++) for(j=1;j<=i;j++)
{ {
printf("%d\t",i); printf("1\t");
} }
printf("\n"); printf("\n");
} }
getch(); getch();
return 0; return 0;
} }
5) * * * * * 6) 5 5 5 5 5
* * * * 4 4 4 4
* * * 3 3 3
* *
2 2
*
1
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i,j; int i,j;
for(i=5;i>=1;i--) for(i=5;i>=1;i--)
{ {
for(j=1;j<=i;j++) for(j=1;j<=i;j++)
{ {
printf("*\t"); printf("%d\t",i);
} }
printf("\n"); printf("\n");
} }
getch(); getch();
return 0; return 0;
} }
[PU:2019 fall]
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i,j; int i,j;
for(i=5;i>=1;i--) for(i=5;i>=1;i--)
{ {
for(j=1;j<=i;j++) for(j=1;j<=i;j++)
{ {
printf("%d\t",j); printf("1\t");
} }
printf("\n"); printf("\n");
} }
getch(); getch();
return 0; return 0;
} }
9) 5 4 3 2 1 10) 1
5 4 3 2
2 3
5 4 3
4 5 6
5 4
7 8 9 10
5
11 12 13 14 15
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i,j; int i,j,a=1;
for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ {
for(j=5;j>=i;j--) for(j=1;j<=i;j++)
{ {
printf("%d\t",j); printf("%d\t",a);
} a++;
printf("\n"); }
} printf("\n");
getch(); }
return 0; getch();
} return 0;}
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i,j,k=1; int i,j;
for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ {
for(j=1;j<=i;j++) for(j=1;j<=5;j++)
{ {
printf("%d\t",k); printf("%d\t",i*j);
k=k+10; }
} printf("\n");
printf("\n"); }
} getch();
getch(); return 0;
return 0; }
}
13) * 14) 1
* * 2 2
* * * 3 3 3
* * * * 4 4 4 4
* * * * * 5 5 5 5 5
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int i,j,k; int i,j,k;
for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ {
for(k=4;k>=i;k--) for(k=4;k>=i;k--)
{ {
printf("\t"); printf("\t");
} }
for(j=1;j<=i;j++) for(j=1;j<=i;j++)
{ {
printf("*\t"); printf("%d\t",i);
} }
printf("\n"); printf("\n");
} }
return 0; return 0;
} }
int main()
{
int i,j;
for(i=0;i<=20;i++)
{
printf(“%d\n”,i++);
}
return 0;
}
(Trace the program yourself)
Output:
0
2
4
6
8
10
12
14
16
18
20
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int n,i;
float x,sum=0;
printf("Enter the value of x");
scanf("%f",&x);
printf("Enter the number of terms");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
sum=sum+(1/pow(x,i));
}
printf("sum=%f",sum);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int n,i,j,fact;
float x,sum=1;
printf("Enter the value of x");
scanf("%f",&x);
printf("Enter the value of n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact=1;
for(j=1;j<=i;j++)
{
fact=fact*j;
}
sum=sum+pow(x,i)/(float)fact;
}
printf("sum=%f",sum);
getch();
return 0;
}
Write a program to generate the following series and print the sum.
1x4,2x7, 3x10 . . . . . . . . n terms
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,n,sum=0;
printf("Enter the number of term");
scanf("%d",&n);
for(i=1,j=4;i<=n;i++,j+=3)
{
printf("%dx%d\t",i,j);
sum=sum+(i*j);
}
printf("\nsum of series=%d",sum);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int i,x,n;
float a,sum=0;
printf("Enter the value of x");
scanf("%d",&x);
printf("Enter the value of n");
scanf("%d",&n);
if(n==0)
{
printf("There is no term");
}
if(n==1)
{
printf("The term is %d",x);
}
if(n>=2)
{ printf("The term is \t%d",x);
for(i=2;i<=n;i++)
{
a=(pow(-1,i)*i)/pow(x,i);
printf("\t%f",a);
sum=sum+a;
}
printf("\nThe sum of terms=%f",sum+x);
}
getch();
return 0;
}
WAP to compute the given series.
Sin( x)= x - x3/3! + x5/5! - x7/7! + x9/9! ........
#include<stdio.h>
#include<conio.h>
int main()
{
int i,n,sign=1;
float x,nume,deno,sum=0,val,term;
printf(" Enter the value for x in degree:");
scanf("%f",&x);
#include<stdio.h>
#include<conio.h>
int main()
{
int i,n,sign=1;
float x,nume,deno,sum=0,val,term;
printf(" Enter the value for x in degree:");
scanf("%f",&x);
printf(" Enter the value for n :");
scanf("%d",&n);
val=x;
x=x*3.14159/180;
nume=1;
deno=1;
sum=1;
for(i=2;i<=n;i++)
{
nume=nume*x*x;
deno=deno*(i*2-3)*(i*2-2);
sign=sign*(-1);
term=nume/deno*sign;
sum=sum+term;
}
printf("\ncos(%f)=%f",val,sum);
getch();
return 0;}
Limitation of Array
Memory allocation in array are static in nature. Which means memory is allocated before the
execution of program begins (During compilation).In this type of allocation the memory cannot
be resized after initial allocation. So it has some limitations.
Wastage of memory
Overflow of memory
eg. int num[100];
Here, the size of an array has been fixed to 100.If we just enter to 10 elements only,
then their will be wastage of 90 memory location and if we need to store more than 100
elements there will be memory overflow.
Types of array
1. One dimensional Array
2. Multidimensional Array
value
Declaration:
data_type array_name[size];
eg. int num[10];
Here, int is a data type and num is the name of the array and 10 is the size of the array. It
means num can only contain 10 elements of int type.
After the array is declared it must be initialized, otherwise it will contain garbage value (any
random value) .An array can be initialized at either compile time or runtime.
2) Runtime initialization
An array can also be initialized at runtime using scanf() function. This Approach is used for
initializing large arrays with user specified values.
#include<stdio.h>
#include<conio.h>
int main()
{
int num[5];
int i;
printf("\nEnter the array elements");
for(i=0;i<5;i++)
{
scanf("%d",&num[i]);
}
printf("\nArray elements are");
for(i=0;i<5;i++)
{
printf("\n%d",num[i]);
}
getch();
return 0;
Example:
int survey[3][5][12];
Here, survey is a three dimensional array declared to contain 180 integer type elements.
Two dimensional array may be initialized by following their declaration with a list of
values enclosed in braces.
Example: int arr[3][3]={ {2,4,6},{8,9,12},{15,16,18}};
These are equivalent to following assignments
arr[0][0]= 2 arr[0][1]= 4 arr[0][2]= 6
arr[1][0]= 8 arr[1][1]= 9 arr[1][2]= 12
arr[2][0]=15 arr[2][1]= 16 arr[2][2]=18
Similarly for,
int arr[2][3]={{1,5,10},{1,10,15}};
int arr[3][4]={{65,85,75,50},{67,65,45,75},{35,5,60,50}};
Note: When array is completely initialized with all values, explicitly, we need not specify the size
of the first dimension.
That is the statement,
int arr[ ][ 3]={{2,4,6},{8,9,12},{15,16,18}}; is permitted.
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j;
int arr[3][3]={{12,14,16},{5,7,15},{15,25,45}};
printf("The matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
printf("\n");
}
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j;
int arr[3][3];
printf("Enter the elements of matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&arr[i][j]);
}
}
printf("Elements of matrix are\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
printf("\n");
}
getch();
return 0;
}
Why array is important in programming? How can you initialize different types of arrays?
Explain 2-dimensional array in C.[PU: 2014 spring,2018 fall]
If we want many elements of similar type than it is not feasible to declare all variables and also
manipulate these elements. So in this case we use array.
For example, if we want 100 integer variables, then instead of writing all 100 variables, we use
array like int num[100]. Here 100 integer elements num[0], num[1], num[2]. . . . . .num[99] are
declared. Due to these reason array is important in programming.
Example:
for(i=0;i<5;i++)
{
scanf("%d",&num[i]);
}
This program statement initializes 5 arrays elements num[0],num[1],num[2],num[3],num[4]
with user specified values.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i,num[10]; int i,num[100],n;
printf("Enter 10 array elements\n"); printf("Enter number of array elements \n");
for(i=0;i<10;i++) scanf("%d",&n);
{ printf("Enter %d array elements\n",n);
scanf("%d",&num[i]); for(i=0;i<n;i++)
} {
printf("The array elements are\n"); scanf("%d",&num[i]);
for(i=0;i<10;i++) }
{ printf("Array elements in reverse order are\n");
printf("%d\n",num[i]); for(i=n-1;i>=0;i--)
} {
getch(); printf("%d\n",num[i]);
return 0; }
} getch();
return 0;
}
2) WAP to input n number in an array and 4) WAP to read n numbers using array and find their
display it. average.
#include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> int main()
int main() {
{ int n,i;
int i,num[100],n; float num[100],sum=0,avg;
printf("Enter the number of array printf("Enter number of array elements \n");
elements\n"); scanf("%d",&n);
scanf("%d",&n); printf("Enter %d elements\n",n);
printf("Enter %d array elements\n",n); for(i=0;i<n;i++)
for(i=0;i<n;i++) {
{ scanf("%f",&num[i]);
scanf("%d",&num[i]); }
} for(i=0;i<n;i++)
printf("The array elements are\n"); {
for(i=0;i<n;i++) sum=sum+num[i];
{ }
printf("%d\n",num[i]); avg=sum/n;
}
getch(); printf("Average=%f\n",avg);
return 0; getch();
} return 0;}
#include<stdio.h>
#include<conio.h>
int main()
{
float temp[7],dev,sum=0,avg;
int i;
for(i=0;i<7;i++)
{
printf("Enter the temperature of Day %d \n",i+1);
scanf("%f",&temp[i]);
sum=sum+temp[i] ;
}
avg=sum/7;
printf("\nThe Average temperature of days = %f",avg);
for(i=0;i<7;i++)
{
dev=temp[i]-avg;
printf("\nThe Deviation of temperature from day %d =%0.2f",i+1,dev);
}
getch();
}
8) WAP to read the marks of 10 students calculate and display the average marks and
deviation of marks of each student from average marks.
#include<stdio.h>
#include<conio.h>
int main()
{
float marks[10],avg,dev,sum=0;
int i;
printf("Enter the marks of 10 students\n");
for(i=0;i<10;i++)
{
scanf("%f",&marks[i]);
sum=sum+marks[i];
}
avg=sum/10;
printf("The average marks is \t%f",avg);
printf("\nThe deviation of each student from average\n");
for(i=0;i<10;i++)
{ dev=marks[i]-avg;
printf("\nmarks[%d]=%f\tdeviation=%f",i,marks[i],dev);
}
getch();
return 0;
}
#include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> int main()
int main() {
{ int i,num[100],n,large,small;
int i,num[100],n,large; printf("Enter the number of array elements ");
printf("Enter the number of array elements\n"); scanf("%d",&n);
scanf("%d",&n); printf("Enter %d elements\n",n);
printf("Enter %d elements\n",n); for(i=0;i<n;i++)
for(i=0;i<n;i++) {
{ scanf("%d",&num[i]);
scanf("%d",&num[i]); }
} large=num[0];
large=num[0]; small=num[0];
for(i=1;i<=n;i++) for(i=1;i<n;i++)
{ {
if(num[i]>large) if(num[i]>large)
{ {
large=num[i]; large=num[i];
} }
} if(num[i]<small)
printf("Largest number=%d",large); {
getch(); small=num[i];
return 0; }
}
}
printf("Largest number=%d",large);
printf("\nSmallest number=%d",small);
getch();
return 0;
}
Assignment:
Write a C program using array to find largest and
smallest number from the list of 100 given
numbers.[PU:2017 spring]
#include<stdio.h>
#include<conio.h>
int main()
{
int i,num[100],n,pcount=0,ncount=0,zcount=0;
printf("Enter the number of array elements\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&num[i]);
}
for(i=0;i<n;i++)
{
if(num[i]>0)
{
pcount++;
}
else if(num[i]<0)
{
ncount++;
}
else
{
zcount++;
}
}
printf("Number of postive numbers=%d",pcount);
printf("\nNumber of Negative numbers=%d",ncount);
printf("\nNumber of Zeros=%d",zcount);
getch();
return 0;
}
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int a[100],b[100],i,n; int a[100],b[100],i,j,n;
printf("Enter number of array elements\n"); printf("Enter the number of array elements\n");
scanf("%d",&n); scanf("%d",&n);
printf("Enter %d elements\n",n); printf("Enter %d elements\n",n);
for(i=0;i<n;i++) for(i=0;i<n;i++)
{ {
scanf("%d",&a[i]); scanf("%d",&a[i]);
} }
printf("\nThe entered elements are:\n"); printf("The array elements are\n");
for(i=0;i<n;i++) for(i=0;i<n;i++)
{ {
printf("%d\n",a[i]); printf("%d\n",a[i]);
} }
for(i=0;i<n;i++) for(i=0,j=n-1;i<n;i++,j--)
{ {
b[i]=a[i]; b[i]=a[j];
} }
printf("\nThe copied elements are\n"); printf("The copied array elements in reverse order
for(i=0;i<n;i++) are\n");
{ for(i=0;i<n;i++)
printf("%d\n",b[i]); {
} printf("%d\n",b[i]);
getch(); }
return 0; getch();
} return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
float marks[100],temp;
int i,j,n;
printf("Enter the number of students\n");
scanf("%d",&n);
printf("Enter the marks of %d students\n",n);
for(i=0;i<n;i++)
{
scanf("%f",&marks[i]);
}
printf("\nEntered marks of studenst are:\n");
for(i=0;i<n;i++)
{
printf("%f\n",marks[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(marks[j]<marks[j+1])
{
temp=marks[j];
marks[j]=marks[j+1];
marks[j+1]=temp;
}
}
}
printf("\nMarks of Top five students are:\n");
for(i=0;i<5;i++)
{
printf("%f\n",marks[i]);
}
getch();
return 0;
}
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int fib[10],i; int a[100],flag,n,i,j,sum=0;
fib[0]=0; printf("Enter the no. of elements:");
fib[1]=1; scanf("%d",&n);
printf("The fibonacci series is \n"); printf("Enter %d array elements\n",n);
printf("%d\t%d\t",fib[0],fib[1]); for(i=0;i<n;i++)
for(i=2;i<=9;i++) {
{ scanf("%d",&a[i]);
fib[i]=fib[i-1]+fib[i-2]; }
} printf("\nprime numbers are:\n");
for(i=2;i<=9;i++) for(i=0;i<n;i++)
{ {
printf("%d\t",fib[i]); flag=0;
} for(j=2;j<a[i];j++)
getch(); {
return 0; if(a[i]%j==0)
} {
flag=1;
break;
}
}
if(flag==0)
{
printf("%d\t",a[i]);
sum=sum+a[i]
}
}
printf("\nThe sum of prime no. is %d",sum);
getch();
}
1) WAP to input 3*3 matrix and display 2) WAP to read the matrix of size 2*3
it. from user and display it to the screen.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int arr[20][20],i,j,m,n; int arr[20][20],i,j,m,n;
printf("Enter the size of row and column of printf("Enter the Row size and column size of matrix\n");
matrix\n"); scanf("%d%d",&m,&n);
scanf("%d%d",&m,&n); printf("Enter %d elements of matrix\n",m*n);
printf("Enter %d elements of matrix",m*n); for(i=0;i<m;i++)
for(i=0;i<m;i++) {
{ for(j=0;j<n;j++)
for(j=0;j<n;j++) {
{ scanf("%d",&arr[i][j]);
scanf("%d",&arr[i][j]); }
} }
} for(i=0;i<m;i++)
printf("Enterd matrix is :\n"); {
for(i=0;i<m;i++) for(j=0;j<n;j++)
{ {
for(j=0;j<n;j++) arr[i][j]=3*arr[i][j];
{ }
printf("%d\t",arr[i][j]); printf("\n");
} }
printf("\n"); for(i=0;i<m;i++)
} {
getch(); for(j=0;j<n;j++)
return 0; {
} printf("%d\t",arr[i][j]);
}
printf("\n");
}
getch();
return 0;
}
5) WAP to input 3*3 order matrix and perform the following operations
Find sum of all elements
Product of all elements
(Perform similar operation for m*n matrix)
#include <stdio.h>
#include <conio.h>
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int arr[20][20],i,j,m,n,sum=0; int arr[20][20],i,j,m,n,sum=0;
printf("Enter the order of matrix\n"); printf("Enter the order of matrix\n");
scanf("%d%d",&m,&n); scanf("%d%d",&m,&n);
if(m==n) if(m==n)
{ {
printf("Enter %d elements of matrix\n",m*n); printf("Enter %d elements of matrix\n",m*n);
for(i=0;i<m;i++) for(i=0;i<m;i++)
{ {
for(j=0;j<n;j++) for(j=0;j<n;j++)
{ {
scanf("%d",&arr[i][j]); scanf("%d",&arr[i][j]);
} }
} }
for(i=0;i<m;i++) for(i=0;i<m;i++)
{ {
for(j=0;j<n;j++) for(j=0;j<n;j++)
{ {
if(i==j) if((i+j)==(m-1))
{ {
sum=sum+arr[i][j]; sum=sum+arr[i][j];
} }
} }
} }
printf("sumof diagonal elements from left=%d",sum); printf("sum of diagonal elements from right=%d",sum);
} }
else else
{ {
printf("Invalid oder of matrix for this operation\n"); printf("Invalid oder of matrix for this operation\n");
} }
getch(); getch();
return 0; return 0;
} }
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int arr[20][20],i,j,m,n,large; int arr[20][20],i,j,m,n,small;
printf("Enter the order of matrix \n"); printf("Enter the order of matrix\n");
scanf("%d%d",&m,&n); scanf("%d%d",&m,&n);
printf("Enter %d elements of matrix\n",m*n); printf("Enter %d elements of matrix\n",m*n);
for(i=0;i<m;i++) for(i=0;i<m;i++)
{ {
for(j=0;j<n;j++) for(j=0;j<n;j++)
{ {
scanf("%d",&arr[i][j]); scanf("%d",&arr[i][j]);
} }
} }
large=arr[0][0]; small=arr[0][0];
for(i=0;i<m;i++) for(i=0;i<m;i++)
{ {
for(j=0;j<n;j++) for(j=0;j<n;j++)
{ {
if(large<arr[i][j]) if(small>arr[i][j])
{ {
large=arr[i][j]; small=arr[i][j];
} }
} }
} }
printf("largest element=%d",large); printf("smallest element=%d",small);
getch(); getch();
return 0; return 0;
} }
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[20][20],i,j,m,n,esum=0,osum=0,ecount=0,ocount=0;
printf("Enter the order of matrix\n");
scanf("%d%d",&m,&n);
printf("Enter %d elements of matrix\n",m*n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(arr[i][j]%2==0)
{
esum=esum+arr[i][j];
ecount++;
}
else
{
osum=osum+arr[i][j];
ocount++;
}
}
}
printf("sum of even number=%d\n",esum);
printf("Number even number=%d\n",ecount);
printf("Sum of odd number=%d\n",osum);
printf("Number of odd number=%d",ocount);
getch();
return 0;
}
13) Write a program to read values of 3*3 order matrix the compute the sum of even
elements.[PU:2012 fall]
Compiled By: Pradip Paudel Page:27
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[3][3],i,j,esum=0;
printf("Enter the elements of matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(arr[i][j]%2==0)
{
esum=esum+arr[i][j];
}
}
}
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[3][3],i,j,osum=0;
printf("Enter the elements of matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(arr[i][j]%2!=0)
{
osum=osum+arr[i][j];
}
}
}
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int arr[20][20],i,j,r,sum=0,m,n; int arr[20][20],i,j,c,sum=0,m,n;
printf("Enter the order of matrix\n"); printf("Enter the order of matrix\n");
scanf("%d%d",&m,&n); scanf("%d%d",&m,&n);
printf("Enter %d elements of matrix\n",m*n); printf("Enter %d elements of matrix\n",m*n);
for(i=0;i<m;i++) for(i=0;i<m;i++)
{ {
for(j=0;j<n;j++) for(j=0;j<n;j++)
{ {
scanf("%d",&arr[i][j]); scanf("%d",&arr[i][j]);
} }
} }
printf("Enter the row that you want find sum\n"); printf("Enter the column that you want find sum\n");
scanf("%d",&r); scanf("%d",&c);
if(r<=m) if(c<=n)
{ {
r=r-1; c=c-1;
for(i=0;i<n;i++) for(i=0;i<m;i++)
{ {
sum=sum+arr[r][i]; sum=sum+arr[i][c];
} }
printf("sum of %d row is %d\n",r+1,sum); printf("sum of %d column is %d\n",c+1,sum);
} }
else else
{ {
printf("Invalid request"); printf("Invalid request!");
} }
getch(); getch();
return 0; return 0;
} }
#include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> int main()
#include<math.h> {
int main() int a[3][3],b[3][3],sum[3][3],i,j;
{ printf("Enter elements of first matrix\n");
int arr[20][20],i,j,m,n,sum=0; for(i=0;i<3;i++)
float norm; {
printf("Enter the order of matrix\n"); for(j=0;j<3;j++)
scanf("%d%d",&m,&n); {
printf("Enter %d elements of matrix\n",m*n); scanf("%d",&a[i][j]);
for(i=0;i<m;i++) }
{ }
for(j=0;j<n;j++) printf("Enter elements of second matrix\n");
{ for(i=0;i<3;i++)
scanf("%d",&arr[i][j]); {
} for(j=0;j<3;j++)
} {
printf("Entered matrix is :\n"); scanf("%d",&b[i][j]);
for(i=0;i<m;i++) }
{ }
for(j=0;j<n;j++) for(i=0;i<3;i++)
{ {
printf("%d\t",arr[i][j]); for(j=0;j<3;j++)
} {
printf("\n"); sum[i][j]=a[i][j]+b[i][j];
} }
for(i=0;i<m;i++) }
{ printf("sum of matrix is :\n");
for(j=0;j<n;j++) for(i=0;i<3;i++)
{ {
sum=sum+pow(arr[i][j],2); for(j=0;j<3;j++)
} {
} printf("%d\t",sum[i][j]);
norm=sqrt((float)sum); }
printf("Norm of the matrix=%f",norm); printf("\n");
getch(); }
return 0; getch();
} return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
int a[20][20],b[20][20],mul[20][20],i,j,k,r1,c1,r2,c2;
printf("Enter the row and column of first matrix\n");
scanf("%d%d",&r1,&c1);
printf("Enter the row and column of second matrix\n");
scanf("%d%d",&r2,&c2);
if(c1!=r2)
{
printf("Matix multiplication is not possible");
}
else
{
printf("Enter %d elements of first matrix\n",r1*c1);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter %d elements of second matrix\n",r2*c2);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
mul[i][j]=0;
for(k=0;k<c1;k++)
{
mul[i][j]=mul[i][j] +a[i][k]*b[k][j];
}
}
}
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
int main()
{
int a[20][20], b[20][20];
int i, j, m1, n1, m2, n2, flag = 1;
printf("Enter the order of first matrix \n");
scanf("%d%d", &m1, &n1);
printf("Enter the order of second matrix \n");
scanf("%d%d", &m2, &n2);
if (m1==m2&&n1==n2)
{
printf("Enter the elements of first matrix \n");
for (i = 0;i<m1;i++)
{
for (j = 0; j<n1; j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of second matrix \n");
for (i = 0; i < m2; i++)
{
for (j = 0; j <n2; j++)
{
scanf("%d",&b[i][j]);
}
}
else
{
printf("Two matrix cannot be compared\n");
}
getch();
return 0;
}
27) Write a program that asks a user for a number and find outs if the number is present in 2D
array given below.
int arr[3][3]=
{
{6,37,33},
{12,11,13},
{14,85,96}
};
Declaration:
char string_name[size];
Here, size determines the number of characters in string_name.
Eg. char name[5];
Note: When the compiler assigns a character string to character array, it automatically supplies
a null character (‘\0’) at the end of string. Therefore, size should be equal to maximum number
of characters in string plus one.
Initialization of strings
Compile time initialization
General form:
char string_name[size]=”list of character”;
eg. char name[5]=”raju”;
OR
char string_name[size]={list of character};
eg. char name[5]={‘r’,’a’,’j’,’u’,’\0’};
Note: C also permits to initialize a character array without specifying the number of elements.
In such cases size of array will determined automatically,based on number of elements
initialized.
Eg. char name[ ]={‘r’,’a’,’j’,’u’,’\0’};
defines, the array string as a five element array.
Greeting message:Hello
Name:raju
Runtime initialization
The familiar input function scanf() can be used with %s format specification to read string.
Example:
char name[20];
scanf(“%s”,name);
Limitation: Here, string variable takes only single word, It is because when whitespace is
encountered the scanf() function terminates,
Output:
To overcome this problem the gets() function is used to read a string of text containing
whitespaces, until newline character is encountered.
#include<stdio.h>
#include<conio.h>
int main()
{
char name[20];
printf("Enter your name:");
gets(name);
printf("Your name is:");
puts(name);
getch();
return 0;
}
Output:
String handling function makes the manipulation of string easier and available in string.h
header file. Some of them are as follows:
Output:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[20];
int len;
printf("Enter the string:");
gets(str);
len=strlen(str);
printf("The length of a string is %d",len);
getch();
return 0;
}
Output:
Enter the string : ramesh
The length of string is 6
b) strcpy()
This function copies one string to another. The function accepts two strings as
parameters and copies the second string character by character into first one upto
including the null character of the second string.
The syntax is :
strcpy(destination_string,source_string);
i.e. strcpy(str2,str1) means the content of str1 is copied to str2.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str1[20]="ramesh",str2[20];
strcpy(str2,str1);
printf("The copied string is %s",str2);
getch();
return 0;
}
output:
c) strcat()
This function concatenates two strings i.e it appends one string at the end of another.
This function accepts two strings as parameters and stores the contents of second
string at the end of first. Its syntax is :
strcat (string1,string2);
ie.string1=string1+string2
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str1[20]="pokhara",str2[20]="university";
strcat(str1,str2);
printf("The concatenated string is %s",str1);
getch();
return 0;
}
Output:
The concatenated string is pokharauniversity
The two strings are compared character by character until there is a mismatch or end of
one string is reached. Whenever two characters in two string differ, the string which has
the character with higher ASCII value is greater.
For example, consider two strings “ram” and “rajesh”.The first two characters are same
but the third character in string ram and that is in rajesh are different. Since ASCII value
of character m in string is ram is greater than that of j in string rajesh, the string ram is
greater than rajesh.
Its syntax is:
integer_variable=strcmp(string1,string2);
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str1[20],str2[20];
int diff;
printf("Enter the first string:");
gets(str1);
printf("Enter the second string:");
gets(str2);
diff=strcmp(str1,str2);
if(diff>0)
{
printf("%s is greater than %s",str1,str2);
}
else if(diff<0)
{
printf("%s is greater than %s ",str2,str1);
}
else
{
printf("Both strings are same");
}
getch();
return 0;
}
Output
Enter first string: ram
Enter second string: rajesh
ram is greater than rajesh
This function is used to reverse all characters in a string except null character at the end of
string. The reverse of string “abc” is “cba”.
It’s syntax is strrev(string);
For example:
strrev(s) means it reverses the characters in string s and stores reversed string in s.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[20]="hello";
strrev(str);
printf("Reversed string is %s\n",str);
getch();
return 0;
}
Output
Reversed string is olleh
f) strupr()
This function converts the lowercase string into uppercase.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[20]="hello";
strupr(str);
printf("The uppercase of given string is %s",str);
getch();
return 0;
}
Output:
The uppercase of given string is HELLO
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[20]="HELLO";
strlwr(str);
printf("The lowercase of given string is %s",str);
getch();
return 0;
}
Output
The lowercase of given string is hello.
Assignment:
Write a program to read n employees names and display them in alphabetical order.[PU:2014
spring]
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
#include<string.h> int main()
int main() {
{ char str[20];
char str[20],ch; int i;
int len,i,pos; printf("Enter the string\n");
printf("Enter the string\n"); gets(str);
gets(str); for(i=0;str[i]!='\0';i++)
printf("Enter the index position you want to insert\n"); {
scanf("%d",&pos); if(str[i]>='a'&&str[i]<='z')
printf("Enter the character you want to insert\n"); {
scanf("%c",&ch); str[i]=str[i]-32;
len=strlen(str); }
for(i=len+1;i>pos;i--) else
{ {
str[i]=str[i-1]; str[i]=str[i]+32;
} }
str[pos]=ch;
printf("Resulting string is \n"); }
puts(str); printf("The converted string is %s",str);
getch(); getch();
return 0; return 0;
} }
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
#include<string.h> int main()
#include<ctype.h> {
int main() char str[100], word[20];
{ int i, index, flag = 0;
char str[20]; printf("Enter any string: ");
int i,l; gets(str);
printf("Enter the string\n"); printf("Enter word to be searched: ");
gets(str); gets(word);
l=strlen(str); for(index=0;str[index] != '\0';index++)
for(i=0;i<l;i++) {
{ if(str[index] == word[0])
if(islower(str[i])) {
{ flag = 1;
str[i]=toupper(str[i]); for(i=0;word[i] != '\0';i++)
} {
if(str[index + i] != word[i])
else {
{ flag = 0;
str[i]=tolower(str[i]); break;
} }
}
} }
printf("\nThe converted string is\n");
puts(str); if(flag == 1)
getch(); {
return 0; break;
}
} }
if(flag == 1)
{
printf("Word is found in a given
string");
}
else
{
printf("Word is not found in a given
string");
}
getch();
return 0;
}
#include <stdio.h>
#include<conio.h> #include<stdio.h>
#include <string.h> #include<conio.h>
int main() #include<string.h>
{ int main()
char ch, str[50]; {
int i,len,flag = 0; char
printf("Enter the string:"); list[10][20]={"ram","hari","sita","gopal","narayan","an
gets(str); "madhav", "manoj","anish","roshan"};
printf("Enter character: "); int i,j,flag=0;
scanf("%c", &ch); char name[20];
len=strlen(str); printf("Enter the name that you want to search\n");
for (i = 0; i <len; i++) gets(name);
{ for(i=0;i<10;i++)
if (str[i] == ch) {
{ if(strcmp(list[i],name)==0)
flag = 1; {
break; flag=1;
} break;
} }
if (flag==1) }
{ if(flag==1)
printf("character is found in given {
string\n"); printf("Entered name is found");
} }
else else
{ {
printf("Character is not found in given printf("Entered name is not found");
string\n"); }
} getch();
getch(); return 0;
return 0; }
}
Assignment:
P
PR
PRO
PROG
PROGR
PROGRAM
PROGRAMM
PROGRAMMI
PROGRAMMIN
PROGRAMMING
PROGRAMMING
PROGRAMMIN
PROGRAMMI
PROGRAMM
PROGRAM
PROGRA
PROGR
PROG
PRO
PR
P
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[20]="PROGRAMMING";
int i,j,len;
len=strlen(str);
for(i=len;i>=0;i--)
{
for(j=0;j<i;j++)
{
printf("%c",str[j]) ;
}
printf("\n");
}
getch();
return 0;
}
void main()
{
char str[20]={"university"};
char str1[20];
strcpy(str1,"pokhara");
printf("\n%s",str1);
strcat(str1," ");
strcat(str1,str);
printf("\n%s",str1);
strrev(str1);
printf("\n%s",str1);
getch();
}
Output:
pokhara
pokhara university
ytisrevinu arahkop
(Trace the program yourself)
What will be the output after executing the following codes.(assume necessary header files)
void main()
{
char str[]="HELLO WORLD";
for(m=0;str[m]!='\0';m++)
{
if(m%2==0)
printf("%c",str[m]);
}
getch();
}
Output:
HLOWRD
(Trace the program yourself)
14) Without using header file <string.h> perform the following operations.
#include<stdio.h>
#include<conio.h>
#include<math.h>
int square(int);
int main()
{
int num=5,result;
result=pow(num,2);
printf("Square of number using library function =%d",result);
result= square(num);
printf("\nSquare of number using user defined function=%d",result);
}
int square(int x)
{
return (x * x);
}
Note: If a function doesn’t return any value , then its return type is void
Syntax:
void function_name (data_type varibale1,data_type variable2,…..,data_type
variable n)
{
statements ;
………………..
…………………
}
2) Function prototype/ function declaration [PU:2018 fall,PU:2019 fall]
The function declaration or prototype is a model or blueprint of a function. If a function is used
before it is defined in a program, then function declaration or prototype is needed to provide
the following information to the compiler.
The name of function
The type of the value returned by the function
The number and type of arguments that must be supplied while calling the function.
3) Accessing/calling a function
When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main
program.
A function can be called or accessed by specifying its name, followed by a list of arguments
enclosed in parentheses and separated by commas. For example, the function add() with two
arguments is called by add(a,b) to add two numbers.
During function call, function name must match with function prototype name, the type of
return type, the number of arguments and order of arguments.
4) Return statement:
The job of return statement is to hand over some value given by function body to the point
from where the call was made. The function defined with its return type must return a value of
that type. For example: If a function has return type int, it returns an integer value from the
called function to the calling function.
The main functions return statement are:
It immediately transfers the control back to the calling program after execution of
return statement (i.e. no statement within the function body is executed after the
return statement.)
It returns value to the calling function.
The syntax for return is:
return (expression);
Define function, function definition, function calling, function declaration with code
example.[2016 spring]
int main()
{
int a, b,result;
printf("Enter the first number\n");
scanf("%d",&a);
printf("Enter the second number\n");
scanf("%d",&b);
result =sum(a,b);
/*actual arguments a and b are passed in calling function*/
printf ("Sum of two numbers= %d, result);
return 0;
}
The arguments in function can be passed in two ways, namely call by value and call by
reference.
Function call by value (or pass by value)
In this method the value of each actual arguments in the calling function is copied into
corresponding formal arguments of the called function.
With this method the changes made to the formal arguments in the called function have
no effect on the values the actu[al argument in the calling function.
#include<stdio.h>
#include<conio.h>
void swap(int x,int y);
int main()
{
int a,b;
a=10;
b=20;
printf("value before swapping a=%d and b=%d",a,b);
swap(a,b);
printf("\nvalue after swapping a=%d and b=%d",a,b);
getch();
return 0;
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
Output:
Value before swapping a=10 and b=20
Value after swapping a=10 and b=20
In this example, the values of a and b are passed in function swap() by value. The value of a is
copied into formal argument x and value of b is copied into formal argument y. The copy of
value of a and b to x and y means the original values of a and b remain same and these values
are copied into the variables x and y also. Thus when x and y are changed within the function ,
the values of the variables x and y are changed but the original value of a and b remains same.
#include<stdio.h>
#include<conio.h>
void swap(int *x,int *y);
int main()
{
int a,b;
a=10;
b=20;
printf("The value before swapping are a=%d and b=%d",a,b);
swap(&a,&b);
printf("\nThe values after swapping are a=%d and b=%d",a,b);
getch();
return 0;
}
}
Value before swapping a=10 and b=20
Value after swapping a=20 and b=10
Category of functions:
Function can be categorized in four types, on the basis of arguments and return value.
1.Function with no arguments and no return values
2.Function with arguments but no return values
3.Function with no arguments but with return values
4.Function with arguments and return values
1. Function with no arguments and no return values
When a function has no arguments, it does not receive any data from the calling function.
Similarly, when it doesn’t return a value, the calling function does not receive any data from the
called function. Thus in such type of functions, there is no transfer between the calling function
and the called function. This type of function is defined as.
void function_name( )
{
/*body of the function*/
}
The keyword void means the function does not return any value. There is no arguments within
parenthesis which implies function has no argument and it does receive any data from the
called function.
void sum()
{
int x,y,r;
printf("Enter the two numbers\n");
scanf("%d%d",&x,&y);
r=x+y;
printf("The sum of numbers=%d",r);
}
These type of function has arguments and receives the data from the calling function. The
function completes the task and does not return any values to the calling function. Such type of
functions are defined as
void function_name(argument list)
{
/*body of function*/
}
Program to illustrate the “function with arguments but no return values”
#include<stdio.h>
#include<conio.h>
void sum(int,int);
int main()
{
int a,b;
printf("Enter the two numbers\n");
scanf("%d%d",&a,&b);
sum(a,b);
getch();
return 0;
}
}
3. Function with no arguments but with return values
These type of function does not receive any arguments but the function return values to the
calling function. Such type of functions are defined as
return_type function_name( )
{
/*body of function*/
}
Program to illustrate the “function with no arguments and with return values”
#include<stdio.h>
#include<conio.h>
int sum();
int main()
{
int result;
result=sum();
printf("The sum of numbers=%d",result);
getch();
return 0;
}
int sum()
{
int x,y,r;
printf("Enter the two numbers\n");
scanf("%d%d",&x,&y);
r=x+y;
return r;
}
int main()
{
int a,b,result;
printf("Enter the two numbers\n");
scanf("%d%d",&a,&b);
result=sum(a,b);
printf("The sum of numbers=%d",result);
getch();
return 0;
}
Global variables:
Global variables are accessible to all functions defined in the program. Global variables are
declared outside any function, generally at the top of program after preprocessor directives. It
is useful to declare variable global if it is to be used by many functions in the program. The
default initial values for this variable is zero. The lifetime is as long as the program execution
does not come to an end.
Local variables:
The variables that are defined within the body of a function or block and local to that function
or block only are known as local variables. The name and value of local variables are valid
within the function in which it is declared. They are unknown to other. The local variables are
created when the function is called and destroyed automatically when function is exited
function.
Example:
#include<stdio.h>
#include<conio.h>
void fun();
int x=5; //global declaration
int main()
{
int a=10; //local declaration
printf("value of x=%d,a=%d",x,a);
fun();
getch();
return 0;
}
void fun()
{
int b=20; //local declaration
printf("\nvalue of x=%d,b=%d",x,b);
}
Output
Value of x=5, a=10
Value of x=5, b=20
Storage classes in c
What do you mean by storage class? Explain different types of storage classes in C? Use
examples to illustrate.[PU:2014 spring,2014 fall,2016 fall, 2016 spring,2017 spring]
Write a short notes on: storage class in c? [PU: 2017 spring]
In C language, each variable has a storage class which decides the following things:
Scope: where the value of the variable would be available inside a program.
Default initial value: if we do not explicitly initialize that variable, what will be its default
initial value.
Storage location of that variable
Lifetime of that variable: for how long will that variable exist.
Syntax: storage_class_specifier type_specifier variable_name
Example:
#include<stdio.h>
#include<conio.h>
void function1(void);
int main()
{
auto int a=5;
printf("a=%d\n",a);
function1();
getch();
return 0;
}
void function1()
{
auto int b=10;
printf("b=%d",b);
}
Output
a=5
b=10
#include<stdio.h>
#include<conio.h>
int main()
{
register int i;
for (i=0;i<5;i++)
{
printf("%d\t", i);
}
getch();
return 0;
}
Output
0 1 2 3 4
The external or global variables are declared outside any block or function.
Global variable can be accessed by any function in the program.
A static variable tells the compiler to persist/save the variable until the end of program.
Instead of creating and destroying a variable every time when it comes into and goes
out of scope, static variable is initialized only once and remains into existence till the
end of the program.
Preprocessor directives
What is preprocessor directives? [PU: 2015 fall,2019 spring]
Preprocessor is a program that process source code before it passes through the
compiler. It operates under the control of which is known as preprocessor directives.
Preprocessor directives are preceded by a hash (#) sign.
Preprocessor directives are often placed in beginning of program before main function.
No semicolon (;) is expected at the end of the preprocessor directive.
Example:
#include
#define
#ifdef
#undef
#if
#else
#endif
1. File inclusion
Source code of the given “filename” is included in the main program in specified place.
Syntax:
#include<filename>
#include ”filename”
Eg.#include<stdio.h>
2. Conditional compilation
Set of commands are included or excluded in source program before compilation with
respect to condition.
Eg.
#ifdef Returns true if this macro is defined
#ifndef Returns true if this macro is not defined
#if Test if compile time condition is true
#else The alternative for if
#endif Ends preprocessor conditional
3. Macro expansion
Macros are a piece of code in a program which is given some name. Whenever this
name is encountered by the compiler the compiler replaces the name with the actual
piece of code. The ‘#define’ directive is used to define a macro.
Eg. #define PI 3.1415
A macro is a fragment of code which has been given a name. Whenever the name is
used, it is replaced by the contents of the macro. Macro is defined by #define directive.
#define macro_name macro_expansion
macro_name is any valid C identifier, and it is generally in capital letters to
distinguish it from other variables.
macro_expansion can be any text
There are two types of macros:
1) Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to
represent numeric constants.
For example: #define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
Example
#include <stdio.h>
#define PI 3.14
int main()
{
float r,area;
printf("Enter the radius: ");
scanf("%f", &r);
area = PI*r*r;
printf("Area=%.2f",area);
return 0;
}
2) Function-like Macros
The function-like macro looks like function call. For example:
#define max(a,b) ((a)>(b)?(a):(b)) Here, max is the macro name.
#include<stdio.h>
#include<conio.h>
int main()
{
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("STDC :%d\n", __STDC__ );
getch();
return 0;
}
Macro Function
1. Macro is preprocessed. 1. Function is compiled.
2. Before Compilation macro name is 2. During function call , Transfer of
replaced by macro value. Control takes place
3. Macros are faster in execution 3. Functions are bit slower in
than function. execution.
4. Useful where small code appears 4. Useful where large code appears
many time many time
5. Generally Macros do not extend 5. Function can be of any number of
beyond one line lines
6. Increase the program size. 6. Makes program smaller and
compact
Output:
Square of number using macro=25
Square of number using function=25
Header files in C
A header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files. There are two types of header files: the
files that the programmer writes and the files that comes with your compiler.
Including a header file is equal to copying the content of the header file but we do not do it
because it will be error-prone and it is not a good idea to copy the content of a header file in
the source files, especially if we have multiple source files in a program.
Both the user and the system header files are included using the preprocessing directive
#include. It has the following two forms −
#include <file>
This form is used for system header files. It searches for a file named 'file' in a standard list of
system directories.
#include "file"
This form is used for header files of your own program. It searches for a file named 'file' in the
directory containing the current file.
Header files are the special files which stores the predefined library functions. Suppose if we
are using printf() & scanf() functions in your program then we have to include <stdio.h> header
file. It is for standard i/o. If we don't include the the header files we can't run our program.
Therefore we have to include the header files.
Another header file is #include<conio.h> which is for console i/o. This header file stores clrscr()
& getch() functions. clrscr() is for clearing the screen & getch() is holding the screen until we
press any single character from keyboard.
Also we have lots of different header files which stores different functions
Header file function
#include<stdio.h> Used to perform input and output operations in C like scanf() and printf().
#include<string.h> Perform string manipulation operations like strlen and strcpy
#include<conio.h> Perform console input and console output operations like clrscr() to clear the
screen and getch() to get the character from the keyboard.
#include<stdlib.h> Perform standard utility functions like dynamic memory allocation, using
functions such as malloc() and calloc().
#include<math.h> Perform mathematical operations like sqrt() and pow(). To obtain the square
root and the power of a number respectively.
#include<signal.h> Perform signal handling functions like signal() and raise(). To install signal
handler and to raise the signal in the program respectively
#include<errno.h> Used to perform error handling operations like errno().
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int num,result;
printf("Enter the number");
scanf("%d",&num);
result=pow(num,2);
printf("Square of a given number is %d",result);
getch();
return 0;
}
A function that calls itself is known as a recursive function. Recursion is a process by which
function calls itself repeatedly until some specified condition will be satisfied.
To solve a problem using recursive method, two conditions must be satisfied .They are
#include<stdio.h>
#include<conio.h>
long int fact(int n);
int main()
{
int num;
long int f;
printf("Enter the number\n");
scanf("%d",&num);
f=fact(num);
printf("The factorial of a given number is %ld",f);
getch();
return 0;
}
long int fact(int n)
{
if(n==1)
return 1;
else
return n*fact(n-1);
}
Write a program to find the sum of first n natural number using recursive function
[PU: 2018 Fall]
#include<stdio.h>
#include<conio.h>
int snatural(int n);
int main()
{
int num,s;
printf("Enter the value of n \n");
scanf("%d",&num);
s=snatural(num);
printf("The sum of n natrual number is %d",s);
getch();
return 0;
}
Write a program to generate the Fibonacci series upto nth term using recursive function.
Fibonacci series is 0,1,1,2,3,5…. [PU: 2012 fall, 2010 fall, 2006 fall, 2019 fall]
#include<stdio.h>
#include<conio.h>
int fib(int n);
int main()
{
int n,result,i;
printf("Enter how many terms you want to generate");
scanf("%d",&n);
for(i=0;i<n;i++)
{
result=fib(i);
printf("%d\t",result);
}
getch();
return 0;
}
int fib(int n)
{
if (n==0||n==1)
return n;
else
return(fib(n-1) + fib(n-2));
}
#include<stdio.h>
#include<conio.h>
int fib(int n);
int main()
{
int i,result;
for(i=0;i<15;i++)
{
result=fib(i);
printf("%d ",result);
}
getch();
return 0;
}
int fib(int n)
{
if (n==0||n==1)
return n;
else
return(fib(n-1) + fib(n-2));
}
Write a recursive program to generate 10 terms Fibonacci sequence starting from 2.
[PU: 2016 Fall]
#include<stdio.h>
#include<conio.h>
int fib(int n);
int main()
{
int i,result;
for(i=2;i<12;i++)
{
result=fib(i);
printf("%d\t",result);
}
getch();
return 0;
}
Write a program to find nth term of Fibonacci number using recursive function.
[PU: 2010 Fall]
#include<stdio.h>
#include<conio.h>
int fib(int n);
int main()
{
int n,result;
printf("Enter the term:");
scanf("%d",&n);
result=fib(n);
printf("The %d fibonacci term is %d",n,result);
getch();
return 0;
}
int fib(int n)
{
if (n==1)
return 0;
else if(n==2)
return 1;
else
return(fib(n-1) + fib(n-2));
}
#include<stdio.h>
#include<conio.h>
int sum(int n);
int main()
{
int num, result;
printf("Enter the number: ");
scanf("%d", &num);
result = sum(num);
printf("Sum of digits of given number=%d",result);
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<math.h>
int fact(int n);
int main()
{
float sum=0,nume,deno,x;
int n,i,sign;
printf("\nEnter the value of x and n\n");
scanf("%f%d",&x,&n);
for(i=1;i<=n;i++)
{
nume=pow(x,2*i-1);
deno=fact(2*i-1);
sign=pow(-1,i+1);
sum=sum+sign*nume/deno;
}
printf("sum of series=%f",sum);
getch();
return 0;
}
int fact(int n)
{
if(n==1||n==0)
return 1;
else
return (n*fact(n-1));
}
#include<stdio.h>
#include<conio.h>
int count(int n);
int main()
{
int num, result;
printf("Enter the number: ");
scanf("%d", &num);
result = count(num);
printf("Number of digits in a given number=%d",result);
return 0;
}
int count(int n)
{
if (n == 0)
return 0;
else
return (1+ count(n/10));
}
#include<stdio.h>
#include<conio.h>
float power (float x,int n);
int main()
{
float x,result;
int n;
printf("Enter the value of x\n");
scanf("%f",&x);
printf("Enter the value of n\n");
scanf("%d",&n);
result=power(x,n);
printf("Result=%f",result);
getch() ;
return 0;
}
WAP to check whether the given number is Armstrong number or not using recursive
function. (for three digit number)
#include<stdio.h>
#include<conio.h>
int armstrong(int);
int main()
{
int num,a;
printf("Enter any three digit number");
scanf("%d",&num);
a=armstrong(num);
if(a==num)
{
printf("The number is armstrong number");
}
else
{
printf("The number is not armstrong number");
}
Recursion vs Iteration
Recursion Iteration
1. The statement in a body of function 1. Allows the set of instructions to be
calls the function itself. repeatedly executed.
2. Recursion is always applied to 2. Iteration is applied to iteration
functions. statements or "loops".
3. In recursive function, only 3. Iteration includes initialization,
termination condition (base case) is condition, execution of statement
specified within loop and updation
(increments/decrements) the control
variable
4. If the function does not converge to 4. If the control condition in the
some condition called (base case), it iteration statement never become
leads to infinite recursion. false, it leads to infinite iteration
5. The stack is used to store the set of 5. Does not uses stack.
new local variables and parameters
each time the function is called
6. Infinite recursion can crash the 6. Infinite loop uses CPU cycles
system. repeatedly.
7. Slow in execution 7. Fast in execution.
#include<stdio.h>
int a=100,b=200;
int funct1(int c);
main()
{
int count,c;
for(count=1;count<=10;++count)
{
c=4*count;
printf("%d\n",funct1(c));
}
}
funct1(int x)
{
int c;
c=(x<30)?(a-x):(b+x);
return (c);
}
Here a=100,b=200 Where a and b are global variables.so that they can accessed from
anywhere.
count c=4*count funct1(c) c=(x<30)?(a-x) : (b+x) print c
1 c=4*1=4 funct1(4) (4<30)?(True) 96
c=a-x=100-4=96
2 c=4*2=8 funct1(8) (8<30)?(True) 92
c=100-8=92
3 c=4*3=12 funct1(12) (12<30)?True 88
c=100-12=88
4 c=4*4=16 funct1(16) (16<30)?True 84
c=100-16=84
5 c=4*5=20 funct1(20) (20<30)? True 80
c=100-20=80
6 c=4*6=24 funct1(24) (24<30)?True 76
c=100-24=76
7 c=4*7=28 funct1(28) (28<30)?True 72
c=100-28=72
8 c=4*8=32 funct1(32) (32<30)?False 232
c=b+x=200+32=232
9 c=4*9=36 funct1(36) (36<30)?False 236
c=b+x=200+36=236
10 c=4*10=40 funct1(40) (40<30)?False 240
c=b+x=200+40=240
#include<stdio.h>
#include<conio.h>
void func1(int n);
main()
{
int i;
clrscr();
for(i=1;i<=4;i++)
{
func1(i);
}
getch();
}
void func1(int n)
{
int num=3;
printf("%d\n\n",n*num);
}
Output:
12
#include<stdio.h>
#include<conio.h>
float area(float r);
int main()
{
float r1,r2,a1,a2;
printf("Enter the radious of first circle");
scanf("%f",&r1);
a1=area(r1);
printf("Enter the radious of second circle");
scanf("%f",&r2) ;
a2=area(r2);
printf("Area of first circle=%f",a1);
printf("\nArea of second circle=%f",a2);
getch();
}
float area(float r)
{
float a;
a=3.14*r*r;
return a;
}
2. Calculate the sum of n natural numbers using function.
#include<stdio.h>
#include<conio.h>
int snatural(int n);
int main()
{
int num,s;
printf("Enter the value of n\n");
scanf("%d",&num);
s=snatural(num);
printf("Sum of n natural number is %d",s);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
void area(int,int);
void perimeter(int,int);
int main()
{
int l,b;
printf("Enter the length and breadth of rectangle\n");
scanf("%d%d",&l,&b);
area(l,b);
perimeter(l,b);
getch();
return 0;
}
void area(int x,int y)
{
int area;
area=x*y;
printf("area=%d",area);
}
#include<stdio.h>
#include<conio.h>
int max(int,int,int);
int main()
{
int a,b,c,result;
printf("Enter the three numbers\n");
scanf("%d%d%d",&a,&b,&c);
result=max(a,b,c);
printf("Maximum number=%d",result);
getch();
return 0;
}
5. WAP to check the given number is prime or not using user defined function.
[PU:2019 spring]
#include<stdio.h>
#include<conio.h>
void prime(int n);
int main()
{
int num;
printf("Enter the number you want to check\n");
scanf("%d",&num);
prime(num);
getch();
return 0;
}
if(i==n)
{
printf("Number is prime");
}
}
#include<stdio.h>
#include<conio.h>
void palindrome(int n);
int main()
{
int num;
printf("Enter the number you want to check\n");
scanf("%d",&num);
palindrome(num);
getch();
return 0;
}
if(a==rev)
{
printf("Number is palindrome");
}
else
{
printf("Number is not palindrome");
}
}
7. By using function WAP to generate the Fibonacci series upto nth term when initial
value is given by user.
#include<stdio.h>
#include<conio.h>
void fibo(int n,int x,int y);
int main()
{
int a,b,num;
printf("Enter the number of terms you want to generate\n");
scanf("%d",&num);
printf("Enter the two inital values\n");
scanf("%d%d",&a,&b);
fibo(num,a,b);
getch();
return 0;
}
void display(int x)
{
printf("%d\t",x);
}
Write a program to pass one dimensional array to a function and display that array in that
called function.[PU:2019 fall]
Program to illustrate passing an entire array to a function
#include<stdio.h>
#include<conio.h>
void display(int x[],int n);
int main()
{
int i;
int a[5]={5,10,15,20,25};
display(a,5);
getch();
return 0;
}
void display(int x[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d\t",x[i]);
}
}
3) Write a program to find the sum of all prime numbers in a given array. The main
function of your program should take the help of user-defined function that tests
whether a given number is prime or not.[PU -2013 Fall]
#include<stdio.h>
#include<conio.h>
int checkprime(int n);
int main()
{
int a[50],n,i,sum=0,result;
printf("Enter the no. of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nprime numbers are:\n");
for(i=0;i<n;i++)
{
result=checkprime(a[i]);
if(result==1)
{
printf("%d\t",a[i]);
sum=sum+a[i];
}
}
printf("\nThe sum of prime no. is %d",sum);
getch();
}
Practice Questions:
1) Write a program to input n numbers in an array and count number of odd and even
numbers and find their sum using function.
2) WAP to input n number in an array and print in reverse order using function.
3) WAP to input n numbers in an array and check if given number is present or not using
function.
#include<stdio.h>
#include<conio.h>
void input(int a[][20],int x,int y);
void disp(int d[][20],int m,int n);
void addition(int a1[][20],int a2[][20],int p,int q);
int i,j;
int main()
{
int matrix1[20][20],matrix2[20][20],r,c;
printf("Enter the row and column size of matrix\n");
scanf("%d%d",&r,&c);
printf("Enter the first matrix");
input(matrix1,r,c);
printf("Enter the second matrix");
input(matrix2,r,c);
printf("The first matrix is\n");
disp(matrix1,r,c);
printf("The second matrix is\n");
disp(matrix2,r,c);
addition(matrix1,matrix2,r,c);
getch();
return 0;
}
void input(int a[][20],int x,int y)
{
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
scanf("%d",&a[i][j]);
}
}
}
Practice Questions.
1. WAP to input m*n order matrix and count even number of elements present in matrix
and find their sum using function.
2. WAP to input m*n matrix and find highest and lowest element using function.
3. WAP to input m*n order matrix and find highest and lowest element using function.
Here ptr is a pointer variable that only contains the address of integer data type.
Pointer declaration
Pointer variable is declared with an asterisk (*) operator before a variable name. This operator
is called pointer/indirection or dereference operator.
Syntax: data_type *pointer_variable_name;
Data type of the pointer must be same as the data type of the variable to which the pointer
variable is pointing.
eg. int *ptr;
Declares the variable ptr which is a pointer variable that points to an integer data type.
Similarly the statement
float *x;
Declares the variable x which is a pointer variable that points to an float data type.
Void pointer
Write a short notes on: Void pointer [PU: 2018 spring, 2016 Fall]
Void pointer is a special type of pointer that can point any data type (int or float or char or
double).Using void pointer, the pointed data cannot be dereferenced (cannot accessed the
value at the address stored in pointer variable).so that reason we will always have to change
type of void pointer to some other pointer type that points to a concrete data type before
dereferencing it This is done by performing type-casting.
Declaration:
void *pointer_name;
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10;
float b=4.5;
void *ptr;
ptr=&a;
printf("a=%d",*(int*)ptr);
ptr=&b;
printf("b=%f",*(float*)ptr);
getch();
return 0;
}
Output:
a=10
b=4.500000
Pointer Arithmetic
Write a short notes on: Pointer Arithmetic. [PU: 2016 spring]
As a pointer holds the memory address of variable, some arithmetic operations can be
performed with pointers. They are as follows.
Increment
Decrement
Addition
Subtraction
If arithmetic operations done values will be incremented or decremented as per data type
chosen. Let ptr=&arr[0]=1000 i.e Base address of array.
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[5] = {10,20,30,40,50};
int *ptr1,*ptr2;
ptr1=&arr[0];
ptr1=ptr1+4;
printf("\nvalue %d has address %u",*ptr1,ptr1); //points to 5th element
ptr2=&arr[4];
ptr2=ptr2-4 ;
printf("\nvalue %d has address %u",*ptr2,ptr2); //points to 1st element
getch();
return 0;
}
3) One pointer variable can be subtracted from another provided that both
variables points to the element of same array.
int main()
{
int arr[5]={1,2,3,4,5};
int *ptr1,*ptr2;
ptr1=arr;
ptr2=&arr[4];
printf("Difference of two pointer =%d",ptr2-ptr1);
return 0;
}
int main()
{
int arr[5]={1,2,3,4,5};
int *ptr1,*ptr2;
ptr1=&arr[0];
ptr2=&arr[4];
if(ptr2>ptr1)
printf("ptr2 is far from ptr1");
else
printf("ptr1 is far from ptr2");
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
int num=15;
int *ptr1;
int **ptr2;
ptr1=#
ptr2=&ptr1;
printf("num=%d\n",*ptr1);
printf("num=%d",**ptr2);
getch();
return 0;
}
Output
num= 15
num= 15
Program to convert uppercase letter into lower and vice versa passing pointer to function
#include<stdio.h>
#include<conio.h>
void conversion(char *);
int main()
{
char ch;
printf("Enter the character\n");
scanf("%c",&ch);
conversion(&ch);
printf("The corresponding character is:%c",ch);
getch();
return 0;
}
Address of variable can be passes to the function so that changes to value of arguments
in calling function can be easily reflected in called function.
In general function cannot return more than one values, But it can be possible using
concept of pointers.
Arrays and structures can be passes to the function efficiently.
It is possible to pass a portion of an array rather than an entire array to a function using
pointer.
The use of pointer as a function arguments permits the corresponding data items to be
altered globally from within the function.
Write a program with user defined function using pointer to convert all the upper case to lower
case and vice-versa in string given by the user. [PU-2012 Fall]
#include<stdio.h>
#include<conio.h>
void conversion(char *s);
int main( )
{
char str[50];
printf("Enter the string\n");
gets(str);
conversion(str);
printf("String after conversion");
puts(str);
getch();
return 0;
}
void conversion(char *s)
{
int i;
for(i=0; *(s+i) != '\0';i++)
{
if(*(s+i)>='a'&&*(s+i)<='z')
{
*(s+i)=*(s+i)-32;
}
else if(*(s+i)>='A'&&*(s+i)<='Z')
{
*(s+i)=*(s+i)+32;
}
}
}
#include<stdio.h>
#include<conio.h>
void areaperi(int r,float *area,float *peri);
int main()
{
int rad;
float a,p;
printf("Enter the radious\n");
scanf("%d",&rad);
areaperi(rad,&a,&p);
printf("Area of circle=%f",a);
printf("Perimeter of circle=%f",p);
getch();
return 0;
}
void areaperi(int r,float *area,float *peri)
{
*area=3.14*r*r;
*peri=2*3.14*r;
}
Compiler allocates the sufficient amount of memory to contain all the elements of array
in contiguous memory location.
Base address ie. address of the first element of the array is allocated by the compiler.
Suppose, we declare an array arr.
int arr[5]={5,10,15,20,25};
Assuming that base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows.
Here variable arr holds the address of the first element of the array.ie. Points at the starting
memory of address.
So, arr contains the address of arr[0] ie.1000
If we want to declare ptr as integer pointer then we can make the pointer ptr to point the array
arr by following assignment.
int *ptr;
ptr=arr; OR ptr=&arr[0];
Thus
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
int arr[5]={1,2,3,4,5};
int *ptr=arr;
for(i=0;i<5;i++)
{
printf("\nArray element=%d and Memory location=%u",*(ptr+i), (ptr+i));
}
getch();
return 0;
}
WAP to input n number in array and display it using pointer.
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[100],i,n,*ptr;
ptr=arr;
printf("Enter the number of elements you want to enter");
scanf("%d",&n);
printf("\nEnter %d elements",n);
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
printf("Entered elements are\n");
for(i=0;i<n;i++)
{
printf("%d",*(ptr+i));
}
getch();
return 0;
}
WAP to input 5 number in array and display it using pointer. (Do yourself)
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[100],n,i,*ptr,sum=0;
ptr=arr;
printf("Enter number of elements you want to enter");
scanf("%d",&n);
printf("Enter %d elements",n) ;
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
for(i=0;i<n;i++)
{
sum=sum+*(ptr+i);
}
printf("The sum of all elements is %d",sum);
getch();
return 0;
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[100],n,i,j,temp,*ptr;
ptr=arr;
printf("Enter number of elements you want to enter");
scanf("%d",&n);
printf("Enter %d elements",n) ;
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(*(ptr+j)>*((ptr+j)+1))
{
temp=*(ptr+j);
*(ptr+j)=*((ptr+j)+1);
*((ptr+j)+1)=temp;
}
}
}
printf("\nThe sorted array are");
for(i=0;i<n;i++)
{
printf("\n%d",*(ptr+i));
}
getch();
return 0;
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[100],i,n,*ptr;
ptr=arr;
printf("Enter number of elements you want to enter");
scanf("%d",&n);
printf("Enter %d elements",n) ;
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[100],n,i,*ptr,esum=0,ecount=0,osum=0,ocount=0;
ptr=arr;
printf("Enter number of elements you want to enter");
scanf("%d",&n);
printf("Enter %d elements",n) ;
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
for(i=0;i<n;i++)
{
if(*(ptr+i)%2==0)
{
esum=esum+*(ptr+i);
ecount++;
}
else
{
osum=osum+*(ptr+i) ;
ocount++;
}
}
printf("sum of even elements=%d and number of even elements=%d",esum,ecount);
printf("\nsum of odd elements=%d and number of odd elements=%d",osum,ocount);
getch();
return 0;
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[100],n,i,*ptr,num,flag=0;
ptr=arr;
printf("Enter number of elements you want to enter");
scanf("%d",&n);
printf("Enter %d elements",n) ;
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
printf("Enter a number you want to search");
scanf("%d",&num);
for(i=0;i<n;i++)
{
if(*(ptr+i)==num)
{
flag=1;
break;
}
}
if(flag==1)
{
printf("Your number is found");
}
else
{
printf("Your number is not found");
}
getch();
return 0;
Since memory in computer is organized linearly it is not possible to store the 2-D array in rows
and columns. The concept of rows and columns is only theoretical, actually a 2-D array is stored
in row major order i.e rows are placed next to each other. The following figure shows how the
above 2-D array will be stored in memory.
Each row of the 2-D array treated as a 1-D array, so a two-dimensional array can be considered
as a collection of one-dimensional arrays that are placed one after another.
So here arr is an array is an array of 3 elements where each element is a 1-D array of 4 integers.
&arr[0][0]=*(ptr+0)+0=*ptr arr[0][0]=*(*(ptr+0)+0)=**ptr
&arr[0][1]=*ptr+1 arr[0][1]=*(*(ptr+0)+1)=*(*ptr+1))
&arr[1][1]=*(ptr+1)+1 arr[1][1]= *(*(ptr+1)+1)
&arr[2][3]=*(ptr+2)+3 arr[2][3]=*(*(ptr+2)+3)
Note: As array name holds the base address (i.e. address of first element of array).Then, if arr is
a 2D array we can access any element arr[i][j] of the array using the pointer expression.
*(*(arr+i)+j)
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[2][3] ={{11,12,13},{14,15,16}};
int i, j;
printf("Contents of array are\n");
for(i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
{
printf("\narr[%d][%d]=%d", i, j, *( *(arr + i) + j) );
}
printf("\n");
}
getch();
return 0;
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sum=sum+*(*(arr+i)+j);
}
}
printf("sum of matrix is %d",sum);
getch();
return 0;
}
Array of pointers
Array of pointers is a collection of address.
The address present in the array of pointers can be address of variable or address of
array element.
Array of pointers can be declared as:
datatype *pointer_name[size];
eg.int *ptr[4];
This statement declares an array of 4 pointers, each of which points to an integer value. The
first pointer is called ptr[0] ,the second is ptr[1] ,third is ptr[2] and fourth is ptr[3].
As the string is an array of characters, the name of string variable is pointer to the first
character of the string and can be used to access and manipulate the characters.
eg.
char str[6] = "Hello";
char *ptr = str; // assigning the address of the string str to the pointer ptr.
Here, the variable name of the string str holds the address of the first element of the array i.e.,
it points at the starting memory address.
We can represent the character pointer variable ptr as follows.
The pointer variable ptr is allocated memory address 8000 and it holds the base address of the
string variable str i.e., 1000.
5. An array can store the number of 5. A pointer variable can store the address of
elements, mentioned in the size of array only one variable at a time.
variable
1) malloc()
The malloc() function reserves a block of memory of specified size and returns a
pointer of type void, which can be casted into pointer of any form.
The memory allocation can fail if the space in heap is not sufficient to satisfy the
request. If it fails it returns NULL.
Syntax:
ptr =(cast-type*)malloc(byte-size);
ptr is pointer of type cast-type.
eg.
int *ptr;
ptr=(int*)malloc(100*sizeof(int));
A memory space equivalent to “100 times the size of integer” is reserved and address of
the first memory allocated is assigned to pointer ptr of type int.
3) realloc()
This function is used to modify the size of previously allocated space.
Syntax:
ptr=realloc(ptr,newsize);//Reallocation of space
Sometimes previously allocated space is not sufficient we need to additional space and
sometimes allocated memory is much larger than necessary. In both situation, we can
change the memory size already allocated with the help of function realloc()
This function allocates the new memory space of size newsize to the pointer variable ptr and
returns a pointer to the first byte of new memory.
4) free()
It releases the previously allocated space by malloc(), calloc(), and the realloc() function.
Its syntax is
free(ptr);
The memory dynamically allocated is not returned to the system until the programmer
returns the memory explicitly. This can be done by using free() fuction. This function is used
to release the space when it is not required.
Where ptr is a pointer to memory block which has already been created by malloc(),calloc()
or realloc() function.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int *ptr;
int i,n;
printf("Enter number of elements to be entered\n");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter %d numbers\n",n);
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
printf("The elments are\n");
for(i=0;i<n;i++)
{
printf("\n%d",*(ptr+i));
}
free(ptr);
getch();
return 0;
}
Hint:
ptr=(int*)malloc(n*sizeof(int));
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int)*2);
int i;
int *ptrnew;
*ptr = 10;
*(ptr + 1) = 20;
ptrnew = (int *)realloc(ptr, sizeof(int)*3);
*(ptrnew + 2) = 30;
for(i = 0; i < 3; i++)
{
printf("%d\t ", *(ptrnew + i));
}
getch();
return 0;
}
Output:
10 20 30
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int *ptr;
int i,n,sum=0;
printf("Enter number of elements to be entered\n");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
Write a program to find the sum of 5 numbers supplied by users using DMA. [PU: 2016 Fall]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int *ptr;
int i,n,sum=0;
ptr=(int*)calloc(5,sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter 5 numbers\n",n);
for(i=0;i<5;i++)
{
scanf("%d",(ptr+i));
}
for(i=0;i<5;i++)
{
sum=sum+*(ptr+i);
}
printf("The sum of 5 numbers is %d",sum);
free(ptr);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int *ptr;
int i,j,temp,n;
printf("Enter number of elements to be entered\n");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter %d numbers\n",n);
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
printf("The array before sorting are\n");
for(i=0;i<n;i++)
{
printf("\n%d",*(ptr+i));
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(*(ptr+j)>*((ptr+j)+1))
{
temp=*(ptr+j);
*(ptr+j)=*((ptr+j)+1);
*((ptr+j)+1)=temp;
}
}
}
Write a program to read ‘n’ numbers dynamically and sort it in descending order.
Hint:
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(*(ptr+j)<*((ptr+j)+1))
{
temp=*(ptr+j);
*(ptr+j)=*((ptr+j)+1);
*((ptr+j)+1)=temp;
}
}
}
Write a program to print reverse element of an array using dynamic memory allocation.
[2013 fall]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int *ptr;
int i,n;
printf("Enter number of elements to be entered\n");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int *ptr;
int i,n,large,small;
printf("Enter number of elements to be entered\n");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter %d numbers\n",n);
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
large=*ptr;
small=*ptr;
for(i=0;i<n;i++)
{
if(large<*(ptr+i))
large=*(ptr+i);
if(small>*(ptr+i))
small=*(ptr+i);
}
printf("largest element =%d",large);
printf("smallest element =%d",small);
free(ptr);
getch();
return 0;
}
Assignment:
Write a program to input n numbers in an array and find the sum of all even and odd
numbers and count them using DMA.
WAP to check if any given number is present in an array or not using DMA.
Write a program to find highest number in an array using dynamic memory allocation and
function.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i;
void display(int *p,int m);
void largest(int *ptr,int y);
In static memory allocation the memory is allocated before the execution of program
begins (During compilation).In this type of allocation the memory cannot be resized
after initial allocation. So it has some limitations. Like
Wastage of memory
Overflow of memory
eg. int arr[100];
Here, the size of an array has been fixed to 100.If we just enter to 10 elements only,
then their will be wastage of 90 memory location and if we need to store more than 100
elements there will be memory overflow.
Assignment
Why dynamic memory allocation is needed?
How dynamic memory allocation is better than static memory allocation?
Write a short notes on: Dynamic memory management [PU: 2017 fall]
This statement allocates contiguous space in memory for 25 elements each with size of
int.
Malloc Calloc
1. malloc() allocates memory block of 1. calloc() allocates a region of memory
given size (in bytes) large enough to hold "n elements" of
"size" bytes each.
2. malloc() doesn’t initialize the 2. The allocated region is initialized to
allocated memory. zero.
3. It takes one argument and allocates 3. The calloc() function takes two
the memory in bytes given in arguments number of variables to be
argument. allocated and size of each variable.
4. Syntax: 4. Syntax:
ptr=(cast-type*)malloc(byte-size); ptr=(cast-type*)calloc(n,element-size);
5. eg. 5. eg.
int *ptr; int *ptr;
ptr=(int*)malloc(100*sizeof(int)); ptr=(int*) calloc(25,sizeof(int));
A memory space equivalent to “100 This statement allocates contiguous
times the size of integer” is reserved space in memory for 25 elements
each with size of int.
Below are the different definitions of the function search() [PU:2013 spring]
i) void search(int *m[],int x)
{
}
ii) void search(int *m,int x)
{
}
Are they equivalent? Explain.
In function definition,
void search(int *m ,int x)
{
}
Here, pointer is used as an function argument, which has been used to accept the
address of integer type element. Here, we can pass address of one element at a
time. In case of array beginning address of array is passed.
void main()
{
int m[2];
int *p=m;
m[0]=100;
m[1]=200;
printf(“%d%d”,++*p,*p);
}
Solution:
Tracing the program logi ,by assuming 1000 is an starting address of an array
*p=*p/2+13;
}
(Trace the program yourself)
Output:
4
15
Output:
x=26
y=26
z=26
5) Trace the output of the following program.
void main()
{
int arr[]={10,20,30,45,67,58,74}
int *i,*j;
i=&arr[1];
j=&arr[5];
printf("%d\n%d",j-i,*j-*i);
}
(Trace the program yourself)
Output
4
38
#include<stdio.h>
#include<conio.h>
int main()
{
float a[5]={13.24,1.5,1.5,5.4,3.5};
float *j,*k;
j=&a[0];
j=j+4;
k=&a[2];
printf("\n%.2f\n%.2f\n%.2f\n%d",*j,*k,*j-*k,j-k);
getch();
}
(Trace the program yourself)
Output:
3.50
1.50
2.00
2
void main()
{
float f[]={10.5,1.5,2.5,3.5,4.5};
float *p,*q;
p=f;
p=p+4;
q=&f[2];
printf("%f\t%f\t%f",*p,*q,*p-*q);
getch();
}
(Trace the program yourself)
Output:
4.50000 2.500000 2.000000
struct student
{
char name[20];
char address[20];
int class;
int rollno;
int age;
}
Now multiple variable of struct student type can be declared as:
int main()
{
struct student st1, st2,st3. . . . stn;
...........................
return 0;
}
Declaration of structure
Method I
Syntax:
struct structure_name Example
{ struct student
datatype member1; {
datatype member2; char name[20];
................... int roll;
datatype memebern; float marks;
}; };
int main() int main()
{ {
struct structure_name variable1, struct student st1, st2, st3;
variable2,……..variable n; }
.........................
return 0;
}
Structure initialization
Structure variable can be also initialized at compile time. The values to be initialized must
appear in order as in the definition of structure within braces and separated by commas.
Syntax:
struct structure_name structure_variable={value1,value2, . . . . . . ., value n };
where value1 is initialized to the first member, value2 is initialized to second member and so
on.
For example:
If the structure is declared as
struct student
{
char name[20];
int rollno;
float marks;
}
The variable of this type can be initialized during its declaration as shown below.
struct student st={“Ram”,100,56.5};
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int roll;
float marks;
};
int main()
{
struct student st={"Ram",15,85.5};
printf("Name of student is %s",st.name);
printf("\nRoll number= %d",st.roll);
printf("\nMarks obtained=%f",st.marks);
getch();
return 0;
}
Initialization of structure at runtime
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int roll;
float marks;
};
int main()
{
struct student st;
printf("Enter the name of student");
gets(st.name);
printf("Enter the Roll number of student");
scanf("%d",&st.roll);
printf("Enter the marks of student");
scanf("%f",&st.marks);
printf("Name of student is");
puts(st.name);
printf("Roll number= %d",st.roll);
printf("Marks obtained=%f",st.marks);
getch();
return 0;
}
structure employee
{
char name[50];
int id;
struct date dob;
float salary;
}e;
#include<stdio.h>
#include<conio.h>
struct date
{
int day;
int month;
int year;
};
struct employee
{
char name[20];
int id;
struct date dob;
float salary;
}e;
int main()
{
printf("Enter the name of employee");
scanf("%s",e.name);
printf("Enter ID of employee");
scanf("%d",&e.id);
printf("Enter the year of birthday\n");
scanf("%d",&e.dob.year);
printf("Enter the month of birthday\n");
scanf("%d",&e.dob.month);
printf("Enter the day of birthday\n");
scanf("%d",&e.dob.day);
printf("Enter the salary of employee\n");
scanf("%f",&e.salary);
printf("Detail information of employee is\n");
printf("Name\tId\tDate\tMonth\tYear\tsalary\n");
printf("%s\t%d\t%d\t%d\t%d\t%f",e.name,e.id,e.dob.day,e.dob.month,e.dob.year,e.salary);
getch();
return 0;
}
In above example,
The member within date are accessed as
e.dob.day;
e.dob.month;
e.dob.year;
Array of structure
Array of structure is the collection of multiple structures variables where each variables contain
information about different entities.
struct employee
{
char name[20];
int id;
float salary;
};
Normally, when we want to store the record of multiple employee ,Let’s suppose 10 ,we have
to declare 10 different structure variables such as e1,e2,e3……. e9, e10.
By using array of structure we can simply declared in following ways;
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[20];
int id;
float salary;
};
int main()
{
int i;
struct employee e[10];
printf("Enter the Information of 10 employee\n");
for(i=0;i<10;i++)
{
printf("Enter the Employee id\n");
scanf("%d",&e[i].id);
printf("Enter the name of employee\n");
gets(e[i].name);
printf("Enter the salary of employee\n");
scanf("%f",&e[i].salary);
}
printf("\nEmployee Information List:");
for(i=0;i<10;i++)
{
printf(" \nId:%d\tName:%s\tsalary:%f",e[i].id,e[i].name,e[i].salary);
}
getch();
return 0;
}
struct employee
{
char name[20];
int id;
float salary;
};
int main()
{
struct employee e[5];
}
Structure array initialization follows same syntax as we initialize single structure variable. The
only difference is here we can initialize more than one structure variable at a time.
struct employee e[5] =
{
{ "Ramesh", 12,15000.35},
{ "Hari", 15, 25000.5 },
{ "Gopal", 17, 30000.25 },
{ "Sita", 2, 45000.56 },
{ "Roshan", 9, 32000.25}
};
Output
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[50];
float salary;
};
void display(struct employee *e);
void addbonus(struct employee *ee);
int main()
{
struct employee emp;
printf("Enter the name of employee");
scanf("%s",emp.name);
printf("Enter the salary of employee");
scanf("%f",&emp.salary);
addbonus(&emp);
display(&emp);
getch();
}
Here the structure node is referencing to self as it has a pointer of its own type ‘struct node’,
named ‘next’.
Such self-referential structures are very useful in applications that involve linked data
structures, such as lists and trees.
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node a,b,c;
a.data=10;
b.data=20;
c.data=30;
a.next=&b;
b.next=&c;
c.next=NULL;
printf("a=%d",a.data);
printf("\nb=%d",a.next->data);
printf("\nc=%d",b.next->data);
getch();
return 0;
}
Union
Union is a derived data type which allows to store number of variables of different data types in
same memory location.
Unions are similar to structure but there is only difference in terms of storage. In structures,
each member has its own memory location but all member of the union use the same storage
location. Due to sharing of a common memory location, all the members of union cannot
accessed at a time.
The memory occupied by the union will be the memory sized occupied by a member which
requires largest memory space among members.
Eg.
union student
{
char name[20];
int roll;
float marks;
};
Here, memory required for member name is 20 bytes, roll is 2 bytes and marks is 4 bytes. Here,
largest memory space (ie.20 bytes) will be allocated for union.
Declaration of union
Method I
Syntax: Example:
union union_name union student
{ {
datatype member1; char name[20];
datatype member2; int roll;
…………………………….. float marks;
datatype memebern; };
}; int main()
int main() {
{ union student st1, st2, st3;
union union_name variable1, }
variable2,……..variable n;
}
Example:
#include<stdio.h>
#include<conio.h>
union student
{
char name[20];
int roll;
float marks;
};
int main()
{
union student st;
printf("Enter the Name");
scanf("%s",st.name);
printf("Name is:%s",st.name);
printf("Enter the Rollno");
scanf("%d",&st.roll);
printf("Rollno is %d",st.roll);
printf("Enter the marks");
scanf("%f",&st.marks);
printf("Marks is %f",st.marks);
getch();
return 0;
}
#include<stdio.h> #include<stdio.h>
struct student union student
{ {
int roll; int roll;
float marks; float marks;
}; };
int main() int main()
{ {
struct student st; union student st;
st.roll=15; st.roll=15;
st.marks=67.5; st.marks=67.5;
printf("Roll= %d",st.roll); printf("Roll=%d",st.roll);
printf("\nMarks=%f",st.marks); printf("\nMarks=%f",st.marks);
return 0; return 0;
} }
Output: Output:
Roll=15 Roll=(Garbage value)
Marks=67.5 Marks=67.5
Description: Description:
Here the memory reserved for structure will Here the memory reserved for union will be 4
be (2 bytes+4 bytes=6 bytes) bytes because data type of marks is float
2 bytes is reserved for integer roll and 4 which is the largest member of union.
bytes is reserved for float marks But, all members cannot be used at the same
As well all members can be used at the same time because all members in union share the
time. common memory location.
Structure Union
Keyword struct is used. Keyword union is used.
Syntax Syntax:
struct structure_name union union_name
{ {
datatype member1; datatype member1;
datatype member2; datatype member2;
............... .. .................
datatype membern; datatype membern;
}; };
The separate memory location is allocated to All members of the union share the same
each member of the structure. memory location.
All the members of structure can be accessed Only one members of union can be accessed
at a time. at a time.
Size of the structure is equal to the sum of Size of the union is equal to the size of the
size of the each member. largest member.
Eg. Eg.
struct employee struct union
{ {
char name[20]; char name[20];
int age; int age;
float salary; float salary;
}; };
Memory reserved=(20+2+4)=24 bytes Memory reserved=20 bytes
Hint:
Hint:
float high;
...............
. . . . . . . . . . . .. . . .
high=e[0].salary;
for(i=0;i<n;i++)
{
if(e[i].salary>high)
{
high=e[i].salary;
}
}
printf("\nInformation of employee who have highest salary are\n");
printf("\nName\tAddress\tSalary\tAge");
for(i=0;i<n;i++)
{
if(e[i].salary==high)
{
printf("\n%s\t%s\t%f\t%d",e[i].name,e[i].address,e[i].salary,e[i].age);
}
}
1) Create a structure called customer having name, address, account number and balance.
Input n records and
Display information of customer whose balance is greater than 10000
Ask for account number from customer and display their information
[Note: Data type for accountno will be long int and format specifier %ld ]
2) Create a structure called employee having name, address, post salary and age. Input n
records of employee and display information of those employee whose post is
accountant.
3) Create a structure called university having name, college, and number of faculties.
Input n records of college and display the name of those colleges whose address is
Kathmandu.
4) Create a structure to specify students data rollno,name,address,marks1,mark2,mark3 to
read 20 students data into array of structures and print the information of those
students who are failed.
(Note: Pass mark for any subject is 45)
1) Create a structure for the following data.
Write a program to input 100 students and Display the records of student of “computer”
faculty.[PU:2013 fall]
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct dob
{
int dd;
int mm;
int yy;
};
struct student
{
int roll;
char name[20];
char address[20];
char faculty[20];
struct dob d;
};
#include<stdio.h>
#include<conio.h>
struct date
{
int dd;
int mm;
int yy;
};
struct book
{
char name[20];
float price;
char author[20];
struct date d;
};
int main()
{
int i;
struct book b[100];
for(i=0;i<100;i++)
{
printf("Enter the information of book %d\n",i+1);
printf("Enter the book name");
gets(b[i].name);
printf("Enter the author name");
gets(b[i].author);
printf("Enter the book price");
scanf("%f",&b[i].price);
printf("Enter book published year");
scanf("%d",&b[i].d.yy);
printf("Enter book published month");
scanf("%d",&b[i].d.mm);
printf("Enter book published date");
scanf("%d",&b[i].d.dd);
}
Write a program to input data of 100 employee and display the record of those employees
living in pokhara.
[Note: datatype for telephone must be long int and format specifier is %ld ]
[PU: 2013 spring]
Create a structure for the following data.
Also write a program to input 100 employee records and display whose Department is “sales”.
[PU:2019 spring]
Using football, declare an array player with 50 elements and write a program to read the
information about all the information about all the 50 players and print a country wise list
containing names of players with their number of goal scored. [PU: 2014 fall]
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define N 50
struct football
{
char name[20];
char country[20];
int goal;
};
int main()
{
struct football p[50],temp;
int i, j;
for (i = 0; i < N; i++)
{
printf("Enter the infomation of player %d\n",i+1);
printf("Enter player name");
gets(p[i].name);
printf("Enter player country");
gets(p[i].country);
printf("Enter Number of goal scored : ");
scanf("%d", &p[i].goal);
}
Assignment:
Define a structure called cricket that will describe the following information:
player name,
team name,
batting average.
Using cricket, declare an array player with 50 elements and write a program to read the
information about all the 50 players and print a team-wise list containing names of player with
their batting average.
In a bank there are n customers with attributes name, account no and balance. WAP to find out
information of customer who has highest balance in bank. [PU: 2006 spring]
#include<stdio.h>
#include<conio.h>
struct customer
{
char name[20];
long int accno;
float balance;
};
Assignment:
Write a C program to accept details of 'n' employee (eno, ename, salary) and display the details
of employee having highest salary. Use array of structure.
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
float sub1,sub2,sub3;
float avg;
};
int main()
{
int i;
struct student st[100];
printf("Enter the information of 100 students\n");
for(i=0;i<100;i++)
{
printf("Enter Name");
gets(st[i].name);
printf("Enter Rollno");
scanf("%d",&st[i].rollno);
printf("Enter marks of sub1");
scanf("%f",&st[i].sub1);
printf("Enter marks of sub2");
scanf("%f",&st[i].sub2);
printf("Enter marks of sub3");
scanf("%f",&st[i].sub3);
st[i].avg=(st[i].sub1+st[i].sub2+st[i].sub3)/3;
}
printf("Name of student with average marks greater than 80\n");
for(i=0;i<100;i++)
{
if(st[i].avg>80)
{
puts(st[i].name);
}
}
getch();
return 0;
}
Naming a file
Opening a file
Reading data from file
Writing data to file and
Closing the file
for example:
fclose(fptr1);
fclose(fptr2);
File Pointer
What is the significance of file pointer in file handling? [PU: 2018 spring, 2014 spring]
A file pointer is a pointer to a structure, which contains information about the file, including its
name, current position of the file, whether the file is being read or written, and whether errors or
end of the file have occurred. The user does not need to know the details, because the definitions
obtained from stdio.h include a structure declaration called FILE. The only declaration needed for a file
pointer is symbolized by
FILE *fptr;
This says that fptr is the file pointer that points to a FILE structure.
“w+” Opens file for reading and writing purpose. If the file exists, its contents are
overwritten. If the file does not exist, it
will be created.
“a+” Opens an existing file for both reading and If the file does not exists, it will be
appending purpose. created.
Note: The file opening modes in binary files are similar to text mode .Character b is added to each
mode to indicate the binary mode. eg. rb, wb,ab,rb+,wb+,ab+.
Eg.
FILE *fptr,;
fptr=fopen(“sample.txt”, r);
Here, file named sample.txt is opening for reading mode only.
Similarly,
FILE *fptr,;
fptr=fopen(“hello.dat”,wb+);
Here, file named hello.dat is opening for both reading and writing.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
char ch;
FILE *fptr;
fptr=fopen("sample.txt","r");
printf("The character from file are\n");
if(fptr==NULL)
{
printf("File cannot be openend");
exit(1);
}
while((ch=fgetc(fptr))!=EOF)
{
putchar(ch);
}
fclose(fptr);
getch();
return 0;
}
WAP to read a characters from a keyboard, store in a file and display it.
OR
WAP to read a characters from a keyboard and store in a file named ‘sample.txt’ and display it.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
char ch;
FILE *fptr;
fptr=fopen("sample.txt","w+");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
Using string I/O functions, data can be read from a file or written to a file in the form of array of
characters.
syntax: fgets(string_variable,int_value,file_ptr_variable);
Here, int_value denotes the number of characters in string .The functions read a string from a file
representing file_ptr_variable and stores in a variable string variable.
syntax: fputs(string_variable,file_ptr_variable);
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
fptr=fopen("info.txt","w");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
fputs("Welcome to Nepal",fptr);
fclose(fptr);
getch();
return 0;
}
WAP to write a string data to a file
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
char str[50];
fptr=fopen("sample.txt","w");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
printf("Enter the strings");
while((strlen(gets(str))!=0))
{
fputs(str,fptr);
}
fclose(fptr);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
char str[50];
fptr=fopen("sample.txt","r");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
printf("The information from string is\n");
while(fgets(str,50,fptr)!=NULL)
{
puts(str);
}
fclose(fptr);
getch();
return 0;
}
WAP to input strings to a file and display it.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str[50];
FILE *fptr;
fptr=fopen("text.txt","w+");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
printf("Enter the string!\n");
while((strlen(gets(str))!=0))
{
fputs(str,fptr);
}
These functions are used to read numbers, characters or string from a file or write them to a file in a
format as per requirement.
fprintf() It is formatted output function which is used to write integer, float ,char or string data to a file.
Syntax: fprintf(file_ptr_variable,”control_string”,list_variables );
fscanf() It is formatted input function which is used to read integer ,float, char or string data from a
file.
WAP to input age, gender, marks of a student in a file called “student.txt”. Now read these
information from the file display them.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
char gender;
int age;
float marks;
FILE *fptr;
fptr=fopen("student.txt","w+");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
Write a program to create a file “hello.txt”, write data info to the file and finally read from the file.
[PU: 2017 fall]
Solution:
(just change the file name of above program to “hello.txt”)
WAP to open a new file and read name, address and telephone number of 10 employees from a user
and write to a file.[PU: 2013 fall]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
char name[20],address[20];
long int telno;
int i;
FILE *fptr;
fptr=fopen("employee.txt","w");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
char name[20],address[20];
long int telno;
int i;
FILE *fptr;
fptr=fopen("employee.txt","r");
if(fptr==NULL)
{
printf("Unable to open file");
exit(1);
}
printf("Name\tAddress\tTel.no\n");
for(i=0;i<3;i++)
{
fscanf(fptr,"%s%s%ld",name,address,&telno);
printf("\n%s\t%s\t%ld",name,address,telno);
}
fclose(fptr);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
char items[20];
int qty,rate,i;
FILE *fptr;
fptr=fopen("inventory.txt","w");
if(fptr==NULL)
{
printf("Unable to open file");
exit(1);
}
for(i=0;i<3;i++)
{
printf("Enter Product Name, Quantity and Rate");
scanf("%s%d%d",items,&qty,&rate);
fprintf(fptr,"%s\t%d\t%d\n",items,qty,rate);
}
fclose(fptr);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
char items[20];
int qty,rate,i;
FILE *fptr;
fptr=fopen("inventory.txt","r");
if(fptr==NULL)
{
printf("Unable to open file");
exit(1);
}
Output
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
char name[20];
char choice;
int age;
float height;
FILE *fptr;
fptr=fopen("hello.txt","w+");
if(fptr==NULL)
{
printf("Unable to open file");
exit(1);
}
do
{
printf("Enter the name");
scanf("%s",name);
printf("Enter the age");
scanf("%d",&age);
printf("Enter the height") ;
scanf("%f",&height);
printf("Do you want to continue?");
scanf("%c",&choice);
fprintf(fptr,"%s\t%d\t%f\n",name,age,height);
}while(choice=='Y'||choice=='y');
rewind(fptr);
printf("\nName\tAge\tHeight");
while(fscanf(fptr,"%s%d%f",name,&age,&height)!=EOF)
{
printf("\n%s\t%d\t%f",name,age,height);
}
fclose(fptr);
getch();
return 0;
}
Syntax:
fwrite(&ptr,size_of_array_or_structure,number_of_structure_or_array,fptr);
Syntax:
fread(&ptr, size_of_array_or_structure, number_of_structure_or_array, fptr);
where,
i) ptr is the address of an array or structure to be written
ii) Size_of_array_or_structure is an integer value that shows the size of structure or size of array
which is being read or written.
iii) number_of_structure_or_array is an integer value that indicates number of arrays or
structures to be written to file or read from file.
iv) fptr is a file pointer of a file opened in binary mode.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct student
{
int roll;
char name[25];
float marks;
};
int main()
{
FILE *fptr;
char ch;
struct student st;
fptr = fopen("test.dat","wb+");
if(fptr == NULL)
{
printf("File cannot be opened");
exit(1);
}
do
{
printf("Enter the Rollno:\n");
scanf("%d",&st.roll);
printf("Enter the Name:\n");
scanf("%s",st.name);
printf("Enter the Marks:\n");
scanf("%f",&st.marks);
fwrite(&st,sizeof(st),1,fptr);
printf("Do you want to add another data (y/n):\n");
ch = getche();
}while(ch=='y' || ch=='Y');
printf("Data written successfully\n");
rewind(fptr);
printf("\nRoll\tName\tMarks\n");
while(fread(&st,sizeof(st),1,fptr)==1)
{
printf("\n%d\t%s\t%f",st.roll,st.name,st.marks);
}
fclose(fptr);
getch();
return 0; }
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct university
{
char name[20];
char location[20];
int nooffaculties;
};
int main()
{
struct university u[100];
int i,n;
FILE *fptr;
fptr=fopen("university.dat","wb+");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
printf("Enter number of colleges\n");
scanf("%d",&n);
printf("Enter records of %d college\n",n);
for(i=0;i<n;i++)
{
printf("Enter college name\n");
gets(u[i].name);
printf("Enter location\n");
gets(u[i].location);
printf("Enter number of faculties\n");
scanf("%d",&u[i].nooffaculties);
}
fwrite(&u,sizeof(u),n,fptr);
rewind(fptr);
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct university
{
char name[20];
char location[20];
int nooffaculties;
};
int main()
{
struct university u[100];
int i,n;
FILE *fptr;
fptr=fopen("university.dat","wb+");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
printf("Enter number of colleges\n");
scanf("%d",&n);
printf("Enter records of %d college\n",n);
for(i=0;i<n;i++)
{
printf("Enter college name\n");
gets(u[i].name);
printf("Enter location\n");
for(i=0;i<n;i++)
{
fread(&u,sizeof(u[i]),1,fptr);
if(strcmp(u[i].location,"kathmandu")==0)
{
printf("\n%s",u[i].name);
}
}
fclose(fptr);
getch();
return 0;
}
Alternative solution-2
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct university
{
char name[20];
char location[20];
int nooffaculties;
};
int main()
{
struct university u;
int i,n;
FILE *fptr;
fptr=fopen("university.dat","wb+");
if(fptr==NULL)
{
printf("File cannot be opened");
getch();
exit(1);
}
Assignment:
Create a structure with data members college name, location and number of faculties. Now read the
information of 50 colleges affiliated to Pokhara university and write them into the file named
university.dat and while retrieving ,display the information of colleges whose address is Kathmandu.
2) Write a program by using structure that includes using structure that includes AccNO,
CName, CAddress, CTelno and balance for 100 customers of ABC financial institution and
store in account.txt file and finally display the information of the customers who have
balance greater than Rs.10,000 [PU:2012 fall]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
3) Write a program to create structure for the following data for student (RN, Name, phone,
address and semester).Read the 10 students by user and write only those students whose
semester is 1 in file “student.txt”.[PU:2016 fall]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct student
{
char name[20];
int rollno;
long int phone;
char address[20];
int semester;
};
int main()
{
int i;
struct student st[10];
FILE *fptr;
fptr=fopen("student.txt","wb");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
4) Write a program to input name, address, faculty, program and GPA(in maximum 4.0) of 500
students and store them in ‘RESULT.DAT’ data file and display the records of those student
whose faculty is ‘Engineering’ and GPA>3.5. [PU: 2016 spring]
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
struct student
{
char name[20];
char address[20];
char faculty[20];
char program[20];
float gpa;
};
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct cricketplayer
{
char pname[20];
char pcountry[20];
char ptype[20];
int noofmatches;
float salary;
};
int main()
{
struct cricketplayer c[100];
int i,n;
FILE *fptr;
fptr=fopen("cricket.txt","wb+");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
printf("Enter the number of cricket players\n");
scanf("%d",&n);
printf("Enter records of %d cricket players",n);
for(i=0;i<n;i++)
{
printf("Enter player name");
gets(c[i].pname);
printf("Enter country");
gets(c[i].pcountry);
printf("Enter playing type");
gets(c[i].ptype);
printf("Enter number of matches played");
scanf("%d",&c[i].noofmatches);
printf("Enter salary");
scanf("%f",&c[i].salary);
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
struct football
{
char pname[20];
char pcountry[20];
char tname[20];
int noofmatches;
float salary;
};
int main()
{
struct football f[100];
int i,n;
FILE *fptr;
fptr=fopen("football.txt","wb+");
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
Assignment:
Create a structure named Employee with structure members name, eid, address and gender. Structure
need to read information for 50 employees. Write all content into the file info.dat and while retrieving
display the information of those employees whose address is “Kathmandu”.
[PU: 2019 fall]
8) Create a structure called goods that stores number, price, purchase date and quantity. WAP
to store information of 100 goods in the file “good.dat” [PU: 2011 fall]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct date
{
int yy;
int mm;
int dd;
};
struct goods
{
int number;
float price;
struct date d;
int quantity;
};
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct date
{
int yy;
int dd;
int mm;
};
Write a program to create “student.txt” file to store the above records for 100 students and display
the records of student who are not from pokhara. [PU: 2014 fall]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
Assignment:
i)Consider the following structure:
Write a program to create “student.txt” file to store the above records for 100 students and display the
records of student who are not from Kathmandu.
Write a program to create “student.txt” file to store the above records for 100 students.[PU:2019
spring]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct book
{
char name[20];
char author[20];
float price;
};
int main()
{
int i;
struct book b[500];
FILE *fptr;
fptr=fopen("library.dat","rb");
if(fptr==NULL)
{
printf("file cannot be opened");
exit(1);
}
printf("Book which price is above 300 are");
printf("\nName\tprice");
fread(&b,sizeof(b),500,fptr);
for(i=0;i<500;i++)
{
if(b[i].price>300)
{
printf("\n%s\t%f",b[i].name,b[i].price);
}
}
fclose(fptr);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct book
{
char name[20];
char author[20];
float price;
};
int main()
{
int i;
struct book b;
FILE *fptr;
fptr=fopen("library.dat","rb");
if(fptr==NULL)
{
printf("file cannot be opened");
exit(1);
}
printf("Book which price is above 300 are");
printf("\nName\tprice");
while(fread(&b,sizeof(b),1,fptr)==1)
{
if(b.price>300)
{
printf("\n%s\t%f",b.name,b.price);
}
}
fclose(fptr);
getch();
return 0;
}
11) Write a program to input name, address, registration no, faculty and academic year of
admission in university of ‘n’ number of students of Pokhara University and append them in
data file called ‘STUDENT.DAT’. Then display the records of those students by reading the
records from ‘STUDENT.DAT’ data file who got admission in 2016. [PU: 2015 spring]
if(fptr==NULL)
{
printf("File cannot be opened");
exit(1);
}
printf("Enter number of students");
scanf("%d",&n);
printf("Enter records of %d students of pokhara university\n",n);
for(i=0;i<n;i++)
{
printf("Enter name\n");
gets(st.name);
printf("Enter address\n");
gets(st.address);
printf("Enter registration number\n");
scanf("%ld",&st.regno);
printf("Enter faculty\n");
gets(st.faculty);
printf("Enter admission year\n");
scanf("%d",&st.year);
fwrite(&st,sizeof(st),1,fptr);
}
rewind(fptr);
printf("The records of student who got admission in 2016 are:\n");
printf("\nName\tAddress\tReg.no.\tFaculty\tAdmission Year");
Alternative solution:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct student
{
char name[20];
char address[20];
long int regno;
char faculty[20];
int year;
};
int main()
{
struct student st[100],s;
int i,n;
FILE *fptr;
fptr=fopen("student.dat","ab+");
if(fptr==NULL)
{
printf("File cannot be opened\n");
exit(1);
}
printf("Enter number of students");
scanf("%d",&n);
printf("Enter records of %d students of pokhara university\n",n);