C Programming Lecture Notes (Unit-1,2,3)
C Programming Lecture Notes (Unit-1,2,3)
C Programming Lecture Notes (Unit-1,2,3)
10. Iteration and loops: use of while, do while and for loops, 47 M3
multiple loop variables, use of break and (Loops &
11. Functions- Introduction, types of functions, functions with array, 54 Functions)
passing parameters to functions, Call by value, call by reference
12. Recursion 60
13. Arrays- Array notation and representation, manipulating array 63
elements, using multi dimensional arrays, passing arrays to
functions M4
14. Basic Algorithms: Basic Sorting Algorithms (Bubble, Insertion 73 (Arrays &
and Selection) Basic
15. Character arrays and strings 82 Algorithms)
16. Structure, Use of pointers in self-referential structures Structure 87
Array of structures
17. Union, enumeration 89
18. Notion of order of complexity 91
19. Pointers- Introduction, declaration, applications 93 M5
20. Introduction to dynamic memory allocation (malloc, calloc, 97 ( Pointer& File
realloc, free) Handling)
21. Notion of linked list (no implementation) 101
22. File handling: File I/O functions 103
23. Standard C preprocessors, defining and calling macros, 106
command-line arguments Conditional compilation, passing
values to the compiler
24. Important Programs with solution 113
25. Questions Bank 142
INTRODUCTION TO COMPUTERS
Any programming language is implemented on a computer. Right from its inception, to the present
day, all computer system (irrespective of their shape & size) perform the following 5 basic
operations. It converts the raw input data into information, which is useful to the users.
1. Input: It is the process of entering data & instructions to the computer system.
2. Storing: The data & instructions are stored for either initial or additional processing, as & when
required.
3. Processing: It requires performing arithmetic or logical operation on the saved data to convert it into
useful information.
4. Output: It is the process of producing the output data to the end user.
5. Controlling: The above operations have to be directed in a particular sequence to be completed.
Based on these 5 operations, we can sketch the block diagram of a computer.
Input Unit:
We need to first enter the data & instruction in the computer system, before any computation
begins. This task is accomplished by the input devices. (The data accepted is in a human readable
form. The input device converts it into a computer readable form.
Input device: The input device is the means through which data and instructions enter in a
computer.
1. Camera - most cameras like this are used during live conversations. The camera transmits a
picture from one computer to another, or can be used to record a short video.
3. Keyboard - The keyboard is a way to input letters or numbers into different applications or
programs. A keyboard also has special keys that help operate the computer.
4. Mouse - The mouse is used to open and close files, navigate web sites, and click on a lot of
commands (to tell the computer what to do) when using different applications.
5. Microphone - A microphone is used to record sound. The sound is then saved as a sound file
on the computer.
6. Scanner - A scanner is used to copy pictures or other things and save them as files on the
computer.
7. Joystick - A joystick is used to move the cursor from place to place, and to click on various
items in programs. A joystick is used mostly for computer games.
8. Bar Code Scanner - A bar code scanner scans a little label that has a bar code on it. The
information is then saved on the computer. Bar code scanners are used in libraries a lot.
Storage Unit:
The data & instruction that are entered have to be stored in the computer. Similarly, the end results
& the intermediate results also have to be stored somewhere before being passed to the output unit.
The storage unit provides solution to all these issues. This storage unit is designed to save the initial
data, the intermediate result & the final result. This storage unit has 2 units: Primary storage &
Secondary storage.
Primary Storage:
The primary storage, also called as the main memory, holds the data when the computer is currently
on. As soon as the system is switched off or restarted, the information held in primary storage
disappears (i.e. it is volatile in nature). Moreover, the primary storage normally has a limited
storage capacity, because it is very expensive as it is made up of semiconductor devices.
Hard disk.
A hard disk consists of one or more rigid metal plates coated with a metal oxide
material that allows data to be magnetically recorded on the surface of the platters. The hard disk
platters spin at a high rate of speed, typically 5400 to 7200 revolutions per minute (RPM).Storage
capacities of hard disks for personal computers range from 10 GB to 120 GB (one billion bytes are
called a gigabyte).
CD:
Compact Disk (CD) is portable disk having data storage capacity between 650-700 MB. It can hold
large amount of information such as music, full-motion videos, and text etc. It contains digital
information that can be read, but cannot be rewritten. Separate drives exist for reading and writing
Volatile Memory: This loses its data, when power is switched off.
Non-Volatile Memory: This is a permanent storage and does not lose any data when power
is switched off.
Memory Hierarchy
The total memory capacity of a computer can be visualized by hierarchy of components. The
memory hierarchy system consists of all storage devices contained in a computer system from
the slow Auxiliary Memory to fast Main Memory and to smaller Cache memory.
Auxillary memory access time is generally 1000 times that of the main memory, hence it is at
the bottom of the hierarchy.
The main memory occupies the central position because it is equipped to communicate directly
with the CPU and with auxiliary memory devices through Input/output processor (I/O).
When the program not residing in main memory is needed by the CPU, they are brought in from
auxiliary memory. Programs not currently needed in main memory are transferred into auxiliary
memory to provide space in main memory for other programs that are currently in use.
OutputUnit:
The job of an output unit is just the opposite of an input unit. It accepts the results produced by the
computer in coded form. It converts these coded results to human readable form. Finally, it displays
the converted results to the outside world with the help of output devices ( Eg :monitors, printers,
projectors etc..).
Output device:
Device that lets you see what the computer has accomplished.
1. Monitor - A monitor is the screen on which words, numbers, and graphics can be seem. The
monitor is the most common output device.
2. Compact Disk - Some compact disks can be used to put information on. This is called
burning information to a CD. NOTE: A CD can also be an input device.
3. Printer - A printer prints whatever is on the monitor onto paper. Printers can print words,
numbers, or pictures.
4. Speaker - A speaker gives you sound output from your computer. Some speakers are built
into the computer and some are separate.
5. Headphones - Headphones give sound output from the computer. They are similar to
speakers, except they are worn on the ears so only one person can hear the output at a time.
System Software-
System software are a set of programs, responsible for running the computer, controlling various
operations of computer systems and management of computer resources. They act as an interface
between the hardware of the computer & the application software. E.g.: Operating System.
Application software
is a set of programs designed to solve a particular problem for users. It allows the end user to do
something besides simply running the hardware. E.g.: Web Browser, Gaming Software, etc.
Computer Classification:
Computers can be generally classified by size and power as follows, though there is considerable
overlap:
a. Personal computer: a small, single-user computer based on a microprocessor. In addition to
the microprocessor, a personal computer has a keyboard for entering data, a monitor for displaying
information, and a storage device for saving data.
b. Workstation: a powerful, single-user computer. A workstation is like a personal computer,
but it has a more powerful microprocessor and a higher-quality monitor.
c. Minicomputer: a multi-user computer capable of supporting from 10 to hundreds of users
simultaneously.
d. Mainframe: a powerful multi-user computer capable of supporting many hundreds or
thousands of users simultaneously.
e. Supercomputer: an extremely fast computer that can perform hundreds of millions of
instructions per second.
Notes
Definition: An operating system (OS) is a collection of software that manages computer hardware
resources and provides common services for computer programs.
Definition:(1)As an interface (2) As an environment (3) As a system software
(ii)Interactive System:
An operating system that allows users to run interactive programs. Pretty much all operating
systems that are on PCs are interactive OS.
(v)Multiprocessor system:
1. Multiprocessor System consists of a set of processors that shares a set of physical memory
blocks over an interconnection network.
2. Controls and manage the hardware and software resources such that user can view the entire
system as a powerful uniprocessor system.
(vi)Multiuser System:
1. Multi-user is a term that defines an operating system or application software that allows
concurrent access by multiple users of a computer.
2. Time-sharing systems are multi-user systems. Most batch processing systems for mainframe
computers may also be considered "multi-user", to avoid leaving the CPU idle while it waits for I/O
operations to complete.
Microsoft Windows
Windows is a meta family of graphical operating systems developed, marketed, and sold by
Microsoft.
Active Windows families include Windows NT, Windows Embedded and Windows Phone;
these may encompass subfamilies, e.g. Windows Embedded Compact (Windows CE) or
Windows Server. Defunct Windows families include Windows 9x; Windows 10 Mobile is an
active product, unrelated to the defunct family Windows Mobile.
Microsoft introduced an operating environment named Windows on November 20, 1985, as a
graphical operating system shell for MS-DOS in response to the growing interest in graphical
user interfaces (GUIs).
Version history-Windows 1.0, Windows 2.0, and Windows 2.1xWindows 3.xWindows
9xWindows NT Windows XPWindows VistaWindows 7Windows 8 and
8.1Windows 10
Basic Features of Windows Operating System-
1) Windows Easy Transfer 2) Windows Anytime Upgrade3) Windows Basics 4) Searching and
Organizing 5) Parental Controls 6) Ease of Access Center 7) Default Programs 8) Remote
Desktop Connection
Linux
The Unix operating system was conceived and implemented in 1969 at AT&T's Bell
Laboratories in the United States by Ken Thompson, Dennis Ritchie, Douglas McIlroy, and
Joe Ossanna.
Linux Operating System has primarily three components
Kernel − Kernel is the core part of Linux. It is responsible for all major activities of this
operating system. It consists of various modules and it interacts directly with the
underlying hardware. Kernel provides the required abstraction to hide low level hardware
details to system or application programs.
System Library − System libraries are special functions or programs using which
application programs or system utilities accesses Kernel's features. These libraries
implement most of the functionalities of the operating system and do not requires kernel
module's code access rights.
System Utility − System Utility programs are responsible to do specialized, individual
level tasks.
Android
What is Android-One of the most widely used mobile OS these days is ANDROID.
Android is a software bunch comprising not only operating system but also middleware
and key applications. Android Inc was founded in Palo Alto of California, U.S. by Andy
Rubin, Rich miner, Nick sears and Chris White in 2003. Later Android Inc. was acquired
by Google in 2005. After original release there have been number of updates in the
original version of Android
Applications
These are the basics of Android applications:
• Android applications are composed of one or more application components (activities,
services, content providers, and broadcast receivers)
• Each component performs a different role in the overall application behavior, and each
one can be activated individually (even by other applications)
• The manifest file must declare all components in the application and should also declare
all application requirements, such as the minimum version of Android required and any
hardware configurations required
• Non-code application resources (images, strings, layout files, etc.) should include
alternatives for different device configurations (such as different strings for different
languages)
COMPUTER LANGUAGES
Languages are a means of communication. Normally people interact with each other
through a language. On the same pattern, communication with computers is carried out
through a language. This language is understood both by the user and the machine.
Just as every language like English, Hindi has its own grammatical rules; every computer
language is also bounded by rules known as syntax of that language. The user is bound by
that syntax while communicating with the computer system.
High Level Language: Low level language requires extensive knowledge of the hardware
since it is machine dependent. To overcome this limitation, high level language has been
evolved which uses normal English, which is easy to understand to solve any problem. High
level languages are computer independent and programming becomes quite easy and
simple. Various high level languages are given below:
BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easy to learn
general purpose language. Mainly used in microcomputers in earlier days.
COBOL (Common Business Oriented language): A standardized language used for
commercial applications.
FORTRAN (Formula Translation): Developed for solving mathematical and scientific
problems. One of the most popular languages among scientific community.
C: Structured Programming Language used for all purpose such as scientific application,
commercial application, developing games etc.
Compiler: The software that reads a program written in high level language and translates it into an
equivalent program in machine language is called as compiler. The program written by the
programmer in high level language is called source program and the program generated by the
compiler after translation is called as object program.
Interpreter: it also executes instructions written in a high level language. Both complier & interpreter
have the same goal i.e. to convert high level language into binary instructions, but their method of
execution is different. The complier converts the entire source code into machine level program,
while the interpreter takes 1 statement, translates it, executes it & then again takes the next
statement.
Assembler: The software that reads a program written in assembly language and translates it into an
equivalent program in machine language is called as assembler.
Linker: A linker or link editor is a computer program that takes one or more object files generated by a
compiler and combines them into a single executable file, library file, or another object file.
Algorithm
Characteristics of algorithm: Input, output, definiteness, finiteness, effectiveness.
Algorithm is a step-by-step solution to a problem. Example: one algorithm for adding
two digit numbers is "add the units, add the tens and combine the answers"
"Algorithm" is named after the 9th century Persian mathematician Al-Khwarizmi.
Example: For factorial
1. Start
2. Input number N (for which we want to calculate factorial.)
3. Let M=1 and F=1.
4. F=F*M.
5. Is M=N?
6. If NO then M=M+1 and go to step 3.
7. If YES then output F
8. End
Flow Chart:
A flowchart is a type of diagram that represents an algorithm or process, showing the steps as
boxes of various kinds, and their order by connecting these with arrows. This diagrammatic
representation can give a step-by-step solution to a given problem.
STRUCTURE OF A C PROGRAM
The structure of a C program is a protocol (rules) to the programmer, which he has to follow while
writing a C program. The general basic structure of C program is shown in the figure below.
Types of error
a) Syntax Errors: Errors in syntax (grammar) of the program.
b) Semantic Errors: Errors in the meaning of the program.
c) Logical Errors: Errors in logic of the program. Compiler cannot diagnose these kinds of
errors.
d) Runtime Errors: i) Insufficient memory ii)Floating exception
e) Compile Errors: i) parse error ii)implicit declaration iii) no matching function iv)Unsatisfied
symbols v)incomplete type vi)cannot call member function vii)bad argument viii)cannot
allocate an object
ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with
programming, we should be acquainted with the basic elements that build the language.
Character Set
Communicating with a computer involves speaking the language the computer understands. In
C, various characters have been given to communicate. Character set in C consists of;
Digits 0-9
Keywords
Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a
new meaning to the keyword, which is not allowed by the computer. There are only 32
keywords available in C. Below figure gives a list of these keywords for your ready
reference.
Identifier
In the programming language C, an identifier is a combination of alphanumeric characters, the
first being a letter of the alphabet or an underline, and the remaining being any letter of the
alphabet, any numeric digit, or the underline.
Two rules must be kept in mind when naming identifiers.
1. The case of alphabetic characters is significant. Using "INDEX" for a variable is not the
same as using "index" and neither of them is the same as using "InDeX" for a variable. All
three refer to different variables.
2. As C is defined, up to 32 significant characters can be used and will be considered
significant by most compilers. If more than 32 are used, they will be ignored by the
compiler.
VARIABLES
Variables are names that are used to store values. It can take different values but one at a
time. A data type is associated with each variable & it decides what values the variable can
take. Variable declaration requires that you inform C of the variable's name and data type.
Syntax – data type variable name;
Eg:int page_no;
char grade;
float salary;
long y;
Declaring Variables:
There are two places where you can declare a variable:
After the opening brace of a block of code (usually at the top of a function)
Before a function name (such as before main() in the program) Consider various examples:
Initialization of Variables
When a variable is declared, it contains undefined value commonly known as garbage value. If
we want we can assign some initial value to the variables during the declaration itself. This
is called initialization of the variable.
Eg-int pageno=10;
Expressions
An expression consists of a combination of operators, operands, variables & function calls. An
expression can be arithmetic, logical or relational. Here are some expressions:
a+b – arithmetic operation
a>b- relational operation a
== b - logical operation
func (a,b) – function call
Statements
Statements are the primary building blocks of a program. A program is a series of statements
with some necessary punctuation. A statement is a complete instruction to the computer. In
C, statements are indicated by a semicolon at the end. a semicolon is needed to identify
instructions that truly are statements.
INPUT-OUTPUT IN C
When we are saying Input that means we feed some data into program. This can be given in
the form of file or from command line. C programming language provides a set of built-in
functions to read given input and feed it to the program as per requirement.
FORMATTED INPUT-OUTPUT
Data can be entered & displayed in a particular format. Through format specifications, better
presentation of results can be obtained.
Generally there are two kinds of locations in a computer where such a value can be present, these
are Memory and CPU registers. The storage class of a particular variable determines in which of
the above two locations the variable‘s value is stored.
There are four properties by which storage class of a variable can be recognized. These are scope,
default initial value, scope and life.
A variable‘s storage class reveals the following things about a variable
(i) Where the variable is stored.
(ii) What is the initial value of the variable if the value of the variable is not specified?
(iii) What is the scope of the variable (To which function or block the variable is available).
(iv) What is the life of particular variable (Up to what extent the variable exists in a program).
In c there are four types of storage class. They are: 1. Auto 2. Register 3.
Static 4. Extern
Storage class is modifier or qualifier of data types which decides: In which area of memory
a particular variable will be stored? What is scope of variable? What is visibility of
variable?
Scope of a variable in c: Meaning of scope is to check either variable is alive or dead. Alive
means data of a variable has not destroyed from memory. Up to which part or area of the
program a variable is alive, that area or part is known as scope of a variable. There are
four type of scope in c:
1. Block scope.
2. Function scope.
3. File scope.
3. Program scope.
In the above program, variable a was used frequently as a loop counter so the variable a is defined as a
register variable. Register is a not a command but just a request to the compiler to allocate the
memory for the variable into the register. If free registers are available than memory will be
allocated in to the registers. And if there are no free registers then memory will be allocated in the
RAM only (Storage is in memory i.e. it will act as automatic variable).
Every type of variables can be stored in CPU registers. Suppose the microprocessor has 16 bit registers
then they can‘t hold a float or a double value which requires 4 and 8 bytes respectively.
Output:10 11 12
Here in the above program the output is 10, 11, 12, because if a variable is declared as static then it is
initialized only once and that variable will never be initialized again. Here variable k is declared as
static, so when test() is called for the first time k value is initialized to 10 and its value is
incremented by 1 and becomes 11. Because k is static its value persists. When test() is called for the
second time k is not reinitialized to 10 instead its old value 11 is available. So now 11 is get printed
and it value is incremented by 1 to become 12. Similarly for the third time when test() is called
12(Old value) is printed and its value becomes 13 when executes the statement ‗k++;‘
So the main difference between automatic and static variables is that static variables are initialized to
zero if not initialized but automatic variables contain an unpredictable value(Garbage Value) if not
initialized and static variables does not disappear when the function is no longer active , their value
persists, i.e. if the control comes back to the same function again the static variables have the same
values they had last time.
General advice is avoid using static variables in a program unless you need them, because their values
are kept in memory when the variables are not active which means they occupies space in memory
that could otherwise be used by other variables.
So if a variable is to be used by many functions and in different files can be declared as external
variables. The value of an uninitialized external variable is zero. The declaration of an external
variable declares the type and name of the variable, while the definition reserves storage for the
variable as well as behaves as a declaration. The keyword extern is specified in declaration but not
in definition. Now look at the following four statements
1. auto int a;
2. register int b;
3. static int c;
4. extern int d;
Out of the above statements first three are definitions where as the last one is a declaration. Suppose
there are two files and their names are File1.c and File2.c respectively. Their contents are as
follows:
File1.c
int n=10;
void hello()
{
printf(―Hello‖);
}
File2.c
extern int n;
extern void hello();
void main()
{printf(―%d‖, n);
hello();}
In the above program File1.obj+ File2.obj=File2.exe and in File2.c value of n will be 10.
Topic: Arithmetic expressions and precedence: Operators and expression using numeric
and relational operators, mixed operands, type conversion, logical operators, bit
operations, assignment operator, operator precedence and associability.
OPERATORS-An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. C language is rich in built-in operators and provides the following
types of operators: Arithmetic Operators, Relational Operators, Logical Operators, Bitwise
Operators, Assignment Operators, Increment and decrement operators, Conditional
operators, Misc Operators
% B % A will give 0
Division
== Checks if the values of two operands are equal or not, if yes (A == B) is not
then condition becomes true. true.
> Checks if the value of left operand is greater than the value (A > B) is not
of right operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is not
the value of right operand, if yes then condition becomes true.
true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand, if yes then condition becomes true.
Logical Operators:
Assume variable A holds 1 and variable B holds 0, then:
Operator Description Example
&&
nonzero, then condition becomes true. false.
|| (A || B) is true.
non-zero, then condition becomes true.
!(A && B) is
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
& Binary AND Operator copies a bit to the result if it (A & B) will give 12,
exists in both operands. which is 0000 1100
^ Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49,
one operand but not both. which is 0011 0001
~ Binary Ones Complement Operator is unary and has (~A ) will give -61, which
the effect of ‗flipping‘ bits. is 1100 0011 in 2‘s
complement form.
<< Binary Left Shift Operator. The left operands value A << 2 will give 240
is moved left by the number of bits specified by the which is 1111 0000
right operand.
>> Binary Right Shift Operator. The left operands A >> 2 will give 15
value is moved right by the number of bits specified which is 0000 1111
by the right operand.
Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e, executes different statements
according to test condition whether it is either true or false.
Syntax of conditional operators;
conditional_expression?expression1:expression2
If the test condition is true (that is, if its value is non-zero), expression1 is returned and if false
expression2 is returned.
y = ( x> 5 ? 3 : 4 ) ;this statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.
Misc Operators:
There are few other operators supported by c language.
Operator Description Example
& Returns the address of a variable. &a; will give actual address of
the variable.
Type casting /type conversion 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 typecast long to int.
You can convert values from one type to another explicitly using the cast operator. There
are two types of type casting in c languages that are implicit conversions and Explicit
Conversions.
New data type should be mentioned before the variable name or value in brackets which
to be typecast.
C TYPE CASTING EXAMPLE PROGRAM:
In the below C program, 7/5 alone will produce integer value as 1.So, type cast is done
before division to retain float value (1.4).
#include <stdio.h>
int main ()
{
float x;
x = (float) 7/5;
printf(―%f‖,x);
}
Output:
1.400000
WHAT IS TYPE CASTING IN C LANGUAGE?
Converting an expression of a given type into another type is known as type casting. It is best
practice to convert lower data type to higher data type to avoid data loss.Data will be
truncated when the higher data type is converted to lower. For example, if a float is
converted to int, data which is present after the decimal point will be lost.
There are two types of type casting in c language.
TYPES OF TYPECASTING IN C
Types of type casting in C Programming
Implicit Conversion
Explicit Conversion
1. IMPLICIT CONVERSION
Implicit conversions do not require any operator for converted. They are automatically
performed when a value is copied to a compatible type in the program.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion
printf(―implicit value is %d‖,p);
getch();}
Output:-
implicit value is 20.
a) If statement
Syntax:
if(boolean_expression)
{ /* statement(s) will execute if the Boolean expression is true */
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If boolean expression evaluates to false then the first set of code after the end of the if
statement (after the closing curly brace) will be executed. C programming language assumes any
non-zero and non-null values as true and if it is either zero or null then it is assumed as false
value.
Flow Diagram:
Example:
Example:
#include <stdio.h>
main ()
{ int a = 100;
if( a < 20 )
{ Printf("a is less than 20\n" );
}
else
{ Printf("a is not less than 20\n" );
} Printf("value of a is : %d\n", a);}
Example:
main ()
{ char grade = 'B';
switch(grade)
{ case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
} printf("Your grade is %c\n", grade );
}
When the above code is compiled and executed, it produces following result:
Well done
Your grade is B
Topic: Iteration and loops: use of while, do while and for loops, multiple loop variables,
use of break and
Program Loops and Iteration A loop statement allows us to execute a statement or group of statements
multiple times and following is the general from of a loop statement in most of the programming
languages:
(ii) Continue statement: Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating. The continue statement in C programming
language works somewhat like the break statement. Instead of forcing termination,
however, continue forces the next iteration of the loop to take place, skipping any code in
between. Syntax: continue;
Flow Diagram:
Example:
#include <stdio.h>
main ()
{ int a = 10;
do
{ if( a == 15)
{ a = a + 1;
continue;
(iii) Goto Statement: Transfers control to the labeled statement. Though it is not advised to
use goto statement in your program A goto statement in C programming language
provides an unconditional jump from the goto to a labeled statement in the same function.
Syntax:
goto label;
label: statement;
Flow Diagram:
Example:
#include <stdio.h>
main ()
{ int a = 10;
LOOP: do
{ if( a == 15)
{ a = a + 1;
goto LOOP;
}
FUNCTION
MONOLITHIC VS MODULAR PROGRAMMING:
1. Monolithic Programming indicates the program which contains a single function for the
large program.
2. Modular programming help the programmer to divide the whole program into different
modules and each module is separately developed and tested. Then the linker will link all
these modules to form the complete program.
3. On the other hand monolithic programming will not divide the program and it is a single
thread of execution. When the program size increases it leads inconvenience and difficult to
maintain.
Advantage of modular programming: 1. Modular program are easier to code and debug. 2. Reduces
the programming size. 3. Code can be reused in other programs. 4. Problem can be isolated to
specific module so easier to find the error and correct it.
FUNCTION:
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
Function Declaration OR Function Prototype:
1. It is also known as function prototype.
2. It inform the computer about the three things
a) Name of the function
b) Number and type of arguments received by the function.
c) Type of value return by the function
Syntax:
return type function name (type1 arg1 , type2 arg2);
OR
return type function name (type1 type2);
3. Calling function need information about called function .If called function is place
before calling function then the declaration is not needed.
Function Definition:
1. It consists of code description and code of a function. It consists of two parts
a) Function header
b) Function coding
Function definition tells what the I/O functions are and what is going to do.
Syntax:
return type function name (type1 arg1 , type2 arg2)
{local variable; statements ;
return (expression);
}
FUNCTION CATAGORIES
There are four main categories of the functions these are as follows:
1. Function with no arguments and no return values.
2. Function with no arguments and a return value.
3. Function with arguments and no return values.
4. Function with arguments and return values.
With argument
Without argument
If a function takes any arguments, it must declare variables that accept the values as a
arguments. These variables are called the formal parameters of the function. There are two
ways to pass value or data to function in C language which is given below;
call by value
call by reference
Call by value
In call by value, original value can not be changed or modified. In call by value, when you
passed value to the function it is locally stored by the function parameter in stack memory
location. If you change the value of function parameter, it is changed for the current function
only but it not change the value of variable inside the caller method such as main().
#include<stdio.h>
#include<conio.h>
void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to function
printf("\nValue of a: %d",a);
printf("\nValue of b: %d",b);
getch();
}
Output
Value of a: 200
Value of b: 100
Call by reference
In call by reference, original value is changed or modified because we pass reference
(address). Here, address of the value is passed in the function, so actual and formal
arguments shares the same address space. Hence, any value changed inside the function, is
reflected inside as well as outside the function.
Example Call by reference
#include<stdio.h>
#include<conio.h>
void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to function
printf("\nValue of a: %d",a);
printf("\nValue of b: %d",b);
getch();
}
Output
Value of a: 200
Value of b: 100
This method copy original value into function as a This method copy address of arguments into
arguments. function as a arguments.
Actual and formal arguments will be created in Actual and formal arguments will be created in same
different memory location memory location
When Function is call within same function is called Recursion. The function which calls
same function is called recursive function. In other word when a function calls itself then
that function is called Recursive function.
Recursive function are very useful to solve many mathematical problems like to calculate
factorial of a number, generating Fibonacci series, etc.
Advantage of Recursion
Function calling related information will be maintained by recursion.
Stack evaluation will be take place by using recursion.
In fix prefix, post-fix notation will be evaluated by using recursion.
Disadvantage of Recursion
It is a very slow process due to stack overlapping.
Recursive programs can create stack overflow.
Recursive functions can create as loops.
Find the Factorial of any number using recursion
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int fact(int);
int i,f,num;
clrscr();
printf("Enter any number: ");
scanf("%d",&num);
f=fact(num);
printf("Factorial: %d",f);
getch();
}
int fact(int n)
{
if(a<0)
return(-1);
if(a==0)
return(1);
else
{
return(n*fact(n-1));
}}
Output
#include<stdio.h>
#include<conio.h>
void main()
{
int table(int,int);
int n,i; // local variable
clrscr();
printf("Enter any num : ");
scanf("%d",&n);
for(i=1;i< =10;i++)
{
printf(" %d*%d= %d\n",n,i,table(n,i));
}
getch();
}
int table(n,i)
{
int t;
if(i==1)
{
return(n);
}
else
{
t=(table(n,i-1)+n);
return(t);
//return(table(n,i-1)+n);
}
Examples of Recursion
Q1. Write a program using recursion to find the summation of numbers from 1 to n.
Ans: We can say ‗sum of numbers from 1 to n can be represented as sum of numbers from 1 to n-1
plus n‘ i.e.
Sum of numbers from 1 to n = n + Sum of numbers from 1 to n-1
= n + n-1 + Sum of numbers from 1 to n-2
= n+ n-1 + n-2 + ................ +1
The program which implements the above logic is as follows:
#include<stdio.h>
void main()
{
int n,s;
printf(―Enter a number‖);
scanf(―%d‖,&n);
s=sum(n);
printf(―Sum of numbers from 1 to %d is %d‖,n,s);
}
int sum(int m) int r;
if(m==1)
return (1);
else
r=m+sum(m-1);/*Recursive Call*/
return r;}Output:Enter a number 5 15
Topic: Arrays- Array notation and representation, manipulating array elements, using
multi dimensional arrays, passing arrays to functions.
Introduction
A data structure is the way data is stored in the machine and the functions used to access
that data. An easy way to think of a data structure is a collection of related data items.
An array is a data structure that is a collection of variables of one type that are accessed
through a common name.
Each element of an array is given a number by which we can access that element which is
called an index. It solves the problem of storing a large number of values and manipulating
them.
In an Array values of same type are stored. An array is a group of memory locations related
by the fact that they all have the same name and same type. To refer to a particular location
or element in the array we specify the name to the array and position number of particular
element in the array.
One Dimensional Array
Declaration:
Before using the array in the program it must be declared
Syntax:
data_type array_name[size];
data_type represents the type of elements present in the array. array_name represents the name of the
array.
Size represents the number of elements that can be stored in the array.
Example:
int age[100];
float sal[15];
char grade[20];
Here age is an integer type array, which can store 100 elements of integer type. The array sal is
floating type array of size 15, can hold float values. Grade is a character type array which holds 20
characters.
Initialization:
We can explicitly initialize arrays at the time of declaration. Syntax:
data_type array_name[size]={value1, value2,……..valueN};
Value1, value2, valueN are the constant values known as initializers, which are assigned to the array
elements one after another.
Example:
int marks[5]={10,2,0,23,4};
The values of the array elements after this initialization are: marks[0]=10, marks[1]=2, marks[2]=0,
marks[3]=23, marks[4]=4
1. In 1-D arrays it is optional to specify the size of the array. If size is omitted during
initialization then the compiler assumes the size of array equal to the number of initializers.
Example:int marks[]={10,2,0,23,4};Here the size of array marks is initialized to 5.
2. We can‘t copy the elements of one array to another array by simply assigning it.Example:
Processing:
For processing arrays we mostly use for loop. The total no. of passes is equal to the no. of elements
present in the array and in each pass one element is processed.
Example:
#include<stdio.h>
main()
{
int a[3],i;
for(i=0;i<=2;i++) //Reading the array values
{
printf(―enter the elements‖);
scanf(―%d‖,&a[i]);
}
for(i=0;i<=2;i++) //display the array values
{
printf(―%d‖,a[i]);
printf(―\n‖);
}
}
This program reads and displays 3 elements of integer type.
Example:
int a[4][5];
This is a 2-D array of 4 rows and 5 columns. Here the first element of the array is a[0][0] and last
element of the array is a[3][4] and total no.of elements is 4*5=20.
Processing:
For processing of 2-D arrays we need two nested for loops. The outer loop indicates the rows and the
inner loop indicates the columns.
Example:
int a[4][5];
Reading values in a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
scanf(―%d‖,&a[i][j]);
Displaying values of a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
printf(―%d‖,a[i][j]);
Rule: Addition of two matrixes is only possible if both matrixes are of same size. Suppose
two matrixes A and B is of same size m X n
Sum of two marixes is defined as
(A + B)ij = Aij + Bij
Where 1 ≤ i ≤ m and 1 ≤ j ≤ n
For example:
Suppose two matrixes A and B of size of 2 X 3 is as follow:
Where 1 ≤ i ≤ m and 1 ≤ j ≤ n
For example:
Suppose two matrixes A and B of size of 2 x 2 and 2 x 3 respectively:
Diagonal elements have been shown in the bold letter.We can observer the properties any
element Aij will diagonal element if and only if i = j
We can pass individual array elements as arguments to a function like other simple variables.
Example:
#include<stdio.h> void check(int); void main()
{
int a[10],i; clrscr();
printf(―\n enter the array elements:‖); for(i=0;i<10;i++)
{
scanf(―%d‖,&a[i]);
check(a[i]);
}
void check(int num)
{
if(num%2==0)
printf(―%d is even\n‖,num); else
printf(―%d is odd\n‖,num);
}
Output:
enter the array elements:
1 2 3 4 5 6 7 8 9 10
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Example:
C program to pass a single element of an array to function
#include <stdio.h> void display(int a)
{
printf("%d",a);
}
int main()
{
int c[]={2,3,4};
display(c[2]); //Passing array element c[2] only. return 0;
}
Output
234
We can pass whole array as an actual argument to a function the corresponding formal arguments
should be declared as an array variable of the same type.
Example:
#include<stdio.h>
main()
{
int i, a[6]={1,2,3,4,5,6};
func(a);
printf(―contents of array:‖);
for(i=0;i<6;i++)
printf(―%d‖,a[i]);
printf(‖\n‖);
}
func(int val[])
{
int sum=0,i;
for(i=0;i<6;i++)
{
val[i]=val[i]*val[i];
sum+=val[i];
}
printf(―the sum of squares:%d‖, sum);
}
Output
contents of array: 1 2 3 4 5 6
the sum of squares: 91
Example.2:
Write a C program to pass an array containing age of person to a function. This function should find
average age and display the average age in main function.
#include <stdio.h>
float average(float a[]);
int main()
{
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
return 0;
}
float average(float a[])
{
int i;
float avg, sum=0.0;
for(i=0;i<6;++i)
SEARCHING
Linear Search
Linear search or sequential search is a method for finding a particular value in a list that consists
of checking every one of its elements, one at a time and in sequence, until the desired one is
found.
Linear search is the simplest search algorithm; it is a special case of brute-force search.
1. Repeat For J = 1 to N
2. If (ITEM == A[J]) Then
3. Print: ITEM found at location J
4. Return [End of If]
[End of For Loop]
5. If (J > N) Then
6. Print: ITEM doesn‘t
exist [End of If]
7. Exit
//CODE
Main()
{int a[10],i,n,m,c=0, x;
printf("Enter the size of an array: ");
Linear search on a list of n elements. In the worst case, the search must visit every element
once. This happens when the value being searched for is either the last element in the list, or is
not in the list. However, on average, assuming the value searched for is in the list and each list
element is equally likely to be the value searched for, the search visits only n/2 elements. In best
case the array is already sorted i.e O(1)
Binary Search
A binary search or half-interval search algorithm finds the position of a specified input value
(the search "key") within an array sorted by key value. For binary search, the array should be
arranged in ascending or descending order. In each step, the algorithm compares the search key
value with the key value of the middle element of the array. If the keys match, then a matching
element has been found and its index is returned. Otherwise, if the search key is less than the
middle element's key, then the algorithm repeats its action on the sub-array to the left of the
middle element or, if the search key is greater, on the sub-array to the right. If the remaining
array to be searched is empty, then the key cannot be found in the array and a special "not
found" indication is returned.
Main()
{
int ar[10],val,mid,low,high,size,i;
clrscr();
printf("\nenter the no.s of elements u wanna input in array\n");
scanf("%d",&size);
for(i=0;i<size;i++)
{
printf("input the element no %d\n",i+1);
scanf("%d",&ar[i]);
}
INTRODUCTION TO SORTING
Sorting is nothing but storage of data in sorted order, it can be in ascending or descending
order. The term Sorting comes into picture with the term Searching. There are so many things in
our real life that we need to search, like a particular record in database, roll numbers in merit
list, a particular telephone number, any particular page in a book etc.
Sorting Efficiency
There are many techniques for sorting. Implementation of particular sorting technique
depends upon situation. Sorting techniques mainly depends on two parameters.
First parameter is the execution time of program, which means time taken for execution of
program.
Second is the space, which means space taken by the program.
TYPES OF SORTING
• An internal sort is any data sorting process that takes place entirely within the main
memory of a computer. This is possible whenever the data to be sorted is small enough to all be
held in the main memory.
• External sorting is a term for a class of sorting algorithms that can handle massive
amounts of data. External sorting is required when the data being sorted do not fit into the main
memory of a computing device (usually RAM) and instead they must reside in
the slower external memory (usually a hard drive). External sorting typically uses a hybrid
sort-merge strategy. In the sorting phase, chunks of data small enough to fit in main memory are
• We can say a sorting algorithm is stable if two objects with equal keys appear in the same
order in sorted output as they appear in the input unsorted array.
Insertion sort
It is a simple sorting algorithm that builds the final sorted array (or list) one item at a time.
This algorithm is less efficient on large lists than more advanced algorithms such as quicksort,
heapsort, or merge sort. However, insertion sort provides several advantages:
· Simple implementation
· Efficient for small data sets
· Stable; i.e., does not change the relative order of elements with equal keys
· In-place; i.e., only requires a constant amount O(1) of additional memory space.
//CODE
IS()
{int A[6] = {5, 1, 6, 2, 4, 3};
int i, j, key;
for(i=1; i<6; i++)
{
key = A[i];
j = i-1;
while(j>=0 && key < A[j])
{
A[j+1] = A[j];
j--;
}
A[j+1] = key;
}
Selection Sort
Selection sorting is conceptually the simplest sorting algorithm. This algorithm first finds the
smallest element in the array and exchanges it with the element in the first position, then find
the second smallest element and exchange it with the element in the second position, and
continues in this way until the entire array is sorted
//CODE
Bubble Sort is an algorithm which is used to sort N elements that are given in a memory for
eg: an Array with N number of elements. Bubble Sort compares all the element one by one and
sort them based on their values.
It is called Bubble sort, because with each iteration the smaller element in the list bubbles up
towards the first place, just like a water bubble rises up to the water surface.
Sorting takes place by stepping through all the data items one-by-one in pairs and
comparing adjacent data items and swapping each pair that is out of order.
First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since
5 > 1.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 142 58) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.
Second Pass:
(14258) (14258)
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2
(12458) (12458)
(12458) (12458)
Now, the array is already sorted, but our algorithm does not know if it is completed.
The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
(12458) (12458)
(12458) (12458)
(12458) (12458)
(12458) (12458)
Hence we can insert a flag and can keep checking whether swapping of elements is taking
place or not. If no swapping is taking place that means the array is sorted and we can jump out
of the for loop.
In the above code, if in a complete single cycle of j iteration(inner for loop), no swapping
takes place, and flag remains 0, then we will break out of the for loops, because the array has
already been sorted.
In C language strings are stored in array of char type along with null terminating character ‗\0‘ at
the end.
When sizing the string array we need to add plus one to the actual size of the string to make space
for the null terminating character, ‗\0‘.
syntax:
char fname[4];
The above statement declares a string called fname that can take up to 3 characters. It can be indexed
just as a regular array as well.
fname[]={‗t‘,‘w‘,‘o‘};
We can insert more than one variable. Conversion specification %s is used to insert a string and then
go to each %s in our string, we are printing.
A string is an array of characters. Hence it can be indexed like an array.
char ourstr[6] = ―EED‖;
– ourstr[0] is ‗E‘
– ourstr[1] is ‗E‘
– ourstr[2] is ‗D‘
– ourstr[3] is ‗\0‘
– ourstr[4] is ‗\0‘
– ourstr[5] is ‗\0‘
Reading strings:
If we declare a string by writing
char str[100];
then str can be read from the user by using three ways;
Although the syntax of scanf() function is well known and easy to use, the main pitfall with this
function is that it terminates as soon as it finds a blank space. For example, if the user enters Hello
World, then str will contain only Hello. This is because the moment a blank space is encountered,
the string is terminated by the scanf() function.Example:
char str[10];
printf(―Enter a string\n‖); scanf(―%s‖,str);
The next method of reading a string a string is by using gets() function. The string can be read by
writing
gets(str);
gets() is a function that overcomes the drawbacks of scanf(). The gets() function takes the starting
address of the string which will hold the input. The string inputted using gets() is automatically
terminated with a null character.
Example:
char str[10];
printf(―Enter a string\n‖); gets(str);
The string can also be read by calling the getchar() repeatedly to read a sequence of single characters
(unless a terminating character is encountered) and simultaneously storing it in a character array as
follows:
int i=0;
char str[10],ch;
getchar(ch);
while(ch!=‘\0‘)
{
str[i]=ch; // store the read character in str
i++;
getch(ch); // get another character
}
str[i]=‘\0‘; // terminate str with null character
Writing string
We can use width and precision specification along with %s. The width specifies the minimum output
field width and the precision specifies the maximum number of characters to be displayed.
Example:
this statement would print only the first three characters in a total field of five charaters; also these
three characters are right justified in the allocated width.
The next method of writing a string is by using the puts() function. The string can be displayed by
writing:
puts(str);
It terminates the line with a newline character (‗\n‘). It returns an EOF(-1) if an error occurs and returns
a positive number on success.
Finally the string can be written by calling the putchar( ) function repeatedly to print a sequence of
single characters.
int i=0;
char str[10];
while(str[i]!=‘\0‘)
{putchar(str[i]); // print the character on the screen
i++;
}
strcmp():
It is used to compare the contents of the two strings. If any mismatch occurs then it results the
difference of ASCII values between the first occurrence of 2 different characters.
Syntax:
int strcmp(string 1, string 2);
Example:
char mystr_a[10] = ―Hello‖; char mystr_b[10] = ―Goodbye‖;
– mystr_a == mystr_b; // NOT allowed! The correct way is
if (strcmp(mystr_a, mystr_b ))
printf ("Strings are NOT the same."); else
printf( "Strings are the same.");
Here it will check the ASCII value of H and G i.e, 72 and 71 and return the diference 1.
strcat():
It is used to concatenate i.e, combine the content of two strings.
Syntax:
strcat(string 1, string 2);
Example:
char fname[30]={―bob‖};
char lname[]={―by‖};
printf(―%s‖, strcat(fname,lname));
Output:
bobby.
strlen():
It is used to return the length of a string.
Syntax:
int strlen(string);
Example:
char fname[30]={―bob‖};
int length=strlen(fname);
It will return 3
strchr():
It is used to find a character in the string and returns the index of occurrence of the character for the
first time in the string.
Syntax:
strchr(cstr);
int puts( char s); Prints the string s followed by new line
character. Returns a non-zero integer if
possible or EOF if an error occurs
Definition
A Structure is a user defined data type that can store related information together. The variable
within a structure are of different data types and each has a name that is used to select it from the
structure. C arrays allow you to define type of variables that can hold several data items of the same
kind but structure is another user defined data type available in C programming, which allows you
to combine data items of different kinds.
Structures are used to represent a record, Suppose you want to keep track of your books in a library.
You might want to track the following attributes about each book:
• Title
• Author
• Subject
• Book ID
Structure Declaration-It is declared using a keyword struct followed by the name of the structure.
The variables of the structure are declared within the structure.
Example:
Struct struct-name
{
data_type var-name;
data_type var-name;
};
Structure Initialization-Assigning constants to the members of the structure is called initializing
of structure. Syntax:
struct struct_name
{
data _type member_name1;
data _type member_name2;
} struct_var={constant1,constant2};
Accessing the Members of a structure-A structure member variable is generally accessed using a
‗.‘ operator.
Syntax: strcut_var. member_name;
The dot operator is used to select a particular member of the structure. To assign value to the individual
Data members of the structure variable stud, we write, stud.roll=01;
stud.name=‖Rahul‖;
To input values for data members of the structure variable stud, can be written as,
scanf(―%d‖,&stud.roll);
scanf(‗‘%s‖,&stud.name);
To print the values of structure variable stud, can be written as: printf(―%s‖,stud.roll);
printf(―%f‖,stud.name);
QUESTIONS
1. Write a program using structures to read and display the information about an employee.
2. Write a program to read, display, add and subtract two complex numbers.
3. Write a program to enter two points and then calculate the distance between them.
Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to any other
variable as follows:
struct books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To find the
address of a structure variable, place the & operator before the structure's name as follows:
struct_pointer = &book1;
To access the members of a structure using a pointer to that structure, you must use the ->
operator as follows:
struct_pointer->title;
1 .Write a program to display, add and subtract two time defined using hour, minutes and values of
seconds.
2. Write a program, using pointer to structure, to initialize the members in the structure. Use
functions to print the students information.
3. Write a program using an array of pointers to a structure to read and display the data of a
student.
UNION
Union is a collection of variables of different data types, in case of union information can
only be stored In one field at any one time.
A union is a special data type available in C that enables you to store different data types in
the same memory location.
You can define a union with many members, but only one member can contain a value at
any given time. Unions provide an efficient way of using the same memory location for
multi-purpose.
Declaring Union
union union-name
{
data_type var-name;
data_type var-name;
};
The union tag is optional and each member definition is a normal variable definition, such
as int i; or float f; or any other valid variable definition. At the end of the union's definition,
before the final semicolon, you can specify one or more union variables but it is optional.
Here is the way you would define a union type named Data which has the three members i, f, and
str. Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. This means that a single variable ie. same memory location can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For
example, in above example Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by character string. Following is the example which will
display total memory size occupied by the above union:
Accessing a Member of a Union
#include <stdio.h>
#include <string.h>
union Data
{int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
1. Write a program to define a union and a structure both having exactly the same members. Using
the sizeof operator, print the size of structure variable as well as union variable and comment on the
result.
2. Write a program to define a structure for a hotel that has the member‘s mane, address, grade,
number of rooms, and room charges. Write a function to print the names of the hotels in a particular
grade. Also write a function to print names of a hotel that have room charges less than the specified
value.
Enumerated Types
Enumerations are integer types that you define in a program. The definition of an
enumeration begins with the keyword enum, possibly followed by an identifier for the
enumeration, and contains a list of the type's possible values, with a name for each value:
enum [identifier] { enumerator-list };
The following example defines the enumerated type enum color:
enum color { black, red, green, yellow, blue, white=7, gray };
The identifier color is the tag of this enumeration. The identifiers in the listblack, red, and so
onare the enumeration constants , and have the type int. You can use these constants
anywhere within their scopeas case constants in a switch statement, for example.
Each enumeration constant of a given enumerated type represents a certain value, which is
determined either implicitly by its position in the list, or explicitly by initialization with a
constant expression. A constant without an initialization has the value 0 if it is the first
constant in the list, or the value of the preceding constant plus one. Thus in the previous
example, the constants listed have the values 0, 1, 2, 3, 4, 7, 8.
Within an enumerated type's scope, you can use the type in declarations:
enum color bgColor = blue, // Define two variables
fgColor = yellow; // of type enum color.
void setFgColor( enum color fgc ); // Declare a function with a parameter
// of type enum color.
An enumerated type always corresponds to one of the standard integer types. Thus your C
programs may perform ordinary arithmetic operations with variables of enumerated types.
The compiler may select the appropriate integer type depending on the defined values of the
enumeration constants. In the previous example, the type char would be sufficient to
represent all the values of the enumerated type enum color.Different constants in an
enumeration may have the same value:
enum { OFF, ON, STOP = 0, GO = 1, CLOSED = 0, OPEN = 1 };
As the preceding example also illustrates, the definition of an enumerated type does not
necessarily have to include a tag. Omitting the tag makes sense if you want only to define
constants, and not declare any variables of the given type. Defining integer constants in
this way is generally preferable to using a long list of #define directives, as the
enumeration provides the compiler with the names of the constants as well as their
numeric values.
Complexity
Complexity of an algorithm is a measure of the amount of time and/or space required by
an algorithm for an input of a given size (n).
What do we measure?
In analyzing an algorithm, rather than a piece of code, we will try and predict the number
of times "the principle activity" of that algorithm is performed. For example, if we are
analyzing a sorting algorithm we might count the number of comparisons performed, and
if it is an algorithm to find some optimal solution, the number of times it evaluates a
solution. If it is a graph coloring algorithm we might count the number of times we check
that a colored node is compatible with its neighbors.
Worst Case
is the maximum run time, over all inputs of size n, ignoring effects (a) through (d) above.
That is, we only consider the "number of times the principle activity of that algorithm is
performed".
Best Case
In this case we look at specific instances of input of size n. For example, we might get
best behaviour from a sorting algorithm if the input to it is already sorted.
Average Case
Arguably, average case is the most useful measure. It might be the case that worst case
behaviour is pathological and extremely rare, and that we are more concerned about how
the algorithm runs in the general case. Unfortunately this is typically a very difficult thing
to measure. Firstly, we must in some way be able to define by what we mean as the
"average input of size n". We would need to know a great deal about the distribution of
cases throughout all data sets of size n. alternatively we might make a possibly dangerous
assumption that all data sets of size n are equally likely. Generally, in order to get a feel
for the average case we must resort to an empirical study of the algorithm, and in some
way classify the input (and it is only recently with the advent of high performance, low
cost computation, that we can seriously consider this option).
Time complexity:
Space complexity:
Applications of Complexity
Computational complexity theory is the study of the complexity of problems—that is, the
difficulty of solving them. Problems can be classified by complexity class according to the time
it takes for an algorithm—usually a computer program—to solve them as a function of the
problem size. Some problems are difficult to solve, while others are easy.
For example, some difficult problems need algorithms that take an exponential amount of time in
terms of the size of the problem to solve. Take the traveling salesman problem, it can be solved
in time O(n^2 2^n) (where n is the size of the network to visit—let's say the number of cities the
traveling salesman must visit exactly once). As the size of the network of cities grows, the time
needed to find the route grows (more than) exponentially.
Even though a problem may be computationally solvable in principle, in actual practice it may
not be that simple. These problems might require large amounts of time or an inordinate amount
of space. Computational complexity may be approached from many different aspects.
Computational complexity can be investigated on the basis of time, memory or other resources
used to solve the problem. Time and space are two of the most important and popular
considerations when problems of complexity are analyzed.
An Introduction to Pointers
Pointer Notation
Consider the declaration,
int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
We see that the computer has selected memory location 65524 as the place to store the
value 3. The location number 65524 is not a number to be relied upon, because some
other time the computer may choose a different location for storing the value 3. The
important point is, i‘s address in memory is a number.
We can print this address number through the following program:
main( )
{
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nValue of i = %d", i ) ;
}
The output of the above program would be:
Address of i = 65524
Value of i = 3
Look at the first printf( ) statement carefully. ‗&‘ used in this statement is C‘s ‗address
of‘ operator. The expression &i returns the address of the variable i, which in this case
happens to be 65524. Since 65524 represents an address, there is no question of a sign
being associated with it. Hence it is printed out using %u, which is a format specifier for
printing an unsigned integer.
We have been using the ‗&‘ operator all the time in the scanf( ) statement. The other
pointer operator available in C is ‗*’, called ‗value at address‘ operator. It gives the value
stored at a particular address. The ‗value at address‘ operator is also called ‗indirection‘
operator.
Observe carefully the output of the following program:
main( )
{
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
A word of caution! Do not attempt the following operations on pointers... they would
never work out.
(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant
Now we will try to correlate the following two facts, which we have learnt above:
(a) Array elements are always stored in contiguous memory locations.
(b) A pointer when incremented always points to an immediately next location of its type.
Dynamic memory management refers to manual memory management. This allows you to obtain
more memory when required and release it when not necessary.
Although C inherently does not have any technique to allocate memory dynamically, there are
4 library functions defined under <stdlib.h> for dynamic memory allocation.
Allocates requested size of bytes and returns a pointer first byte of allocated
malloc()
space
Allocates space for an array elements, initializes to zero and then returns a
calloc()
pointer to memory
malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size and return a pointer of
type void which can be casted into pointer of any form.
Syntax of malloc()
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively
and the pointer points to the address of first byte of memory.
This statement will allocate contiguous space in memory for an array of n elements. For
example:
This statement allocates contiguous space in memory for an array of 25 elements each of size of
float, i.e, 4 bytes.
free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its
own. You must explicitly use free() to release the space.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
C realloc()
If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().
Syntax of realloc()
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
A linked list is a linear data structure where each element is a separate object.
Each element (we will call it a node) of a list is comprising of two items - the data and a
reference to the next node. The last node has a reference to null. The entry point into a
linked list is called the head of the list. It should be noted that head is not a separate
node, but the reference to the first node. If the list is empty then the head is a null
reference.
A linked list is a dynamic data structure. The number of nodes in a list is not fixed and can grow
and shrink on demand. Any application which has to deal with an unknown number of objects
will need to use a linked list.
One disadvantage of a linked list against an array is that it does not allow direct access to the
individual elements. If you want to access a particular item then you have to start at the head and
follow the references until you get to that item.
Another disadvantage is that a linked list uses more memory compare with an array - we extra 4
bytes (on 32-bit CPU) to store a reference to the next node.
A doubly linked list is a list that has two references, one to the next node and another to
previous node.
Another important type of a linked list is called a circular linked list where last node of
the list points back to the first node (or the head) of the list.
A linked list is a linear data structure, in which the elements are not stored at contiguous memory
locations. The elements in a linked list are linked using pointers as shown in the below image:
FILE
A File is a collection of data stored on a secondary storage device like hard disk. File
operation is to combine all the input data into a file and then to operate through the C
program. Various operations like insertion, deletion, opening closing etc can be done upon a
file.
When the program is terminated, the entire data is lost in C programming. If you want to keep large
volume of data, it is time consuming to enter the entire data. But, if file is created these information
can be accessed using few commands.
There are large numbers of functions to handle file I/O in C language. In this tutorial, you will learn
to handle standard I/O(High level file I/O functions) in C. High level file I/O functions can be
categorized as:
1. Text file
2. Binary file
A file can be open in several modes for these operations. The various modes are:
r open a text file for reading
w truncate to zero length or create a text file for writing
a append; open or create text file for writing at end-of-file
rb open binary file for reading
wb truncate to zero length or create a binary file for writing ab append; open or create binary file
for writing at end-of-file r+ open text file for update (reading and writing)
w+ truncate to zero length or create a text file for update a+ append; open or create text file for
update
r+b or rb+ open binary file for update (reading and writing)
w+b or wb+ truncate to zero length or create a binary file for update a+b or ab+ append; open or
create binary file for update
fopen and freopen opens the file whose name is in the string pointed to by filename and
associates a stream with it. Both return a pointer to the object controlling the stream, or if
the open operation fails a null pointer.
The error and end-of-file(EOF) indicators are cleared, and if the open operation fails error
is set. freopen differs from fopen in that the file pointed to by stream is closed first when
already open and any close errors are ignored.
Q2. Write a C program to read name and marks of n number of students from user and store
them in a file. If the file previously exits, add the information of n students.
Ans:
#include <stdio.h>
int main()
{
char name[50]; int marks, i,n;
printf(―Enter number of students‖);
scanf(―%d‖, &n);
FILE *fptr; fptr=(fopen(―C:\\student.txt‖,‖a‖));
if (fptr==NULL){ printf("Error!"); exit(1);
}
for(i=0;i<n;++i)
{ printf("For student%d\nEnter name: ",i+1); scanf("%s",name);
printf(―Enter marks‖);
scanf(―%d‖, &marks);
fprintf(fptr, ―\nName: %s\nMarks=%d\n‖, name, marks);
}
fclose(fptr);
Return 0;
}
The fclose function causes the stream pointed to be flushed and the associated file to be closed. Any
unwritten buffered data for the stream are delivered to the host environment to be written to the
file; any unread buffered data are discarded. The stream is disassociated from the file. If the
associated buffer was automatically allocated, it is deallocated. The function returns zero if the
stream was successfully closed or EOF if any errors were detected.
Q4. Write a C program to write all the members of an array of strcures to a file using fwrite().
Read the array from the file and display on the screen.
Ans:
#include<stdio.h>
Struct s
{
Char name[50];
Int height;
};
Int main()
{
Struct s a[5], b[5];
FILE *fptr;
Int I;
Fptr=fopen(―file.txt‖, ―wb‖);
For(i=0; i<5; ++i)
{
fflush(stdin);
printf("Enter name: ") ;
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
}
Features of C Preprocessor
There are several steps involved from the stage of writing a C program to the stage of getting it
executed.
Note that if the source code is stored in a file PR1.C then the expanded source code gets stored in
a file PR1.I. When this expanded source code is compiled the object code gets stored in PR1.OBJ.
When this object code is linked with the object code of library functions the resultant executable
code gets stored in PR1.EXE.
The preprocessor offers several features called preprocessor directives. Each of these preprocessor
directives begin with a # symbol. The directives can be placed anywhere in a program but are
most often placed at the beginning of a program, before the first function definition. We would
learn the following preprocessor directives here:
(a) Macro expansion b) File inclusion
(c) Conditional Compilation
(d) Miscellaneous directives
Let us understand these features of preprocessor one by one.
a) Macro Expansion
Have a look at the following program.
#define UPPER 25
main( )
{
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;
#define UPPER 25
This statement is called ‗macro definition‘ or more commonly, just a ‗macro‘. What purpose
does it serve? During preprocessing, the preprocessor replaces every occurrence of UPPER
in the program with 25.
When we compile the program, before the source code passes to the compiler it is examined
by the C preprocessor for any macro definitions. When it sees the #define directive, it goes
through the entire program in search of the macro templates; wherever it finds one, it
replaces the macro template with the appropriate macro expansion. Only after this procedure
has been completed is the program handed over to the compiler.
Remember that a macro definition is never to be terminated by a semicolon.
In this program wherever the preprocessor finds the phrase AREA(x) it expands it into the
statement ( 3.14 * x * x ). However, that‘s not all that it does. The x in the macro template
AREA(x) is an argument that matches the x in the macro expansion ( 3.14 * x * x ). The
statement AREA(r1) in the program causes the variable r1 to be substituted for x. Thus the
statement AREA(r1) is equivalent to:
Be careful not to leave a blank between the macro template and its argument while defining
the macro. For example, there should be no blank between AREA and (x) in the definition,
#define AREA(x) ( 3.14 * x * x )
b) File Inclusion
The second preprocessor directive we‘ll explore in this chapter is file inclusion. This directive
causes one file to be included in another. The preprocessor command for file inclusion looks like
this:
#include "filename"
and it simply causes the entire contents of filename to be inserted into the source code at that
point in the program.
c) Conditional Compilation
We can, if we want, have the compiler skip over part of a source code by inserting the
preprocessing commands #ifdef and #endif, which have the general form:
#ifdef macroname
statement 1 ;
statement 2 ;
statement 3 ;
#endif
If macroname has been #defined, the block of code will be processed as usual; otherwise not.
Where would #ifdef be useful? When would you like to compile only a part of your program? In
three cases:
(a) To ―comment out‖ obsolete lines of code. It often happens that a program is changed at the
last minute to satisfy a client. This involves rewriting some part of source code to the
client‘s satisfaction and deleting the old code. But veteran programmers are familiar with the
clients who change their mind and want the old code back again just the way it was. Now
you would definitely not like to retype the deleted code again.
One solution in such a situation is to put the old code within a pair of /* */ combination. But
we might have already written a comment in the code that we are about to ―comment out‖.
This would mean we end up with nested comments. Obviously, this solution won‘t work
since we can‘t nest comments in C.
Therefore the solution is to use conditional compilation as shown below.
main( )
{
#ifdef OKAY
statement 1 ;
statement 2 ; /* detects virus */
statement 3 ;
statement 4 ; /* specific to stone virus */
#endif
statement 5 ;
(b) A more sophisticated use of #ifdef has to do with making the programs portable, i.e. to make
them work on two totally different computers. Suppose an organization has two
different types of computers and you are expected to write a program that works on both the
machines. You can do so by isolating the lines of code that must be different for each
machine by marking them off with #ifdef. For example:
main( )
{
#ifdef INTEL
code suitable for a Intel PC
#else
code suitable for a Motorola PC
#endif
code common to both the computers
}
When you compile this program it would compile only the code suitable for a Intel PC and
the common code. This is because the macro INTEL has not been defined. Note that the
working of #ifdef - #else - #endif is similar to the ordinary if - else control instruction of C.
If you want to run your program on a Motorola PC, just add a statement at the top saying,
#define INTEL
Sometimes, instead of #ifdef the #ifndef directive is used. The #ifndef (which means ‗if not
defined‘) works exactly opposite to #ifdef. The above example if written using #ifndef,
would look like this:
main( )
{
#ifndef INTEL
code suitable for a Intel PC
#else
code suitable for a Motorola PC
#endif
code common to both the computers
}
(c) Suppose a function myfunc( ) is defined in a file ‗myfile.h‘ which is #included in a file
‗myfile1.h‘. Now in your program file if you #include both ‗myfile.h‘ and ‗myfile1.h‘ the
compiler flashes an error ‗Multiple declaration for myfunc’. This is because the same file
‗myfile.h‘ gets included twice. To avoid this we can write following code in the header file.
/* myfile.h */
#ifndef __myfile_h
#define __myfile_h
myfunc( )
{
/* some code */
#undef Directive
On some occasions it may be desirable to cause a defined name to become ‗undefined‘. This can
be accomplished by means of the #undef directive. In order to undefine a macro that has been
earlier #defined, the directive,
#undef macro template
can be used. Thus the statement,
#undef PENTIUM
would cause the definition of PENTIUM to be removed from the system. All subsequent #ifdef
PENTIUM statements would evaluate to false. In practice seldom are you required to undefine a
macro, but for some reason if you are required to, then you know that there is something to fall
back upon.
#pragma Directive
This directive is another special-purpose directive that you can use to turn on or off certain
features. Pragmas vary from one compiler to another. There are certain pragmas available with
Microsoft C compiler that deal with formatting source listings and placing comments in the
object file generated by the compiler. Turbo C/C++ compiler has got a pragma that allows you to
suppress warnings generated by the compiler. Some of these pragmas are discussed below.
(a) #pragma startup and #pragma exit: These directives allow us to specify functions that are
called upon program startup (before main( )) or program exit (just before the program
terminates). Their usage is as follows:
void fun1( ) ;
void fun2( ) ;
#pragma startup fun1
#pragma exit fun2
main( )
{
printf ( "\nInside maim" ) ;
}
void fun1( )
{
printf ( "\nInside fun1" ) ;
}
void fun2( )
{
printf ( "\nInside fun2" ) ;
}
(b) #pragma warn: This directive tells the compiler whether or not we want to suppress a
specific warning. Usage of this pragma is shown below.
#pragma warn –rvl /* return value */
#pragma warn –par /* parameter not used */
#pragma warn –rch /* unreachable code */
int f1( )
{
int a = 5 ;
}
void f2 ( int x )
{
printf ( "\nInside f2" ) ;
}
int f3( )
{
int x = 6 ;
return x ;
x++ ;
}
void main( )
{
f1( ) ;
f2 ( 7 ) ;
f3( ) ;
}
If you go through the program you can notice three problems immediately. These are:
(a) Though promised, f1( ) doesn‘t return a value.
(b) The parameter x that is passed to f2( ) is not being used anywhere in f2( ).
(c) The control can never reach x++ in f3( ).
If we compile the program we should expect warnings indicating the above problems.
However, this does not happen since we have suppressed the warnings using the #pragma
directives. If we replace the ‗–‘ sign with a ‗+‘ then these warnings would be flashed on
compilation. Though it is a bad practice to suppress warnings, at times it becomes useful to
suppress them. For example, if you have written a huge program and are trying to compile it,
then to begin with you are more interested in locating the errors, rather than the warnings. At
such times you may suppress the warnings. Once you have located all errors, then you may
turn on the warnings and sort them out.
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
float pi=3.14,area,ci;
clrscr();
printf(―enter radius of circle: ‖);
scanf(―%d‖,&r);
area=pi*r*r;
printf(―area of circle=%f ‖,area);
ci=2*pi*r;
printf(―circumference=%f ‖,ci);
getch();
}
Output:
enter radius of a circle: 5
area of circle=78.000
circumference=31.4
#include<stdio.h>
#include<conio.h>
void main()
{
int p,r,t,si;
clrscr();
printf(―enter principle, Rate of interest & time to find simple interest: ‖);
scanf(―%d%d%d‖,&p,&r,&t);
si=(p*r*t)/100;
printf(―simple intrest= %d‖,si);
getch();
}
Output:
enter principle, rate of interest & time to find simple interest: 500
5
2
simple interest=50
#include<stdio.h>
#include<conio.h>
void main()
{
float c,f;
clrscr();
printf(―enter temp in centigrade: ‖);
scanf(―%f‖,&c);
f=(1.8*c)+32;
printf(―temp in Fahrenheit=%f ‖,f);
getch();
}
Output:
enter temp in centigrade: 32
temp in Fahrenheit=89.59998
#include<stdio.h>
#include<conio.h>
void main()
{
int s1,s2,s3,s4,s5,sum,total=500;
float per;
clrscr();
printf(―enter marks of 5 subjects: ‖);
scanf(―%d%d%d%d%d‖,&s1,&s2,&s3,&s4,&s5);
sum=s1+s2+s3+s4+s5;
printf(―sum=%d‖,sum);
per=(sum*100)/total;
printf(―percentage=%f‖,per);
getch();
}
Output:
enter marks of 5 subjects: 60
65
50
60
60
sum=300
percentage=60.000
#include <stdio.h>
int main()
{
int i, n, flag;
//Flag is used as notification. Initially we have supposed that the number is prime.
flag = 1;
/*
* If flag contains 1 then it is prime
*/
if(flag==1)
{
printf("\n%d is prime number", n);
}
else
{
printf("\n%d is not prime number", n);
}
return 0;
}
#include <stdio.h>
int main()
{
int n, num, lastDigit, sum = 0;
/*
* Finds the sum of cubes of each digit of number
*/
while(n != 0)
{
/* Finds last digit of number */
lastDigit = n % 10;
/* Finds cube of last digit and adds to sum */
sum += (lastDigit * lastDigit * lastDigit);
n = n / 10;
}
/* Checks if sum of cube of digits is equal to original value or not. */
if(num == sum)
{
printf("\n%d is Armstrong number.", num);
}
else
{
printf("\n%d is not Armstrong number.", num);
}
return 0;}
#include <stdio.h>
int main()
{ int i, num, sum = 0;
#include <stdio.h>
int main()
{
int i, j, n, isPrime; //isPrime is used as flag variable
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}
Now Fibonacci series algorithm is simple and contains only four steps.
Step 1: Print the value of c.
#include <stdio.h>
int main()
{
int a, b, c, i, n;
printf("Enter value of n to print Fibonacci series : ");
scanf("%d", &n);
a = 0;
b = 1;
c = 0;
a=b;
b=c;
c=a+b;
}
return 0;}
#include <stdio.h>
/* Function declarations */
int isPrime(int num);
int isArmstrong(int num);
int isPerfect(int num);
int main()
{
int num;
return 0;
}
/**
* Checks whether a number is prime or not. Returns 1 if the number is prime
* otherwise returns 0.
*/
int isPrime(int num)
{
int i;
/**
* Checks whether a number is Armstrong number or not. Returns 1 if the number
* is Armstrong number otherwise returns 0.
*/
int isArmstrong(int num)
{
int lastDigit, sum, n;
sum = 0;
n = num;
while(n!=0)
{
/* Finds last digit of number */
lastDigit = n % 10;
n = n/10;
}
/**
* Checks whether the number is perfect number or not. Returns 1 if the number
* is perfect otherwise returns 0.
*/
int isPerfect(int num)
{
int i, sum, n;
sum = 0;
n = num;
#include <stdio.h>
#include <math.h>
/* Fuction declaration */
int reverse(int num);
int main()
{
int num, rev;
return 0;
}
/**
* Recursive function to find reverse of any number
*/
int reverse(int num)
{
int digit;
//Base condition
if(num==0)
return 0;
#include <stdio.h>
//Function declaration
long long fibo(int num);
int main()
{
int num;
long long fibonacci;
fibonacci = fibo(num);
return 0;
}
/**
* Recursive function to find nth Fibonacci term
*/
long long fibo(int num)
{
if(num == 0) //Base condition
return 0;
else if(num == 1) //Base condition
return 1;
else
return fibo(num-1) + fibo(num-2); //Recursively calls fibo() to find nth fibonacci term.
int main()
{
int arr[MAX_SIZE];
int i, n, sum=0;
/*
* Reads size and elements in array from user
*/
printf("Enter size of the array: ");
scanf("%d", &n);
printf("Enter %d elements in the array: ", n);
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
/*
* Adds each element of array to sum
*/
for(i=0; i<n; i++)
{
sum = sum + arr[i];
}
return 0;
}
int main()
{
int arr[100];
int i, max, min, size;
/*
* Reads size array and elements in the array
*/
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/*
* Finds maximum and minimum in all array elements.
*/
for(i=1; i<size; i++)
{
/* If current element of array is greater than max */
if(arr[i]>max)
{
max = arr[i];
}
/*
* Prints the maximum and minimum element
*/
printf("Maximum element = %d\n", max);
printf("Minimum element = %d", min);
return 0;
}
int main()
{
int arr[100], reverse[100];
int size, i, j;
/*
* Reads the size of array and elements in array
/*
* Reverse the array
*/
j=0;
for(i=size-1; i>=0; i--)
{
reverse[j] = arr[i];
j++;
}
/*
* Prints the reversed array
*/
printf("\nReversed array : ");
for(i=0; i<size; i++)
{
printf("%d\t", reverse[i]);
}
return 0;
}
int main()
{
int arr[100];
int size, i, num, flag;
/*
* If element is not found in array
*/
if(flag==0)
{
printf("\n%d is not found in the array", num);
}
return 0;
}
int main()
{
int arr[100];
int size, i, j, temp;
/*
* Read size of array and elements in array
*/
printf("Enter size of array: ");
scanf("%d", &size);
/*
* Array sorting code
*/
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
/*
* If there is a smaller element towards right of the array then swap it.
*/
if(arr[j] < arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
/*
* Prints the sorted array
*/
printf("\nElements of array in sorted ascending order: ");
for(i=0; i<size; i++)
return 0;
}
#include <stdio.h>
/*
* Checks each character of string
*/
while(string[i]!='\0')
{
if((string[i]>='a' && string[i]<='z') || (string[i]>='A' && string[i]<='Z'))
{
alphabets++;
}
else if(string[i]>='0' && string[i]<='9')
{
digits++;
}
else
{
others++;
}
return 0;
}
Example:
Input any decimal number: 112
Output binary number: 0111000
Decimal number system:
Decimal number system is a base 10 number system. Decimal number system uses only 10
symbols to represent all number i.e. 0 1 2 3 4 5 6 7 8 9
Binary number system:
Binary number system is a base 2 number system. Binary number system uses only 2
symbols to represent all numbers i.e. 0 and 1
Program:
#include <stdio.h>
int main()
{
long long decimal, tempDecimal, binary;
int rem, place = 1;
binary = 0;
/*
/*
* Converts the decimal number to binary number
*/
while(tempDecimal!=0)
{
rem = tempDecimal % 2;
tempDecimal /= 2;
place *= 10;
}
return 0;
}
1. Draw a flow chart for arranging three numbers a, b and c in ascending order.
2. What is the need of an operating system?
2. Classify the operating system into different types based on their processing capability.
3. Differentiate between a Linker and Compiler.
4. What is kernel?
5. Explain types of errors while compilation and execution of c program.
6. What is top down approach?
7. Compare compiler, interpreter and assembler.
8. Why ‗C' is called structured programming language?
9. What are the classifications of computer? Explain any two in detail.
10. Describe the functionalities of an operating system.
11. Explain different types of type conversion in 'C' with suitable example.
12. What are escape sequences characters?
13. What do curly braces denote in C? Why does it make sense to use curly braces to surround
the body of a function?
14. Give any four format specifiers used in printf() function
15. Write down the difference between associatively and precedence of operators.
16. If int a = 2 , b = 3, x = 0; Find the value of x = (++a, b+=a).
17. Find the value of Y (assume Y is integer data type) Y=4 * 2 / 4 – 6 /2 + 3 % 2 * 6 / 2 + 2 >
2 && 4 != 2.
18. Explain the structure of C program with suitable example.
19. What is difference between macro and constant?
20. What will be the output of the following code?
void main( )
{
int a=5,b=6,c;
c=a++>b&&++b<10||b++;
printf("%d%d%d",a,b,c);
}
21. Find the output of the statement printf("%d%d%d",n++,++n,--n);if n=3.
22. Differentiate the following:
1. Unary operator and Binary operator
2. Local variables and Global variables
23. Write briefly about the user defined functions and standard library functions.
24. Explain the ternary operators in details with example.
25. Give various types of scope in ‗C‘ programming.
26. Write down any four characteristics of a good programming language.
1.How many bytes are needed for a pointer ? Justify your answer .
2.Differentiate between Structure and Union.
3.Write a function in C to exchange the content of two integer variables without using a third
variable.
4.Justify that operating system is a resource manager.
5. What are the different types of operators in C language? Explain with example. Discuss the
significance of each.
6. Write an algorithm to print all the even numbers and odd numbers between any given two
integers Nl and N2 (N1 < N2) and also print the sum of all even numbers and odd numbers.
7. Write short note on the· following with example in reference to C language:
(i)Data type (ii) Entry and exit control loops, (iii) Switch statement· and if
statement.
8. Discuss the major components of a digital computer· with suitable block diagram. Also
discuss the functions of these components.
9. Differentiate between the following: -
i) High level language and low level language. (ii) Compiler and interpreter.
(iii) Logical error and run time error. (iv) Algorithm and flowchart.
10. Draw a flowchart to play a dice game according to the following rules
(i) If you throw two identical numbers, you win.
(ii) If the numbers are not the same, but are both even, or both odd, you have another turn.
(iii) If one number is odd, and the other is even, you lose.
11. For a digital computer briefly explain the following:
a) Cache Memory b) Control Unit c) ALU
12. Differentiate between pseudo code and algorithm. Write the characteristics of an algorithm.
Draw a flow chart and write a program in C for printing Fibonacci series upto a term
given by user.
13. Write about the formatted and unformatted Input / Output functions in 'C‘
14. What are different types in C. Explain in terms of memory size, format specifier and range.
15. Write a program in C that accept the length and width of a rectangle and print the area.
The area of a rectangle is calculated by a function and returns it value to main program
where it is printed. The values of length and width of rectangle are accepted from the
keyboard. Also give the flowchart and algorithm.
16. Discuss various storage classes in C with suitable example. Also give their significance.
17. Draw the flow chart and write a function in c to calculate the sum S of the following
series ':
S = 11 + 22+ 33 + 44 + ... + NN
18. What do you mean by sorting? Write a program in C to sort the given n positive integers.
Also give the flow chart for the same.
19. Write a program that counts the total number of Vowels in a given sentence.