Department of CE / IT 07 / 16 ... - Dr. Subhash Tech
Transcript of Department of CE / IT 07 / 16 ... - Dr. Subhash Tech
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
1 DSTC Junagadh
1. FUNDAMENTAL OF COMPUTER: Definition:
“Computer is an electronic device that is designed to work with Information.”
The term ‘computer’ is derived from the Latin term ‘computare’, this means to calculate.
Computer is an advanced electronic device that takes raw data as input from the
user and processes these data under the control of set of instructions (called
program) and gives the result (output) and saves output for the future use. It can
process both numerical and non-numerical (arithmetic and logical) calculations.
The basic components of a modern digital computer are:
Input Device
Output Device
Central Processor Unit
Storage Device
Basic block diagram of computer system:
Figure: Basic block diagram of computer system
Input Unit:
We need to input the data and instructions into the computers. The input unit
consists of one or more input devices.
Example: Keyboard, Mouse, Joy stick, Webcam, Scanner
All the input devices perform the following functions.
1) Accept the data and instructions from the outside world.
2) Convert it to a form that the computer can understand.
3) Supply the converted data to the CPU for further processing.
Input Unit
Central
Processor Unit
(CPU)
Storage
Unit
Output Unit
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
2 DSTC Junagadh
Central Processing Unit(CPU):
The control unit and ALU of the computer are together known as the Central Processing
Unit (CPU).
The CPU is like brain performs the following functions:
1) It performs all calculations.
2) It takes all decisions.
3) It controls all units of the computer.
A PC may have CPU-IC such as Intel 8088, 80286, 80386, 80486, Celeron, Pentium,
Pentium Pro, Pentium II, Pentium III, Pentium IV, Dual Core, and AMD etc.
Output Unit:
The output unit of a computer provides the information and results of a computation to
outside world.
Example: Printers, Monitor, Plotter, LCD
All the output devices perform the following functions.
Accept data or information from CPU or storage device.
Then display it on display device.
Storage Unit:
The storage unit of the computer holds data and instructions that are entered through the
input unit, before they are processed. It preserves the intermediate and final results before
these are sent to the output devices. It also saves the data for the later use.
Types of Storage Devices:
1. Primary Storage
2. Secondary Storage
Example: RAM, ROM, Hard disk, Floppy disk, pen drive
2. CLASSIFICATION OF COMPUTER SYSTEM: Computers differ based on their data processing abilities. They are classified according to
purpose, data handling and functionality, size.
According to purpose, computers are
General purpose:
General purpose computers are designed to perform a range of tasks. They
have the ability to store numerous programs, but lack in speed and efficiency.
specific purpose:
Specific purpose computers are designed to handle a specific problem or to
perform a specific task.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
3 DSTC Junagadh
According to data handling, computers are
Analog Computer:
Analog computers work on the principle of measuring, in which the
measurements obtained are translated into data. Modern analog computers
usually employ electrical parameters, such as voltages, resistances or currents,
to represent the quantities being manipulated. Such computers do not deal
directly with the numbers. They measure continuous physical magnitudes.
Digital Computer:
Digital computers are those that operate with information, numerical or
otherwise, represented in a digital form. Such computers process data into a
digital value (in 0s and 1s). They give the results with more accuracy and at a
faster rate.
Hybrid Computer:
Hybrid computers incorporate the measuring feature of an analog computer
and counting feature of a digital computer. For computational purposes, these
computers use analog components and for storage, digital memories are used.
According to size, computer are
Super Computer The fastest and most powerful type of computer Supercomputers are very
expensive and are employed for specialized applications that require immense
amounts of mathematical calculations. For example, weather forecasting
requires a supercomputer. Other uses of supercomputers include animated
graphics, fluid dynamic calculations, nuclear energy research, and petroleum
exploration.
Mainframe Computer A very large and expensive computer capable of supporting hundreds, or even
thousands, of users simultaneously. In the hierarchy that starts with a simple
microprocessor (in watches, for example) at the bottom and moves to
supercomputers at the top, mainframes are just below supercomputers. In
some ways, mainframes are more powerful than supercomputers because they
support more simultaneous programs. But supercomputers can execute a
single program faster than a mainframe.
Mini Computer A midsized computer. In size and power, minicomputers lie between
workstations and mainframes. In the past decade, the distinction between large
minicomputers and small mainframes has blurred, however, as has the
distinction between small minicomputers and workstations. But in general, a
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
4 DSTC Junagadh
minicomputer is a multiprocessing system capable of supporting from 4 to
about 200 users simultaneously.
Micro Computer or Personal Computer
Desktop Computer:
A personal or micro-mini computer sufficient to fit on a desk.
Laptop Computer:
A portable computer complete with an integrated screen and keyboard.
It is generally smaller in size than a desktop computer and larger than a
notebook computer.
Palmtop Computer/Digital Diary /Notebook /PDAs:
A hand-sized computer. Palmtops have no keyboard but the screen
serves both as an input and output device.
Workstations
A terminal or desktop computer in a network. In this context, workstation is
just a generic term for a user's machine (client machine) in contrast to a
"server" or "mainframe."
3. CHARACTERISTICS OF COMPUTER SYSTEM: 1. Speed:
As you know computer can work very fast. It takes only few seconds for calculations that we take
hours to complete. You will be surprised to know that computer can perform millions (1,000,000)
of instructions and even more per second.
2. Accuracy:
The degree of accuracy of computer is very high and every calculation is performed with
the same accuracy. The accuracy level is 7 determined on the basis of design of computer.
The errors in computer are due to human and inaccurate data.
3. Diligence:
A computer is free from tiredness, lack of concentration, fatigue, etc. It can work for
hours without creating any error. If millions of calculations are to be performed, a
computer will perform every calculation with the same accuracy.
4. Versatility:
It means the capacity to perform completely different type of work. You may use your
computer to prepare payroll slips. Next moment you may use it for inventory
management or to prepare electric bills.
5. Power of Remembering:
Computer has the power of storing any amount of information or data. Any information
can be stored and recalled as long as you require it, for any numbers of years. It depends
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
5 DSTC Junagadh
entirely upon you how much data you want to store in a computer and when to lose or
retrieve these data.
6. No IQ:
Computer is a dumb machine and it cannot do any work without instruction from the user.
It performs the instructions at tremendous speed and with accuracy. It is you to decide
what you want to do and in what sequence. So a computer cannot take its own decision as
you can.
7. No Feeling:
It does not have feelings or emotion, taste, knowledge and experience. Thus it does not
get tired even after long hours of work. It does not distinguish between users.
8. Storage:
The Computer has an in-built memory where it can store a large amount of data. You can
also store data in secondary storage devices such as floppies, which can be kept outside
your computer and can be carried to other computers.
4. APPLICATION OF COMPUTER SYSTEM:
Education
Health and Medicine
Science
Business
Recreation and Entertainment
Government
Defense
Sports
5. LIMITATIONS OF COMPUTER SYSTEM:
Computer cannot identify any input and output by itself for solving a problem.
It cannot make any decision related problem, solution formula must be given.
Cannot make any decision base on experience.
It cannot interpret the data store into storage media in different aspects as per
situation.
For every solution rules or procedure or sequence needed.
6. Difference between hardware and software: Hardware Software It is a physical component of computer. It’s a logical component of computer.
Hardware contains electronic components. Software is a collection of programs.
User can touch the hardware of computer. User can not touch software in computer.
Hardware is divided into three part: Software is divided into two parts:
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
6 DSTC Junagadh
Input/output devices
Processor
Storage device
System software
Application software
Example: Monitor, printer, keyboard, mouse,
scanner
Example: OS, MS office, turbo c, matlab
7. Difference between compiler and interpreter: Compiler Interpreter Compiler scans the whole program at a
time and list out error if any.
Interpreter scans the program line by line and
stops scanning whenever error occurs.
Compiler converts the whole source
code into object code at a time.
Interpreter converts the source program to
executable code.
Execution is faster. Execution is slower.
Object code is generated when the
program is error free.
Interpreter generates object code for each line
immediately if it is error free.
8. Difference between system software and application software: System Software Application Software System software comprise of those programs,
which directs the computer.
Application software is the software
developed for solving business problems.
System software varies from computer to
computer.
Application software varies from
organization to organization
System software is written in low-level
language.
Application software are usually written in
high level language.
Detail knowledge of hardware is required This requires detailed knowledge of
organization.
System software is used to improve the
performance and maximum utilization of
system resources.
Application software programs are used to
improve the speed and quality of a business
activity.
The manufactures along with the hardware
usually supply system software.
Application software is developed by
individuals or supplied by software vendors
as generalized application software.
9. Difference between data and information: Data Information
Data is plural of word Datum. It is defined as
the raw of facts or observations or
assumptions or occurrence about physical
phenomenon or business transaction.
It is the data that has been converted in to a
meaningful and useful context for specific
end uses.
Data is the collection of facts, which is
unorganized in to useful information.
Information is an organized or classified data
having a high value for its users.
They are the objective measurements of
attributes (Characteristics) of entities (like
people, place, thing and events)
To obtain information, data is subjected to the
following:-
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
7 DSTC Junagadh
1. Data’s form is aggregated,
manipulated and organized
2. Its content is analyzed and evaluated.
3. It is placed in a proper context for a
human user.
Data should be accurate but need not be
relevant, timely or concise
Information must be relevant, accurate,
timely, concise and complete and apply to the
current situation. It should be condensed into
suitable length.
It can exist in different forms. E.g. picture,
sound, text or all these together
It exists as reports, in a systematic textual
format, or as graphics.
10. ALGORITHM: Algorithm is a step wise solution of given problem or flowchart. Or A process or set
of rules to be followed in calculations or other problem-solving operations, esp. by a
computer.
An algorithm is any set of detailed instructions which results in a predictable end-state
from a known beginning.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
8 DSTC Junagadh
11. FLOW CHART:
Flow chart is a graphical representation of problem. Generally following symbols are used to
represent flow chart:
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
9 DSTC Junagadh
12. Define terms:
Computer System:
Computer is an advanced electronic device that takes raw data as input from the user
and processes these data under the control of set of instructions (called program) and
gives the result (output) and saves output for the future use. It can process both
numerical and non-numerical (arithmetic and logical) calculations.
Computer hardware:
Computer hardware refers to the physical parts of a computer and related devices.
Computer Software:
Computer software is a general term that describes set of computer programs.
System software: Software used to control the computer and develop and run applications. It includes programs
such as operating systems, database managers, compilers, Web servers, router operating
systems and control programs for other network devices.
Application software: Application software is a program or group of programs designed for end users.
High level language:
A computer programming language that resembles natural language or mathematical notation
and is designed to reflect the requirements of a problem
Low level language:
A computer language consisting of mnemonics that directly correspond to machine language
instructions.
Compiler: A compiler is a software program that compiles program source code files into an executable
program.
Interpreter: An interpreter is a program that reads and executes code. This includes source code, pre-
compiled code, and script.
Data: Computer data is raw material.
Information:
Information is processed data.
Algorithm:
Step wise solution of problem/program.
Flowchart: Graphical representation of problem/program.
13. WHAT IS C?
C language is a general purpose and structured programming language developed by 'Dennis
Ritchie' at AT&T's Bell Laboratories in the 1972s in USA.
It is also called as 'Procedure oriented programming (POP) language.'
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
10 DSTC Junagadh
C is not specially designed for specific applications areas like COBOL (Common Business-
Oriented Language) or FORTRAN (Formula Translation). It is well suited for business and
scientific applications. It has some various features like control structures, looping
statements, arrays, macros required for these applications.
The C language has following numerous features as:
Portability
Flexibility
Effectiveness and efficiency
Reliability
Interactivity
14. EXECUTION OF C PROGRAM:
C program executes in following 4 (four steps).
1. Creating a program :
An editor like notepad or word pad is used to create a C program. This file contains a
source code which consists of executable code. The file should be saved as '*.c'
extension only.
2. Compiling the program :
The next step is to compile the program. The code is compiled by using compiler.
Compiler converts executable code to binary code i.e. object code.
3. Linking a program to library :
The object code of a program is linked with libraries that are needed for execution of
a program. The linker is used to link the program with libraries. It creates a file with
'*.exe' extension.
4. Execution of program :
The final executable file is then run by dos command prompt or by any other
software.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
11 DSTC Junagadh
15. HISTORY OF C:
Year of
Establishment Language Name Developed By
1960 ALGOL-60 Cambridge University
1963 CPL (Combined Programming
Language) Cambridge University
1967 BCPL (Basic Combined
Programming Language)
Martin Richard at
Cambridge University
1970 B Ken Thompson at AT& T's
Bell Laboratories.
1972 C Dennis Ritchie at AT& T'
Bell Laboratory.
The development of C was a cause of evolution of programming languages like Algol 60,
CPL (Combined Programming Language), BCPL (Basic Combined Programming Language)
and B.
Algol-60 : (1963) :
ALGOL is an acronym for Algorithmic Language. It was the first structured
procedural programming language, developed in the late 1950s and once widely used
in Europe. But it was too abstract and too general structured language.
CPL : (1963) :
CPL is an acronym for Combined Programming Language. It was developed at
Cambridge University.
BCPL : (1967) :
BCPL is an acronym for Basic Combined Programming Language. It was developed
by Martin Richards at Cambridge University in 1967. BCPL was not so powerful. So,
it was failed.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
12 DSTC Junagadh
B : (1970) :
B language was developed by Ken Thompson at AT& T Bell Laboratories in 1970. It
was machine dependent. So, it leads to specific problems.
C : (1972) :
'C' Programming Language was developed by Dennis Ritchie at AT& T Bell
Laboratories in 1972. This is general purpose, compiled, structured programming
language. Dennis Ritchie studied the BCPL, then improved and named it as 'C' which
is the second letter of BCPL
16. STRUCTURE OF C PROGRAM
The basic structure of C program is as follow:
Document Section
Links Section (File)
Definition Section
Global variable declaration Section
void main()
{
Variable declaration section
Function declaration section
executable statements;
}
Function definition 1
---------------------
---------------------
Function definition n
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
13 DSTC Junagadh
Where,
Document Section:
It consists of set of comment lines which include name of a program, author name, creation
date and other information.
Links Section (File):
It is used to link the required system libraries or header files to excute a program.
Definition Section:
It is used to define or set values to variables.
Global variable declaration Section:
It is used to declare global or public variable.
void main():
Used to start of actual C program. It includes two parts as declaration part and executable
part.
Variable declaration section:
Used to declare private variable.
Function declaration section:
Used to declare functions of program from which we get required output.
Then, executable statements are placed for execution.
Function definition section:
Used to define functions which are to be called from main ().
17. USE OF SEMICOLONS (;) In C program, the semicolon is a statement terminator. That is, each individual
statement must be ended with a semicolon. It indicates the end of one logical entity.
For example, following are two different statements:
printf ("Hello, World! \n");
return0;
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
14 DSTC Junagadh
18. COMMENTS
Comments are like helping text in your C program and they are ignored by the compiler. It
means lines within comment are not executed by compiler. They are of two types:
Single line comment
Multi line comment
1) Single Line Comments.
At a time put only one line intima comment. Start with //
Example:
//This is Program one
2) Multi Line Comment
Put more than one line into comment. Start with /* and terminates with the characters
*/
Example:
/* Hello Friends
This is my first program of
C language */
19. TOKENS IN C
A C program consists of various tokens and a token is a keyword, an identifier, a constant, a
string literal, or a symbol.
For example, the following C statement consists of five tokens:
printf("Hello, World! \n");
The individual tokens are:
printf
(
"Hello, World! \n"
);
Character set:
A character refers to the digit, alphabet or special symbol used to data represetation.
1. Alphabets : A-Z, a-z
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
15 DSTC Junagadh
2. Digits : 0-9
3. Special Characters: ~! @ # $ % ^ & * ( ) _ + { } [ ] - <> , . / ? \ | : ; " '
4. White Spaces : Horizontal tab, Carriage return, New line, form feed
Identifier:
Identifier is the name of a variable that is made up from combination of alphabets, digits and
underscore.
Variable:
It is a data name which is used to store data and may change during program execution. It is
opposite to constant. Variable name is a name given to memory cells location of a computer
where data is stored.
Rules for variables:
First character should be letter or alphabet.
Keywords are not allowed to use as a variable name.
White space is not allowed.
C is case sensitive i.e. UPPER and lower case are significant.
Only underscore, special symbol is allowed between two characters.
The length of identifier may be up to 31 characters but only only the first 8 characters
are significant by compiler.
(Note: Some compilers allow variable names whose length may be up to 247
characters. But, it is recommended to use maximum 31 characters in variable name.
Large variable name leads to occur errors.)
Keywords:
Keywords are the system defined identifiers.
All keywords have fixed meanings that do not change.
White spaces are not allowed in keywords.
Keyword may not be used as an identifier.
It is strongly recommended that keywords should be in lower case letters.
There are totally 32(Thirty Two) keywords used in a C programming.
int float double long
short signed unsigned const
if else switch break
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
16 DSTC Junagadh
default do while for
register extern static struct
typedef enum return sizeof
goto union auto case
void char continue volatile
Escape Sequence Characters (Backslash Character Constants) in C:
C supports some special escape sequence characters that are used to do special tasks.
These are also called as 'Backslash characters'.
Some of the escape sequence characters are as follow:
Character Constant Meaning
\n New line (Line break)
\b Backspace
\t Horizontal Tab
\f Form feed
\a Alert (alerts a bell)
\r Carriage Return
\v Vertical Tab
\? Question Mark
\' Single Quote
\'' Double Quote
\\ Backslash
\0 Null
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
17 DSTC Junagadh
20. Constants in C:
A constant is an entity that doesn't change during the execution of a program.
Followings are the different types of constants:
Real Constant
Integer Constant
Character Constant
String Constant
1. Real Constant:
It must have at least one digit.
It must have a decimal point which may be positive or negative.
Use of blank space and comma is not allowed between real constants.
Example:
+194.143, -416.41
2. Integer Constant:
It must have at least one digit.
It should not contain a decimal place.
It can be positive or negative.
Use of blank space and comma is not allowed between real constants.
Example:
1990, 194, -394
3. Character Constant:
It is a single alphabet or a digit or a special symbol enclosed in a single quote.
Maximum length of a character constant is 1.
Example:
'T', '9', '$'
4. String Constant:
It is collection of characters enclosed in double quotes.
It may contain letters, digits, special characters and blank space.
Example:
"Hello Friends, How are you?"
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
18 DSTC Junagadh
21. DATA TYPES IN C:
Data type can be defined as the type of data of variable or constant store.
When we use a variable in a program then we have to mention the type of data. This can be
handled using data type in C.
Followings are the most commonly used data types in C.
Keyword Format Specifier Size Data Range
char %c 1 Byte -128 to +127
unsigned
char <-- -- > 8 Bytes 0 to 255
int %d 2 Bytes -32768 to +32767
long int %ld 4 Bytes -231 to +231
unsigned int %u 2 Bytes 0 to 65535
float %f 4 Bytes -3.4e38 to +3.4e38
double %lf 8 Bytes -1.7e38 to +1.7e38
long double %Lf 12-16 Bytes -3.4e38 to +3.4e38
Qualifier:
When qualifier is applied to the data type then it changes its size or its size.
Size qualifiers: short, long
Sign qualifiers: signed, unsigned
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
19 DSTC Junagadh
Enum Data Type:
This is an user defined data type having finite set of enumeration constants. The keyword
'enum' is used to create enumerated data type.
Syntax:
enum [data_type] {const1, const2, ...., const n};
Example:
enummca (software, web, seo);
Typedef:
It is used to create new data type. But it is commonly used to change existing data type with
another name.
Syntax:
typedef [data_type] synonym;
OR
typedef [data_type] new_data_type;
Example:
typedefint integer;
integer rno;
22. OPERATORS IN C:
Operator is a symbol that is used to perform mathematical operations.
When we use a variable in a program then we have to mention the type of data. This can be
handled using data type in C.
Followings are the most commonly used data types in C.
Operator Name Operators
Assignment =
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
20 DSTC Junagadh
Arithmetic +, -, *, /, %
Logical &&, ||, !
Relational <, >, <=, >=, ==, !=
Shorthand +=, -=, *=, /=, %=
Unary/Increment - Decrement ++, --
Conditional ()?:;
Bitwise &, |, ^, <<, >>, ~
1. Assignment Operator:
It is used to assign a value to variable. Value after equal to is assigned to variable before
equal to.
Syntax:
Destination variable name = value / source variable name;
Example:
/* Program to demonstrate assignment operator */
#include <stdio.h>
#include <conio.h>
void main()
{
inta,b;
clrscr();
a = 53;
printf("\n\t Value of A : %d",a);
b = a; // Interchange of value using assignment
printf("\n\n\t Value of B : %d",b);
getch();
}
Output:
Value of A: 53
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
21 DSTC Junagadh
Value of B: 53
2. Arithmetic Operators:
It is used to perform arithmetical operations. It is also called as 'Binary operators'.. These
operators operate on two operands.
Syntax:
Operand3 = operand1 operator operand2;
Example:
/* Program to demonstrate arithmetic operators */
#include <stdio.h>
#include <conio.h>
void main()
{
int a,b,c,d,e,f,g;
clrscr();
printf("\n\t Enter First Number :");
scanf("%d",&a);
printf("\n\t Enter Second Number :");
scanf("%d",&b);
c = a + b;
printf("\n\n\t Addition is : %d",c);
d = a - b;
printf("\n\n\t Subtraction is : %d",d);
e = a * b;
printf("\n\n\t Multiplication is : %d",e);
f = a / b;
printf("\n\n\t Division is : %d",f);
g = a % b;
printf("\n\n\t Modulus is : %d",g);
getch();
}
Output:
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
22 DSTC Junagadh
Enter First Number : 5
Enter Second Number : 2
Addition is : 7
Subtraction is : 3
Division is : 2
Modulus is : 1
3. Relational Operators:
It is also used to check conditions. These operators return 1 if condition is true otherwise 0.
Example:
/* Program to demonstrate Relational operators .*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a=6, b=2;
clrscr();
if (no1 < no2)
{
printf("\n\nNo1 is Minimum”);
}
else
{
printf("\n\nNo1 is Minimum”);
}
getch();
}
Output:
No1 is Minimum
4. Logical Operators:
Sometimes, we have to check more than one condition at a time then conditional operator is
used. These operator returns 1 if condition is true otherwise 0.
Example:
/* Program to demonstrate logical operators .*/
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
23 DSTC Junagadh
#include <stdio.h>
#include <conio.h>
void main()
{
int no1=2, no2=5, no3=4;
clrscr();
if (no1 > no2 && no1 > no3)
{
printf("\n\nNo1 is Maximum”);
}
else if(no2 > no3 && no2 > no3)
{
printf("\n\nNo2 is Maximum”);
}
else
{
printf("\n\nNo3 is Maximum”);
}
getch();
}
Output:
No2 is Maximum
5. Unary Operators / Increment – decrement operator:
It operates on a single operand. Therefore, this operator is called as 'unary operator.' It is used
to increase or decrease the value of variable by 1.
Syntax:
Operand++;
++Operand;
First line shows postfix increment. It means first it assigned a value and then increase by one.
While second line shows prefix increment. Means first it increase a value by one and then
assigned.
Example:
/* Program to demonstrate Unary / Ternary operators .*/
#include <stdio.h>
#include <conio.h>
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
24 DSTC Junagadh
void main()
{
int a=4, b;
clrscr();
printf("\n\n Value of A : %d",a);
a++;
printf("\n\n Value of A : %d",a);
++a;
printf("\n\n Value of A : %d",a);
b=--a;
printf("\n\n Value of A : %d",a);
printf("\n\n Value of B : %d",b);
b=a++;
printf("\n\n Value of A : %d",a);
printf("\n\n Value of B : %d",b);
b++;
printf("\n\n Value of B : %d",b);
getch();
}
Output:
Value of A : 4
Value of A : 5
Value of A : 6
Value of A : 5
Value of B : 5
Value of A : 6
Value of B : 5
Value of B : 6
6. Conditional Operator:
Conditional operator is also called as 'ternary operator'. It is widely used to execute
condition in true part or in false part. It operates on three operands. The logical or relational
operator can be used to check conditions.
Syntax:
(Condition) ? (True part ) : (False Part);
Example:
/* Program to demonstrate conditional operator */
#include <stdio.h>
#include <conio.h>
void main()
{
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
25 DSTC Junagadh
int a, b=3;
clrscr();
a = 5;
printf("\n\n A is less than B ? ");
(a<b) ?printf(“Yes”) : printf(“No”);
getch();
}
Output:
A is less than B?
No
7. Bitwise Operators:
Bitwise operators are used for manipulation of data at a bit level. They can be directly applied
to char, short int and long.
8. Special Operators:
Comma Operator:
Comma operators are used to link related expression together.
Example:
int a, b;
Sizeof Operator:
It is unary operator which is used in finding the size of data type, constant, arrays, structure
etc.
Syntax:
Sizeof(variable name);
Example:
#include<stdio.h>
main()
{
int a =4;
float b = 2.5;
char c = ‘a’;
printf("Size of variable a = %d\n",sizeof(a));
printf("Size of variable b = %d\n",sizeof(b));
printf("Size of variable c= %d\n",sizeof(c));
getch();
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
26 DSTC Junagadh
}
Output:
Size of variable a = 2
Size of variable b = 4
Size of variable c = 1
Operators Precedence and Associativity :
In C, each and every operator has a spcial precedence which is associated with it. There are
various levels of precedence. This precedence is especially used to determine to evaluation of
expression which has more than one operator in it. The operators which has higher
precedence are executed first and vice-versa. Operators which has same precedence level are
evaluated from left to right. It is dependent on its level. This feature is well known as
'Associativity of an operator.'
Associativity Operator Description
Left to Right
() Function
[] Array
--> Pointer to member
. Structure
Right to left
- Unary Minus
+ Unary Plus
++ / -- Increment/Decrement
~ One's Complement
& Address of
(type) Type casting
sizeof Size (in bytes)
! Logical Not
* Pointer reference
Left to Right
* Multiplication
/ Division
% Modulus
Left to Right + Addition
- Subtraction
Left to Right << Left Shift
>> Right Shift
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
27 DSTC Junagadh
Left to Right
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
Left to Right == Equality
!= Not Equal to
Left to Right & Bitwise AND
Left to Right ^ Bitwise XOR
Left to Right | Bitwise OR
Left to Right && Logical AND
Left to Right || Logical OR
Left to Right ? : Conditional Operator
Right to Left = *= += Assignment
Left to Right , Comma
23. DECISION MAKING STATEMENTS / CONDITIONAL
STATEMENTS:
C program executes program sequentially. Sometimes, a program requires checking of
certain conditions in program execution. C provides various key condition statements to
check condition and execute statements according conditional criteria.
These statements are called as 'Decision Making Statements' or 'Conditional Statements.'
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
28 DSTC Junagadh
Followings are the different conditional statements used in C.
1. If Statement
2. If-Else Statement
3. Nested If-Else Statement
4. Ladder If-Else Statement
5. Switch Case
If Statement:
This is a conditional statement used in C to check condition or to control the flow of
execution of statements. This is also called as 'decision making statement or control
statement.' The execution of a whole program is done in one direction only.
Syntax:
if(condition)
{
statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and executes the block of statements associated with it. If it returns
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
29 DSTC Junagadh
false, then program skips the braces. If there are more than 1 (one) statements in if statement
then use { } braces else it is not necessary to use.
Program :
/* Program to demonstrate if statement.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
a=5;
clrscr();
if(a>4)
{
printf("\nValue of A is greater than 4 !");
}
getch();
}
Output :
Value of A is greater than 4 !_
If-Else Statement :
This is also one of the most useful conditional statement used in C to check conditions.
Syntax:
if(condition)
{
true statements;
}
else
{
false statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and executes the block of statements associated with it. If it returns
false, then it executes the else part of a program.
Example:
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
30 DSTC Junagadh
/* Program to demonstrate if-else statement.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no%2==0)
{
printf("\n\n Number is even !");
}
else
{
printf("\n\n Number is odd !");
}
getch();
}
Output :
Enter Number : 11
Number is odd !
Nested If-Else Statement:
It is a conditional statement which is used when we want to check more than 1 condition at a
time in a same program. The conditions are executed from top to bottom checking each
condition whether it meets the conditional criteria or not. If it found the condition is true then
it executes the block of associated statements of true part else it goes to next condition to
execute.
Syntax:
if(condition)
{
if(condition)
{
statements;
}
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
31 DSTC Junagadh
else
{
statements;
}
}
else
{
statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and again checks the next condition. If it is true then it executes the
block of statements associated with it else executes else part.
Program :
/* Program to demonstrate nested if-else statement.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no>0)
{
printf("\n\n Number is greater than 0 !");
}
else
{
if(no==0)
{
printf("\n\n It is 0 !");
}
else
{
printf("Number is less than 0 !");
}
}
getch();
}
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
32 DSTC Junagadh
Output :
Enter Number : 0
It is 0 !
Ladder If-Else Statement:
It is a conditional statement which is used when we want to check more than 1 conditions in a
same program. The conditions are executed from top to bottom checking each condition
whether it meets the conditional criteria or not. If it found the condition is true then it
executes the block of associated statements of true part else it goes to next condition to
execute. Into next condition again check if. If condition is true then execute otherwise goes to
else. If all concision becomes false then execute last else.
Syntax:
if(condition)
{
statements;
}
else if(condition)
{
statements;
}
else if(condition)
{
statements;
}
:
:
else
{
statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and again checks the next condition. If it is true then it executes the
block of statements associated with it else executes else part.
Program :
/* Program to demonstrate nested if-else statement.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
33 DSTC Junagadh
Creation Date : 09 Nov 2010 02:51:18 AM
Author : www.technoexam.com [Technowell, Sangli] */
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no>0)
{
printf("\n\n Number is greater than 0 !");
}
Else if(no<0)
{
printf("\n\n Number is less than 0 !");
}
else
{
printf("Number equal to 0 !");
}
getch();
}
Output :
Enter Number : 0
Number equal to 0 !
24. Switch case Statement:
This is a multiple or multi way branching decision making statement.
When we use nested if-else statement to check more than 1 conditions then the complexity of
a program increases in case of a lot of conditions. Thus, the program is difficult to read and
maintain. So to overcome this problem, C provides 'switch case'.
Switch case checks the value of a expression against a case values, if condition matches the
case values then the control is transferred to that point.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
34 DSTC Junagadh
Syntax:
switch(expression)
{
case expr1:
statements;
break;
case expr2:
statements;
break;
:
:
caseexprn:
statements;
break;
default:
statements;
}
In above syntax, switch, case, break are keywords.
expr1, expr2 are known as 'case labels.'
Statements inside case expression need not to be closed in braces.
Break statement causes an exit from switch statement.
Default case is optional case. When neither any match found, it executes.
Program :
/* Program to demonstrate switch case statement.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter any number from 1 to 3 :");
scanf("%d",&no);
switch(no)
{
case 1:
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
35 DSTC Junagadh
printf("\n\n It is 1 !");
break;
case 2:
printf("\n\n It is 2 !");
break;
case 3:
printf("\n\n It is 3 !");
break;
default:
printf("\n\n Invalid number !");
}
getch();
}
Output 1 :
Enter any number from 1 to 3 : 3
It is 3 !
Output 2 :
Enter any number from 1 to 3 : 5
Invalid number !
Rules for declaring switch case:
The case label should be integer or character constant.
Each compound statement of a switch case should contain break statement to exit
from case.
Case labels must end with (:) colon.
Advantages of switch case :
Easy to use.
Easy to find out errors.
Debugging is made easy in switch case.
Complexity of a program is minimized.
25. LOOPING STATEMENTS / ITERATIVE STATEMENTS:
A loop is a part of code of a program which is executed repeatedly. A loop is used using
condition. The repetition is done until condition becomes true.
A loop declaration and execution can be done in following ways.
Check condition to start a loop
Initialize loop with declaring a variable.
Executing statements inside loop.
Increment or decrement of value of a variable.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
36 DSTC Junagadh
Types of looping statements:
Basically, the types of looping statements depend on the condition checking mode. Condition
checking can be made in two ways as : Before loop and after loop. So, there are 2(two) types
of looping statements.
Entry controlled loop
Exit controlled loop
1. Entry controlled loop:
In such type of loop, the test condition is checked first before the loop is executed.
Some common examples of this looping statements are :
while loop
for loop
2. Exit controlled loop:
In such type of loop, the loop is executed first. Then condition is checked after block of
statements are executed. The loop executed atleat one time compulsarily.
Some common example of this looping statement is :
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
37 DSTC Junagadh
do-while loop
While loop :
This is an entry controlled looping statement. It is used to repeat a block of statements until
condition becomes true.
Syntax:
while(condition)
{
statements;
increment/decrement;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the loop and executes the block of statements associated with it. At the end of
loop increment or decrement is done to change in variable value. This process continues until
test condition satisfies.
Program :
/* Program to demonstrate while loop.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
clrscr();
a=1;
while(a<=5)
{
printf("\n %d", a);
a++;
}
Printf(“\nLoop Over”);
getch();
}
Output :
1
2
3
4
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
38 DSTC Junagadh
5
Loop Over
Do-While loop :
This is an exit controlled looping statement. Sometimes, there is need to execute a block of
statements first then to check condition. At that time such type of a loop is used. In this, block
of statements are executed first and then condition is checked.
Syntax:
do
{
statements;
(increment/decrement);
}while(condition);
In above syntax, the first the block of statements are executed. At the end of loop, while
statement is executed. If the resultant condition is true then program control goes to evaluate
the body of a loop once again. This process continues till condition becomes true. When it
becomes false, then the loop terminates.
For loop:
This is an entry controlled looping statement. In this loop structure, more than one variable
can be initialized. One of the most important feature of this loop is that the three actions can
be taken at a time like variable initialization, condition checking and increment/decrement.
The for loop can be more concise and flexible than that of while and do-while loops.
Syntax:
for(initialization; test-condition; incre/decre)
{
Statements;
}
In above syntax, the given three expressions are separated by ';' (Semicolon)
Features :
More concise
Easy to use
Highly flexible
More than one variable can be initilized.
More than one increments can be applied.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
39 DSTC Junagadh
More than two conditions can be used.
Example :
/* Program to demonstrate for loop.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
clrscr();
for(i=0; i<5; i++)
{
printf("\n\t %d",i); }
getch();
}
Output :
0
1
2
3
4
26. Break Statement:
Sometimes, it is necessary to exit immediately from a loop as soon as the condition is
satisfied.
When break statement is used inside a loop, then it can cause to terminate from a loop. The
statements after break statement are skipped.
Syntax :
break;
Example:
/* Program to demonstrate break statement.*/
#include <stdio.h>
#include <conio.h>
void main()
{
inti;
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
40 DSTC Junagadh
clrscr();
for(i=1; ; i++)
{
if(i>5)
{
break;
}
printf("\t%d",i);
}
getch();
}
Output :
1 2 3 4 5
27. Continue Statement:
Sometimes, it is required to skip a part of a body of loop under specific conditions. So, C
supports 'continue' statement to overcome this anomaly.
The working structure of 'continue' is similar as that of that break statement but difference is
that it cannot terminate the loop. It causes the loop to be continued with next iteration after
skipping statements in between. Continue statement simply skipps statements and continues
next iteration.
Syntax :
continue;
Program :
/* Program to demonstrate continue statement.*/
#include <stdio.h>
#include <conio.h>
void main()
{
inti;
clrscr();
for(i=1; i<=10; i++)
{
if(i==6)
{
continue;
}
printf("\n\t %d",i);
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
41 DSTC Junagadh
}
getch();
}
Output :
1
2
3
4
5
7
8
9
10
28. Goto Statement:
It is a well known as 'jumping statement.' It is primarily used to transfer the control of
execution to any place in a program. It is useful to provide branching within a loop.
When the loops are deeply nested at that if an error occurs then it is difficult to get exited
from such loops. Simple break statement cannot work here properly. In this situations, goto
statement is used.
Syntax :
goto [Lable];
:
:
Lable:
Program :
/* Program to demonstrate goto statement.*/
#include <stdio.h>
#include <conio.h>
void main()
{
inti=1, j;
clrscr();
while(i<=3)
{
for(j=1; j<=3; j++)
{
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
42 DSTC Junagadh
printf(" * ");
if(j==2)
{
goto stop;
}
}
i = i + 1;
}
stop: printf("\n\n Exited !");
getch();
}
Output :
* *
Exited!
29. FUNCTIONS IN C:
The function is a self-contained block of statements which performs a coherent task of a same
kind.
C program does not execute the functions directly. It is required to invoke or call that
functions. When a function is called in a program then program control goes to the function
body. Then, it executes the statements which are involved in a function body. Therefore, it is
possible to call function whenever we want to process that functions statements.
Types of functions:
There are 2(two) types of functions as:
Built in Function
User Defined Functions
1. Built in Functions:
These functions are also called as 'library functions'. These functions are provided by system.
These functions are stored in library files. e.g.
scanf()
printf()
strcpy
strlwr
strcmp
strlen
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
43 DSTC Junagadh
strcat
2. User Defined Functions:
The functions which are created by user for program are known as 'User defined functions'. It
can be divided into four category:
1) Function with no argument, no return value
2) Function with argument, no return value
3) Function with no argument, with return value
4) Function with argument, with return value
Function with no argument, no argument:
When a function is called we are not passé any argument into it. It simply call by function
name. When function is executing it not return anything to main program.
Syntax:
voidmain()
{
// Function prototype
<return_type><function_name>([<argu_list>]);
// Function Call
<function_name>([<arguments>]);
}
// Function definition
<return_type><function_name>([<argu_list>]);
{
<function_body>;
}
Example:
/* Program to demonstrate function.*/
#include <stdio.h>
#include <conio.h>
void add();
void main()
{
add();
getch();
}
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
44 DSTC Junagadh
void add()
{
int a, b, c;
clrscr();
printf("\n Enter Any 2 Numbers : ");
scanf("%d %d",&a,&b);
c = a + b;
printf("\n Addition is : %d",c);
}
Output :
Enter Any 2 Numbers : 23 6
Addition is : 29
Function with argument, no return value:
When a function is called by passing value of variables then that function is known as
'function call by passing values.'
Syntax:
// Declaration
void<function_name>(<data_type><var_nm>)
// Calls
<function_name>(<var_nm>);
// Definition
void<function_name>(<data_type><var_nm>)
{
<function_body>;
- - - - - - - -;
}
Example:
/* Program to demonstrate function call by passing value.*/
#include <stdio.h>
#include <conio.h>
voiddisplay(int);
void main()
{
int no;
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
45 DSTC Junagadh
clrscr();
printf("\n Enter Number : ");
scanf("%d", &no);
dispaly(no);
getch();
}
void display(int a)
{
printf("\n Number is : %d", a);
}
Output :
Enter Number : 21
Number is : 21
Function with no argument, with return value:
When a function returns value of variables then that function is known as 'function call by
returning values.'
Syntax:
// Declaration
<data_type><function_name>();
// Calls
<variable_of_function>=<function_nm>();
// Definition
<data_type><function_name>()
{
<function_body>;
- - - - - - - -;
return<variable_of_function>;
}
Program :
/* Program to demonstrate function call by returning value.*/
#include <stdio.h>
#include <conio.h>
int number();
void main()
{
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
46 DSTC Junagadh
int no;
clrscr();
no = number();
printf("\n Number is : %d",no);
getch();
}
int number()
{
int no;
printf("\n Enter Number : ");
scanf("%d",&no);
return no;
}
Output :
Enter Number : 5
Number is : 5
Function with argument, with return value:
When a function passes and returns value of variables then that function is known as 'function
call by passing and returning values.'
Example:
/* Program to demonstrate function call by passing and returning value.*/
#include <stdio.h>
#include <conio.h>
int number(int,int);
void main()
{
int a=2,b=3,c;
clrscr();
c= number(2,3);
printf("\n NAnsweris : %d",c);
getch();
}
int number(int x, int y)
{
Int z;
z=x+y;
return z;
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
47 DSTC Junagadh
}
Output :
Answeris :5
Advantages of user define function:
It is easy to use.
Debugging is more suitable for programs.
It reduces the size of a program.
It is easy to understand the actual logic of a program.
Highly suited in case of large programs.
By using functions in a program, it is possible to construct modular and structured
programs.
30. RECURSION (RECURSIVE FUNCTION):
When a function of body calls the same function (function call itself) then it is called as
'recursive function.'
Example:
Recursion()
{
printf("Recursion !");
Recursion();
}
Program :
/* Program to demonstrate function recursion.*/
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
Recursion();
}
Recursion()
{
int no;
printf("\n\n Enter Number : ");
scanf("%d",&no);
if (no==3)
{
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
48 DSTC Junagadh
printf(“Recursion over”);
exit(0);
}
else
{
Recursion();
}
}
Output :
Enter Number : 2
Recursion...
Enter Number : 1
Recursion...
Enter Number : 3
Recursion over
Features of recursion:
There should be at least one if statement used to terminate recursion.
It does not contain any looping statements.
Advantages of recursion:
It is easy to use.
It represents compact programming strctures.
Disadvantages of recursion :
It is slower than that of looping statements because each time function is called.
31. STORAGE CLASS:
'Storage' refers to the scope of a variable and memory allocated by compiler to store that
variable. Scope of a variable is the boundary within which a varible can be used. Storage
class defines the the scope and lifetime of a variable.
From the point view of C compiler, a variable name identifies physical location from a
computer where varaible is stored. There are two memory locations in a computer system
where variables are stored as : Memory and CPU Registers.
Functions of storage class :
To detemine the location of a variable where it is stored ?
Set initial value of a variable or if not specified then setting it to default value.
Defining scope of a variable.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
49 DSTC Junagadh
To determine the life of a variable.
Types of Storage Classes :
Automatic Storage Class
Register Storage Class
Static Storage Class
External Storage Class
Automatic Storage Class:
Keyword : auto
Storage Location : Main memory
Initial Value : Garbage Value
Life : Control remains in a block where it is defined.
Scope : Local to the block in which variable is declared.
Syntax :
auto [data_type] [variable_name];
Example :
autoint a;
Program :
/* Program to demonstrate automatic storage class.*/
#include <stdio.h>
#include <conio.h>
void main()
{
autointi=10;
clrscr();
{
autointi=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);
getch();
}
Output :
20
10
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
50 DSTC Junagadh
Register Storage Class:
Keyword : register
Storage Location : CPU Register
Initial Value : Garbage
Life : Local to the block in which variable is declared.
Scope : Local to the block.
Syntax:
register [data_type] [variable_name];
Example:
registerint a;
When the calculations are done in CPU, then the value of variables are transferred from main
memory to CPU. Calculations are done and the final result is sent back to main memory. This
leads to slowing down of processes.
Register variables occur in CPU and value of that register variable is stored in a register
within that CPU. Thus, it increases the resultant speed of operations. There is no waste of
time, getting variables from memory and sending it to back again.
It is not applicable for arrays, structures or pointers.
It cannot not used with static or external storage class.
Unary and address of (&) cannot be used with these variables as explicitly or implicitly.
Program :
/* Program to demonstrate register storage class.*/
#include <stdio.h>
#include <conio.h>
void main()
{
registerinti=10;
clrscr();
{
registerinti=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
51 DSTC Junagadh
getch();
}
Output :
20
10
Static Storage Class:
Keyword : static
Storage Location : Main memory
Initial Value : Zero and can be initialize once only.
Life : depends on function calls and the whole application or program.
Scope : Local to the block.
Syntax:
static [data_type] [variable_name];
Example:
staticint a;
There are two types of static variables as :
a) Local Static Variable
b) Global Static Variable
Static storage class can be used only if we want the value of a variable to persist between
different function calls.
Program :
/* Program to demonstrate static storage class.*/
#include <stdio.h>
#include <conio.h>
void main()
{
inti;
voidincre(void);
clrscr();
for (i=0; i<3; i++)
incre();
getch();
}
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
52 DSTC Junagadh
voidincre(void)
{
intavar=1;
staticintsvar=1;
avar++;
svar++;
printf("\n\n Automatic variable value : %d",avar);
printf("\t Static variable value : %d",svar);
}
Output :
Automatic variable value : 2 Static variable value : 2
Automatic variable value : 2 Static variable value : 3
Automatic variable value : 2 Static variable value : 4
External Storage Class:
Keyword : extern
Storage Location : Main memory
Initial Value : Zero
Life : Until the program ends.
Scope : Global to the program.
Syntax:
extern [data_type] [variable_name];
Example:
externint a;
The variable access time is very fast as compared to other storage classes. But few registers
are available for user programs.
The variables of this class can be referred to as 'global or external variables.' They are
declared outside the functions and can be invoked at anywhere in a program.
Program :
/* Program to demonstrate external storage class.*/
#include <stdio.h>
#include <conio.h>
externinti=10;
void main()
{
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
53 DSTC Junagadh
inti=20;
void show(void);
clrscr();
printf("\n\t %d",i);
show();
getch();
}
void show(void)
{
printf("\n\n\t %d",i);
}
Output :
20
10
32. ARRAY:
Array is a collection of data/variablewith similar data type. They stored under unique name.
The values in an array is called as 'elements of an array.' These elements are accessed by
numbers called as 'subscripts or index numbers.' Arrays may be of any variable type.
Array is also called as 'subscripted variable.'
Types of an Array:
One / Single Dimensional Array
Two Dimensional Array
Multi Dimensional Array
Single / One Dimensional Array:
The array which is used to represent and store data in a linear form is called as 'single or one
dimensional array.'
Syntax:
<data-type><array_name> [size];
Example:
inta[3] = {2, 3, 5};
charch[20] = "TechnoExam" ;
floatstax[3] = {5003.23, 1940.32, 123.20} ;
Total Size (in Bytes):
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
54 DSTC Junagadh
total size = length of array * size of data type
In above example, a is an array of type integer which has storage size of 3 elements. The total
size would be 3 * 2 = 6 bytes.
* Memory Allocation :
Program :
/* Program to demonstrate one dimensional array.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a[3], i;;
clrscr();
printf("\n\t Enter three numbers : ");
for(i=0; i<3; i++)
{
scanf("%d", &a[i]);
}
printf("\n\n\t Numbers are : ");
for(i=0; i<3; i++)
{
printf("\t %d", a[i]);
}
getch();
}
Output :
Enter three numbers : 9 4 6
Numbers are : 9 4 6
Features:
Array size should be positive number only.
String array always terminates with null character ('\0').
Array elements are countered from 0 to n-1.
Useful for multiple reading of elements (numbers).
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
55 DSTC Junagadh
Disadvantages :
o There is no easy method to initialize large number of array elements.
o It is difficult to initialize selected elements.
Two Dimensional Array:
The array which is used to represent and store data in a tabular form is called as 'two
dimensional array.' Such type of array specially used to represent data in a matrix form.
The following syntax is used to represent two dimensional array.
Syntax:
<data-type><array_nm> [row_subscript][column-subscript];
Example:
inta[3][3];
In above example, a is an array of type integer which has storage size of 3 * 3 matrix. The
total size would be 3 * 3 * 2 = 18 bytes.
It is also called as 'multidimensional array.'
* Memory Allocation :
Program :
/* Program to demonstrate two dimensional array.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a[3][3], i, j;
clrscr();
printf("\n\t Enter matrix of 3*3 : ");
for(i=0; i<3; i++)
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
56 DSTC Junagadh
{
for(j=0; j<3; j++)
{
scanf("%d",&a[i][j]); //read 3*3 array
}
}
printf("\n\t Matrix is : \n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("\t %d",a[i][j]); //print 3*3 array
}
printf("\n");
}
getch();
}
Output :
Enter matrix of 3*3 : 3 4 5 6 7 2 1 2 3
Matrix is :
3 4 5
6 7 2
1 2 3_
Limitations of two dimensional array:
We cannot delete any element from an array.
If we dont know that how many elements have to be stored in a memory in advance,
then there will be memory wastage if large array size is specified.
33. POINTER:
Pointer is a variable which holds the memory address of another variable. Pointers are
represented by '*'. It is a derive data type in C. Pointer returns the value of stored address.
Syntax:
<data_type> *pointer_name;
In above syntax,
* = variable pointer_name is a pointer variable.
pointer_name requires memory location
pointer_name points to a variable of type data type.
How to Use ?
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
57 DSTC Junagadh
int *tot;
Illustration :
int tot = 95;
Figure :
In above example, the statement instructs the system to find out a location for integer variable
quantity and puts the values 95 in that memory location.
Features of Pointer:
Pointer variable should have prefix '*'.
Combination of data types is not allowed.
Pointers are more effective and useful in handling arrays.
It can also be used to return multiple values from a funtion using function arguments.
It supports dynamic memory management.
It reduces complexity and length of a program.
It helps to improve execution speed that results in reducing program execution time.
Program :
/* Program to demonstrate pointer.*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a=10;
int *ptr;
clrscr();
ptr = &a;
printf("\n\t Value of a : %d", a);
scanf("\n\n\t Value of pointer ptr : %d", *ptr);
printf("\n\n\t Address of pointer ptr : %d", ptr);
getch();
}
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
58 DSTC Junagadh
Output :
Value of a : 10
Value of pointer ptr : 10
Address of pointer ptr : -12
34. STRUCTURE:
Structure is user defined data type which is used to store different data under unique name.
Keyword 'struct' is used to declare structure.
The variables which are declared inside the structure are called as 'members of structure'.
Syntax:
structstructure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
}struct_var;
Example :
structemp_info
{
charemp_id[10];
char nm[100];
floatsal;
}emp;
Instances of Structure :
Instances of structure can be created in two ways as,
Instance 1:
structemp_info
{
charemp_id[10];
char nm[100];
floatsal;
}emp;
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
59 DSTC Junagadh
Instance 2:
structemp_info
{
charemp_id[10];
char nm[100];
floatsal;
};
structemp_infoemp;
In above example, emp_info is a simple structure which consists of stucture members as
Employee ID(emp_id), Employee Name(nm), Employee Salary(sal).
Aceessing Structure Members :
Structure members can be accessed using member operator '.' . It is also called as 'dot
operator' or 'period operator'.
structure_var.member;
Program :
/* Program to demonstrate structure.*/
#include <stdio.h>
#include <conio.h>
structcomp_info
{
char nm[100];
charaddr[100];
}info;
void main()
{
clrscr();
printf("\n Enter Company Name : ");
gets(info.nm);
printf("\n Enter Address : ");
gets(info.addr);
printf("\n\n Company Name : %s",info.nm);
printf("\n\n Address : %s",info.addr);
getch();
}
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
60 DSTC Junagadh
Output :
Enter Company Name :TCS
Enter Address :Gandhinagar
Company Name :TCS
Address :Gandhinagar
Array in Structures:
Sometimes, it is necessary to use structure members with array.
Program :
/* Program to demonstrate array in structures.*/
#include <stdio.h>
#include <conio.h>
struct result
{
intrno, mrks[5];
char nm;
}res;
void main()
{
inti,total;
clrscr();
total = 0;
printf("\n\t Enter Roll Number : ");
scanf("%d",&res.rno);
printf("\n\t Enter Marks of 3 Subjects : ");
for(i=0;i<3;i++)
{
scanf("%d",&res.mrks[i]);
total = total + res.mrks[i];
}
printf("\n\n\t Roll Number : %d",res.rno);
printf("\n\n\t Marks are :");
for(i=0;i<3;i++)
{
printf(" %d",res.mrks[i]);
}
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
61 DSTC Junagadh
printf("\n\n\t Total is : %d",total);
getch();
}
Output :
Enter Roll Number : 1
Enter Marks of 3 Subjects : 63 66 68
Roll Number : 1
Marks are : 63 66 68
Total is : 197
Structure with Array:
We can create structures with array for ease of operations in case of getting multiple same
fields.
Program :
/* Program to demonstrate Structure With Array.*/
#include <stdio.h>
#include <conio.h>
structemp_info
{
intemp_id;
char nm[50];
}emp[2];
void main()
{
inti;
clrscr();
for(i=0;i<2;i++)
{
printf("\n\n\t Enter Employee ID : ");
scanf("%d",&emp[i].emp_id);
printf("\n\n\t Employee Name : ");
scanf("%s",emp[i].nm);
}
for(i=0;i<2;i++)
{
printf("\n\t Employee ID : %d",emp[i].emp_id);
printf("\n\t Employee Name : %s",emp[i].nm);
}
getch();
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
62 DSTC Junagadh
}
Output :
Enter Employee ID : 1
Employee Name : ABC
Enter Employee ID : 2
Employee Name : XYZ
Employee ID : 1
Employee Name : ABC
Employee ID : 2
Employee Name : XYZ
Structures within Structures (Nested Structures):
Structures can be used as structures within structures. It is also called as 'nesting of
structures'.
Syntax:
structstructure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
structstructure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
Example :
structstud_Res
{
intrno;
char nm[50];
charstd[10];
structstud_subj
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
63 DSTC Junagadh
{
charsubjnm[30];
int marks;
}subj;
}result;
In above example, the structure stud_Res consists of stud_subj which itself is a structure with
two members. Structure stud_Res is called as 'outer structure' while stud_subj is called as
'inner structure.' The members which are inside the inner structure can be accessed as follow:
result.subj.subjnm
result.subj.marks
Program:
/* Program to demonstrate nested structures*/
#include <stdio.h>
#include <conio.h>
structstud_Res
{
intrno;
charstd[10];
structstud_Marks
{
charsubj_nm[30];
intsubj_mark;
}marks;
}result;
void main()
{
clrscr();
printf("\n\t Enter Roll Number : ");
scanf("%d",&result.rno);
printf("\n\t Enter Standard : ");
scanf("%s",result.std);
printf("\n\t Enter Subject Code : ");
scanf("%s",result.marks.subj_nm);
printf("\n\t Enter Marks : ");
scanf("%d",&result.marks.subj_mark);
printf("\n\n\t Roll Number : %d",result.rno);
printf("\n\n\t Standard : %s",result.std);
printf("\nSubject Code : %s",result.marks.subj_nm);
printf("\n\n\t Marks : %d",result.marks.subj_mark);
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
64 DSTC Junagadh
getch();
}
Output :
Enter Roll Number : 1
Enter Standard : MCA(Sci)-I
Enter Subject Code : SUB001
Enter Marks : 63
Roll Number : 1
Standard : MCA(Sci)-I
Subject Code : SUB001
Marks : 63
35. STRING HANDLING IN C:
String :
A string is a collection of characters. Strings are always enlosed in double quotes as
"string_constant".
Strings are used in string handling operations such as,
Counting the length of a string.
Comparing two strings.
Copying one string to another.
Converting lower case string to upper case.
Converting upper case string to lower case.
Joining two strings.
Reversing string.
Declaration :
The string can be declared as follow :
Syntax:
charstring_nm[size];
Example:
char name[50];
String Structure :
When compiler assigns string to character array then it automatically supplies null character
('\0') at the end of string. Thus, size of string = original length of string + 1.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
65 DSTC Junagadh
char name[7];
name = "TECHNO"
Read Strings :
To read a string, we can use scanf() function with format specifier %s.
char name[50];
scanf("%s",name);
The above format allows to accept only string which does not have any blank space, tab, new
line, form feed, carriage return.
Write Strings :
To write a string, we can use printf() function with format specifier %s.
char name[50];
scanf("%s",name);
printf("%s",name);
Some of the standard member functions of string.h header files are:
strcpy(s1,s2); Copies string s2 into string s1.
strcat(s1,s2); Concatenates string s2 onto the end of string s1.
strlen(s1); Returns the length of string s1.
strcmp(s1,s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1,ch); Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1,s2); Returns a pointer to the first occurrence of string s2 in string s1.
strupr(s1); Convert string s1 into uppercase letter.
strlwr(s1); Convert string s1 into lowercase letter.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
66 DSTC Junagadh
Program :
/* Program to demonstrate string.h header file working.*/
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
charstr[50],str2[50];
clrscr();
printf("\n\t Enter your string1: ");
gets(str1);
printf("\n\t Enter your string2: ");
gets(str2);
printf("\nLower case of string: %s",strlwr(str1));
printf("\nUpper case of string: %s",strupr(str1));
printf("\nReverse of string: %s",strrev(str1));
printf("\nLength of String: %d",strlen(str1));
printf("\nConcat string1 with string2 of String: %d",strcat (str2,str1));
getch();
}
Output :
Enter your string1 :Programming
Enter your string2 : C
Lower case of string: programming
Upper case of string: PROGRAMMING
Reverse of string: gnimmargorP
Length of String: 11
Concat string1 with string2 of String: CProgramming
36. HEADER FILE IN C:
Header file contains different predefined functions, which are required to run the program.
All header files should be included explicitly before main ( ) function.
It allows programmers to seperate functions of a program into reusable code or file. It
contains declarations of variables, subroutines. If we want to declare identifiers in more than
one source code file then we can declare such identifiers in header file. Header file has
extension like '*.h'. The prototypes of library functions are gathered together into various
categories and stored in header files.
E.g. All prototypes of standard input/output functions are stored in header file 'stdio.h' while
console input/output functions are stored in 'conio.h'.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
67 DSTC Junagadh
The header files can be defined or declared in two ways as
Method 1 : #include "header_file-name"
Method 2 : #include <header_file-name>
Method 1 is used to link header files in current directory as well as specified directories using
specific path. The path must be upto 127 characters. This is limit of path declaration. Method
2 is used to link header files in specified directories only.
Standard Header Files:
Followings are the some commonly used header files in C programming:
Stdio.h
Conio.h
String.h
Math.h
Ctype.h
Process.h
Graphics.h
37. PREPROCESSORS:
The C Preprocessor is not part of the compiler, but is a separate step in the compilation
process. In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct
compiler to do required pre-processing before actual compilation. We'll refer to the C
Preprocessor as the CPP.
All preprocessor commands begin with a pound symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in first column.
Following section lists down all important preprocessor directives:
Directive Description
#define Substitutes a preprocessor macro
#include Inserts a particular header from another file
#undef Undefined a preprocessor macro
#ifdef Returns true if this macro is defined
#ifndef Returns true if this macro is not defined
#if Tests if a compile time condition is true
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
68 DSTC Junagadh
#else The alternative for #if
#elif #else an #if in one statement
#endif Ends preprocessor conditional
#error Prints error message on stderr
#pragma Issues special commands to the compiler, using a standardized method
38. FILE I/O
A file represents a sequence of bytes, does not matter if it is a text file or binary file. C
programming language provides access on high level functions as well as low level (OS
level) calls to handle file on your storage devices. This chapter will take you through
important calls for the file management.
Opening Files:
You can use the fopen( ) function to create a new file or to open an existing file, this call will
initialize an object of the type FILE, which contains all the information necessary to control
the stream. Following is the prototype of this function call:
FILE *fopen(constchar* filename,constchar* mode );
Here, filename is string literal which you will use to name your file and access mode can
have one of the following values:
Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing, if it does not exist then a new file is created. Here your
program will start writing content from the beginning of the file.
a Opens a text file for writing in appending mode, if it does not exist then a new file is
created. Here your program will start appending content in the existing file content.
r+ Opens a text file for reading and writing both.
w+ Opens a text file for reading and writing both. It first truncate the file to zero length if
it exists otherwise create the file if it does not exist.
a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The
reading will start from the beginning but writing can only be appended.
If you are going to handle binary files then you will use below mentioned access modes
instead of the above mentioned:
"rb","wb","ab","rb+","r+b","wb+","w+b","ab+","a+b"
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
69 DSTC Junagadh
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is:
intfclose( FILE *fp);
The fclose( ) function returns zero on success, or EOF if there is an error in closing the file.
This function actually, flushes any data still pending in the buffer to the file, closes the file,
and releases any memory used for the file. The EOF is a constant defined in the header file
stdio.h.
There are various functions provide by C standard library to read and write a file character by
character or in the form of a fixed length string. Let us see few of the in the next section.
Writing a File
Following is the simplest function to write individual characters to a stream:
intfputc(int c, FILE *fp);
The function fputc() writes the character value of the argument c to the output stream
referenced by fp. It returns the written character written on success otherwise EOF if there is
an error. You can use the following functions to write a null-terminated string to a stream:
intfputs(constchar*s, FILE *fp);
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-
negative value on success, otherwise EOF is returned in case of any error. You can use
intfprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.
Reading a File
Following is the simplest function to read a single character from a file:
intfgetc( FILE *fp);
The fgetc() function reads a character from the input file referenced by fp. The return value is
the character read, or in case of any error it returns EOF. The following functions allow you
to read a string from a stream:
char*fgets(char*buf,int n, FILE *fp);
The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It
copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have
read the maximum number of characters, then it returns only the characters read up to that
point including new line character. You can also use intfscanf(FILE *fp, const char
*format, ...) function to read strings from a file but it stops reading after the first space
character encounters.
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
70 DSTC Junagadh
39. TYPE CASTING
Type casting is a way to convert a variable from one data type to another data type. For
example, if you want to store a long value into a simple integer then you can type cast long to
int. You can convert values from one type to another explicitly using the cast operator as
follows:
(type_name) expression
Integer Promotion
Integer promotion is the process by which values of integer type "smaller" than int or
unsigned int are converted either to int or unsigned int. Consider an example of adding a
character in an int:
#include<stdio.h>
main()
{
inti=17;
char c ='c';/* ascii value is 99 */
int sum;
sum=i+ c;
printf("Value of sum : %d\n", sum );
}
When the above code is compiled and executed, it produces the following result:
Value of sum : 116
Here, value of sum is coming as 116 because compiler is doing integer promotion and
converting the value of 'c' to ascii before peforming actual addition operation.
Usual Arithmetic Conversion
The usual arithmetic conversions are implicitly performed to cast their values in a common
type. Compiler first performs integer promotion, if operands still have different types then
they are converted to the type that appears highest in the following hierarchy:
Faculty of Degree Engineering - 083 Department of CE / IT – 07 / 16
Programming for Problem Solving
71 DSTC Junagadh
The usual arithmetic conversions are not performed for the assignment operators, nor for the
logical operators && and ||. Let us take following example to understand the concept:
#include<stdio.h>
main()
{
inti=17;
char c ='c';/* ascii value is 99 */
float sum;
sum=i+ c;
printf("Value of sum : %f\n", sum );
}
When the above code is compiled and executed, it produces the following result:
Value of sum : 116.000000