CP
CP
CP
I Year B.Tech-SYLLABUS
COMPUTER PROGRAMMING
UNIT - I
Introduction to Computers – Computer Systems, Computing Environments, Computer Languages,
Creating and running programs, Program Development.
Introduction to the C Language – Background, C Programs, Identifiers, Types, Variables,
Constants, Input / Output, Operators(Arithmetic, relational, logical, bitwise etc.), Expressions,
Precedence and Associativity, Expression Evaluation, Type conversions, Statements-
Selection Statements(making decisions) – if and switch statements, Repetition statements ( loops)-
while, for, do-while statements, Loop examples, other statements related to looping –break, continue,
goto, Simple C Program examples.
UNIT - II
Functions-Designing Structured Programs Functions, user defined functions, inter function
communication, Standard functions, Scope, Storage classes-auto, register, static, extern, scope rules,
type qualifiers, recursion- recursive functions, Limitations of recursion, example C programs,
Preprocessor commands.
Arrays – Concepts, using arrays in C, inter function communication, array applications, two –
dimensional arrays, Multidimensional arrays, C program examples.
UNIT - III
Pointers – Introduction (Basic Concepts), Pointers for inter function communication, pointers to
pointers, compatibility, Pointer Applications-Arrays and Pointers, Pointer Arithmetic and arrays,
Passing an array to a function, memory allocation functions, array of pointers, programming
applications, pointers to void, pointers to functions.
Strings – Concepts, C Strings, String Input / Output functions, arrays of strings, string manipulation
functions, string /
data conversion, C program examples.
UNIT - IV
Enumerated, Structure ,and Union Types– The Type Definition(typedef), Enumerated types,
Structures –Declaration, initialization, accessing structures, operations on structures, Complex
structures, structures and functions, Passing structures through pointers, self referential structures,
unions, bit fields, C programming examples, command –line arguments,
Input and Output – Concept of a file, streams, text files and binary files, Differences between text
and binary files, State of a file, Opening and Closing files, file input / output functions (standard
library input / output functions for files), file status functions (error handling),Positioning functions, C
program examples.
UNIT – V
Searching and Sorting – Sorting- selection sort, bubble sort, Searching-linear and binary search
methods. Lists- Linear list – singly linked list implementation, insertion, deletion and searching
operations on linear list, Stacks- Push and Pop Operations, Queues- Enqueue and Dequeue operations.
TEXT BOOKS:
1. Computer Science: A Structured Programming Approach Using C, B.A.Forouzan and R.F. Gilberg,
ThirdEdition, Cengage Learning.
2. Programming in C. P. Dey and M Ghosh , Oxford University Press.
Computer Programming 2
Unit-1
Introduction to Computers – Computer Systems, Computing Environments, Computer Languages,
Creating and running programs, Program Development.
Introduction to the C Language – Background, C Programs, Identifiers, Types, Variables,
Constants, Input / Output, Operators(Arithmetic, relational, logical, bitwise etc.), Expressions,
Precedence and Associativity, Expression Evaluation, Type conversions, Statements-Selection
Statements(making decisions) – if and switch statements, Repetition statements ( loops)-while, for,
do-while statements, Loop examples, other statements related to looping –break, continue, goto,
Simple C Program examples.
A Computer is an electronic device that takes data and instructions as an input from the user,
processes data, and provides useful information known as output.
A computer is a system made of two major components Hardware and Software. The
computer hardware is the physical equipment. The software is the collection of programs
(instructions) that allow the hardware to do its job. Following figure represents a Computer System.
The computers can perform complex and repetitive calculations rapidly and accurately
Store large amount of data and information for subsequent manipulations
Provide information to the user in many different forms.
Compare items and make decisions.
These capabilities of computers have enabled us to use them for a variety of tasks.
Applications areas where the computers are used :
Data Processing(commercial use)
Numerical Computing(Scientific use)
Message Communication(E-mail)
Image Processing(animation and industrial use) etc.
Computer Hardware:
The Hardware components of the computer system consists of five parts :
Input Devices
Central Processing Unit(CPU)
Primary Storage
Output Devices
Auxiliary Storage Devices
The computer will be of no use unless it is able to communicate with the outside world. Input/Output
devices are required for users to communicate with the computer.
Input Devices:
The input devices are used to enter information to the computer system. Some of the
examples of input devices are keyboard, Mouse, Scanner, Touch Screen, Joystick, Light Pen etc.
An input device is used to provide data and control signals form the user to an computer.
Output Device:
Output devices are the devices through which the user gets information from the computer.
Some of the examples of output devices are Monitor, LCD, Printer, Plotter, Speakers etc.
If the output is shown on the monitor, we call it as a soft copy. If it is produced on a paper by the
printer, we call it as a hard copy.
The central processing unit (CPU) is the main part of a computer system which is responsible
for all arithmetic calculations, movement of data, and comparison among the data. It can be called as
the brain of the computer.
Registers
The Control Unit stores the instruction set which specifies the operation to be performed by
the computer. Control unit transfers the data and the instructions to the Arithmetic Logic unit.
Simply, it is responsible for supervising the operation of the entire computer system.
The Arithmetic Logic Unit performs arithmetical or Logical operation on the received data.
The Register, is a high speed storage area within the CPU that stores the data to be processed
by the CPU and also stores the processed data. The power and speed of the CPU depends on
the number of registers and the size of each register.
Primary Memory:
The Primary storage, also known as Main Memory, is a place where the programs and data
are stored temporarily during processing i.e., the main memory holds instructions and data when a
program is executing. The data in primary storage are erased when we turn off a personal computer.
There are two types of Main Memory devices namely,
RAM is also called as Read-Write memory, i.e., both read and write operations can be done in
RAM.
It is a type of computer memory that can be accessed randomly, i.e. any byte of memory can
be accessed without touching the preceding bytes.
RAM is volatile in nature i.e., the information present in these types of memory devices is lost
as soon as the power is turned off.
ROM is a type of memory that normally can only be read, as opposed to RAM which can be
both read and written. The contents of ROM cannot be changed.
It is non-volatile in nature i.e., the information present in these types of memory devices is not
lost as soon as the power is turned off.
ROM is most commonly used to store system-level programs that we want to have available to
the PC all the times. For Example, BIOS (Basic Input Output System) programs are stored in
ROM which are need at the time of system booting process.
Cache Memory is a memory placed between CPU and main Memory. It is faster compared
to the primary memory. Parts of the program or data that need to be accessed repeatedly are stored in
Cache Memory.
Auxiliary Storage:
The Auxiliary storage, also known as secondary storage (or external storage), it is the place
where the programs and data are stored permanently. When we turn off the computer, our programs
and data remain in the secondary storage ready for next time we need them. Secondary memory
devices include
Magnetic tapes
Computer Software
Software is a set of programs or collection of programs that are necessary for the functioning
of a computer to perform certain tasks.
A Program is a set of instructions written to carry out a particular task, so that the computer
can follow them.
Computer Software is divided into two broad categories : System Software and Application
software.
System Software
System software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
operating system, system support software and system development software.
The operating system provides services such as a user interface, file and database access.
The primary purpose of this software is to keep the system operating in an efficient manner
while allowing the users access to the system.
In simple words Operating system is as software which interacts with the hardware resources
of the computer directly.
System support software provides system utilities and other operating services.
Examples of system utilities are sort programs and disk format programs.
Operating services consists of programs that provide performance statistics and security
monitors to protect the system and data.
The last system software category, System development software, includes the language
translators that convert programs into machine language for execution ,debugging tools etc.
Application software
Application software is directly responsible for helping user in solving their problems. It is
broken in to two classes: general-purpose software and application-specific software.
General purpose software is purchased from a software developer and can be used for more
than one application.
They are labeled general purpose because they can solve a variety of user computing
problems.
A general ledger system used by accountants and a material requirements planning system
used by a manufacturing organization are examples of application-specific software.
They can be used only for the task for which they were designed they cannot be used for other
generalized tasks.
Each layer represents the connection point user interacts with application software to do some work.
The application software interacts with operating system, which is a part of system software directly
interacts with the hardware. The user can directly interact with operating system whenever needed.
Computing Environment:
Computing Environment is the entire set of conditions under which one operates a computer.
Simply it refers to a hardware platform and the operating system that is used in it.
In this environment, all of the computer hardware components are tied together in our
personal computer (PC). In this situation, we have the whole computer for our self; we can do
whatever we want.
Time-Sharing Environment:
Employees in large companies often work in what is known as a time-sharing environment.
In the time-sharing environment, many users are connected to one or more computers. Also, in
the time-sharing environment, the output devices and auxiliary storage devices are shared by all of the
users.
In the time-sharing environment, all computing must be done by the central computer.
In fact, it is some times so busy that the user becomes frustrated by the computer’s slow
responses. Example for time-sharing environments is a college lab in which a minicomputer is shared
by many students.
Because the work is shared between user’s computers (clients) and central computer (server),
response time and monitor display are faster and the users are more productive.
Computer Language:
The operations of a computer are controlled by a set of instructions called computer program.
Instructions are written to tell the computer:
The communication between two parties, whether they are machines or human beings, always
needs a common languages or terminology. The language used in the communication of computer
instructions known as the programming language. The computer has its own language and any
communication with computer must be in its language or translated into this language.
To write a program for a computer, we must use a computer a language. Over years computer
languages have evolved from machine languages to natural languages.
As computers are made of two-state electronic devices they can understand only pulse and no-
pulse i.e., 1 or 0 conditions. Therefore all instructions and data should be written using binary
codes 1 and 0. The binary code is called machine code or machine language.
Computers do not understand English, Hindi or any other language. They respond only to
machine language hence no need of any translator.
The computer directly starts executing the machine language instructions and it takes less
execution time.
Machine dependent: The computers are not identical in design; therefore, each computer has
its own machine language.
Difficult to use and Error prone: It is difficult to understand and remember various
combinations of 1’s and 0’s representing numerous data and instructions. This makes it
difficult for a programmer to write error-free instructions.
Difficult to debug and modify: checking error locations in machine instructions is as tedious
as writing the instructions. Further, modifying such a program is highly problematic.
The Assembly Language, introduced in 1950s, reduced program complexity and provided
some standardization to build an application. It is considered as a Second-Generation
Programming Language.
Unlike machine level language here we use some codes known as mnemonic codes can be
called as operation code or opcode.
mov al,061h
In the above instruction, the opcode “move” is used to move the hexadecimal value 61 into
processor register al.
In case of assembly language a translator is required to translate assembly language to
machine langue. The translator program used in assembly language called as “Assembler”.
Although symbolic languages greatly improved programming efficiency, they still require
programmers to concentrate on the hardware that they are using. The desire to improve programmer
efficiency and to change the focus from the computer to the problem being solved led to the
development of high- level language, i.e., High- level languages are designed to relieve the
programmer from the details of the assembly language.
High- level languages are to be converted into machine language. The process of converting
them is known as Compilation and the tool used to convert is “compiler”.
In this language, instructions are written using normal English language and mathematical
symbols like +, -, %, / etc.
Readability: Programs written in these languages are more readable than those written
in assembly and machine languages.
The following figure shows the simple English statement in high level language(C) and machine level
language.
Assembler
Compiler
Interpreter
Assembler:
Compiler:
Interpreter:
Interpreter is a type of program translator used for translating higher level language into
machine language. It takes one statement of higher level languages, translate it into machine
language and immediately execute it.
Translation and execution are carried out for each statement. It differs from compiler, which
translate the entire source program into machine code and does involve in its execution.
The advantage of interpreter compared to compiler is its fast response to changes in source
program.
Interpreters are easy to write and do not require large memory in computer.
The disadvantage of interpreter is that it is time consuming.
Thus compiled machine language program runs much faster than an interpreted program.
The source code file must be translated into machine language, which is the job of a compiler. The
c compiler has actually two separate programs: 1. Preprocessor 2. Translator.
The preprocessor reads the source code and prepares it for the translator. While preparing
the code, it scans for special instructions known as preprocessor commands. These
commands tell the preprocessor to look for special code libraries, make substitutions in the
code, and in other ways prepare the code for translation into machine language. The result
of the preprocessing is called the Translation Unit.
After the preprocessor has prepared the code for compilation, the translator does the actual
work of converting the program into machine language while converting translator checks
correctness of each statement. If there are any syntactical errors the process of compilation
ends here and those errors will be listed out by the Compiler. (In this step object code is
created with the extension “.obj”.)
An object module is the code in machine language called “Object File” (ProgramName.obj
file)
Even though the output of the compiler is machine language code, it is not yet ready to run;
that is, it is not yet executable because it does not have the required C and other functions
included.
Linking the program
Linking the program is essential process. It puts together all other program files and functions
that are required by the program.
For example, If the programmer is using sqrt() function, then the object code of this function
should be brought from math.h library of the system and linked to the main() program.
After linking, the file obtained is called "Executable File" (ProgramName.exe file).
The Executable file is loaded into memory for execution by a tool is called “loader”.
Address at which program loaded is informed to CPU. Now CPU runs the program from the
address given by loader.
One very popular development life cycle is the Waterfall model. Depending on the company
and the type of software being developed, this model consists of between five and seven phases.
The water fall model starts with system requirements. In this phase , all the requirements of a
project will be gathered, the system analyst define the requirements.
In the analysis phase, different alternatives will be analyzed from system's point of view.
The design phase determines how the system will be built, the functions of individual
programs and the design of files/database is completed.
In the coding phase, the programs will be written.
In the testing phase, all the programs will be tested together, to make sure that the system
works as a whole.
In the maintenance phase, the project will be put in work into production.
Program Development:
When we are given the assignment to develop a program, we will be given a program
requirements statement and the design of any program interfaces. Also we should receive an overview
of the complete project. Our job is to determine how to take the inputs we are given and convert them
into the outputs that have been specified. This is known as program design.
Program development is a multistep process which consists o the following steps:
Understand the problem
Develop a solution
Write a program
Test the program
Develop a solution:
Once we finally understand the problem, we use three tools in developing a solution.
Structured Chart
Algorithm/Pseudo Code
Flow Chart
A Structured Chart also known as a “Hierarchy Chart” is used to design the whole program,
which shows the relationship of various units. (i.e., the functional flow the program).
Algorithm is the Step by step procedure to solve a problem.
Pseudocode is English- like statements that follow a loosely defined syntax and are used to
convey the design of an algorithm. Pseudo code is part English, part program logic. Its purpose is to
describe, in precise algorithmic detail, what the program being designed is to do. This requires
defining the steps to accomplish the task in sufficient detail so that they can be converted into a
computer program. Most of the statements in the pseudocode are easy to understand.
Flowchart: Graphical representation of an algorithm is called as flowchart. A flowchart is a
program design tool in which standard graphical symbols are used to represent the logical flow of
data through function.
Writing a Program:
After developing a solution the program has to be written in any programming language.
After writing the program, it has to be tested to check if there are any errors or not. There are
basically two kinds of testing techniques.
a. Black Box Testing
b. White Box Testing.
Black Box Testing is done by the testing Engineer and the user.
These people don’t know what is there inside the program. They will just test the program
using the given requirements set.
White Box Testing done by the programmer who knows what is there inside the program and
he can test each line of instruction in a program.
There is a time and space complexity associated with each algorithm. Time complexity
specifies the amount of time required by an algorithm and space complexity specifies the amount of
space required. The algorithm that ensures best time and space trade off should be chosen for
obtaining the desired solution.
Features of an algorithm:
Categories of an algorithm:
Sequence: In this category all the instructions are performed one after the other.
Selection: In the selection, instructions will be executed based on the condition, i.e., if the condition
is true, some block of statements are executed; else if is false, another block of statements gets
executed
if(condition)
then statement;
if(condition)
then statement1;
else statement2;
Iteration: In this category some of the instructions will be performed repeatedly for some specific
number of times. Iteration statements are written using the following format.
Repeat
Statements;
Until(Condition)
The statements will be executed continuously if the condition is true.
If the condition becomes false the next step will be executed.
Pseudo Code:
Sequence, selection, iteration; all are same for Pseudo code and algorithm.
Example Algorithms:
Flow chart:
A Flow chart is a Graphical representation of an Algorithm or a portion of an Algorithm.
Flow charts are drawn using certain special purpose symbols such as Rectangles, Diamonds, Ovals
and small circles. These symbols are connected by arrows called flow lines.
(or)
The diagrammatic representation of way to solve the given problem is called a flow chart.
The following are the most common symbols used in Drawing flowcharts:
By using the basic flow chart symbols, we can design any program. Then we will combine them to
design solutions to more complicated problems. There are three design structures, such as Sequence
Selection and loop.
Sequence Structure: It is the simplest, because it is nothing more than a series of statements
performed one after another. It is a sequence because the flow always continues in same direction
every time the structure is executed. A sequence may include number of instructions, but each would
be done in turn in the same order.
Selection Structure: selection structure uses a decision to ask some question. This structure includes
the decision and the operation to be performed in response to the decision. There will be two exists
from the decision, but both of these branches are still a part of the selection structure, then both
branches must rejoin a single flow line to exit the structure. Using these selection structure different
steps may be executed depending on the result of the decision test.
Loop Structure : The loop structure are used to execute a sequence of steps in a number of times or
until a particular condition is true. This structure will have a decision, one or more additonal symbols
indicating the steps to be done within the loop, and a flow line that sends control back to the
beginning of the loop.
There are two loops are available Top Tested loop and Bottom Tested Loop
The top tested loops are leading decision loops means the decision is evaluated always at the
first statement of the of the loop. If it is true, the control follows the flow lines that goes into the loop.
If it is false , control follows the first statement after the loop.
The bottom tested loop is a trailing decision loop , means the decision is always evaluated at
the last statement of the loop. The body of the loop will be executed once before control even gets to
the loop test. If the condition is true then the control follows the flow lines that goes into the loop. If it
is false , control follows the first statement after the loop.
Example Flowcharts:
Introduction to C Language:
C is one of the most popular programming language, it was developed by Dennis Ritche at
AT & T ( American Telephone & Telegraph) Bell Laboratories at USA in 1972.
It is an upgraded version of two earlier languages, called BCPL and B, which were also developed at
Bell Laboratories.
The root map for all modern computer languages are started through the ALGOL language in
early 1960’s after then COBOL( Common Business Oriented Language) was used for Commercial
Application, FORTRAN was being developed for Scientific Application. At this stage, people started
thinking about the single language which can program all possible applications.
Many other high-level languages have been developed based on C. For instance, Perl is a
popular programming language in World Wide Web (WWW) design across the Internet. Perl actually
borrows a lot of features from C. If you understand C, learning Perl is becomes easy. Another
example is the C++ language, which is simply an expanded version of C, although C++ makes object-
oriented programming easier. Also, learning Java becomes much easier if you already know C.
During 1970s, C had evolved into what is now known as “Traditional C”. The language
became more popular after publication of the book “The C Programming Language” by Brian
Kernighan and Dennis Ritche in 1978. The book so popular that the language came to be known as
“K & R C” among the programming community.
The rapid growth of C led to the development of different versions of the language. To assure
that the C language remains standard, in 1983, American National Standards Institute (ANSI) formed
a technical committee to define a standard for C. the committee approved a version of C in 1989
which is now known as ANSI C. It was then approved by the international standard Organization in
1990. This version of C is also referred to as C89.
new features and C is no exception. The Standardization Committee of C felt that a few features of
that a new features of C++ / java , if added to c , would enhance usefulness of the language. The
result was the 1999 standard for c. this version is usually referred as C99.
Although C99 is an improved version, still many commonly available compilers do not support new
features incorporated in C99.
Features of C Language:
C is general purpose , structured programming language.
C is highly portable (i.e., it can be run in different operating systems environments).
C is robust language whose rich set of built in functions and operators can be used to write any
complex programs.
C is well suited for writing system software as well as application software.
C is a middle level language . it performs the task of low level language as well as high level
language. We can write the codes for operating system , Application programs , Assembly
language programs in C language.
C has ability to extend itself. We can continuously add our own functions to the existing
library functions.
C programs are fast and efficient. This is due to its variety of data types and powerful
operations.
C language allows manipulation of data at the lowest level i.e., bit level manipulation. This
features is extensively useful in writing system software program.
C can be applied in systems programming areas like Compiler , Interpreters and Assemblers
etc.
1. Documentation section
2. Linking section
3. Definition section
Declaration section
Executable section
1. Documentation Section :
Documentation section comes first , it consist of set of comment lines giving name of the
program , the name of the author and other details like flow of the program , describing or description
about the functions , variables tec.
The comment lines are nothing but same of kind of statements which are to be placed between
the delimiters like /* & */. The complier ignores or doesn’t compiles the comments. Thus we can say
that comments are not a part of executable program
The programmer can use frequently any number of comments that can be placed any where
in the program.
// this is a single comment line
/* -------------------------------------
--------------------------------*/ this is an example of multi comment lines
2. Link Section :
The Link Section provides instruction to the compiler to link functions from the system
library. In general the link section contains preprocessor directive statements. These statement starts
with a pound sign(#). The preprocessor statements are used to include the header files to the current
program. Each header file by default has an extension of .h. the header file should be included by
using #include directive as given below.
e.g. #include <stdio.h>
3. Definition Section :
The Definition Section used to define all symbolic constants and assign them some value.
e.g. #define MAX 25
Here #define is a compiler directive which tells the compiler whenever MAX is found in the
program replace it with 25.
The execution of the program always begins with the main(). Except the main() section other
sections may or may not necessary. The program execution starts from the opening brace { and ends
with closing brace }. Between two braces the programmer should declare declaration and executable
parts.
Declaration part : The Declaration part declares all variables that are used in executable part.
Initialization of variables can be done in this section.
Executable part : The Executable part contains the statements followed the declaration of variables.
This part contains set of statements or a single statement. These statements are enclosed between the
braces.
6. Subprogram Section :
The Sub Program section consist of all user defined functions that are called in the main
function. User defined functions are generally placed immediately after the main function, although
they appear in any order.
/* simple program in c */
#include<stdio.h>
main() // starting point of the program
{
printf(“welcome to c programming”);
/*printf() is a predefined function or built-in-function which is defined in stdio.h (standard
input/output header file). It is used to print the data that is passed within double quotes on the console
or output screen*/
} /* End of main */
In case of Turboc IDE the following are shortcuts to invoke Compiler, linker
The process of executing a C program is slightly different under Dos and UNIX.
A C program must be converted into an executable file(i.e., a file with an .exe) to run it
in DOS. First the c program has to be typed in a file using an editor. This file is called source
file often, c compilers in many companies supplying C compilers for DOS. Some of the
popular companies are Borland International , Microsoft Corp etc.
Start ----- my computer ------ c drive ------ tc or TURBOC3 ----- click on Tc.exe
Now press ALT+F9 to compile the program. If the program contains any errors those errors are
displayed to the programmer, no errors then object file is created with extension of .obj.
Now we need press f9 then linker software is invoked. The linker combines different object files to
produce the actual executable file.
Now press ctrl+f9 to run the program , observe that screen will flicker for a moment, in reality the
program has been executed by the IDE , it took a very short time to run , during which is printed on
the screen and came back to the IDE. So how can we sure that the program has printed exactly what
we wanted? For this we must view the output screen. By pressing ALT+F5 key we can see the
message that has been printed on the screen after seeing the result of the program press any key to get
back to the main IDE.
This comes a program called tcc.exe in turboc & turboc++. The program is called bcc.exe in
Borland C++. These are the programs that have to be invoked from the command line, and their
purpose is to convert the c program into executable fle.\
For example, assuming that the file hello.c has been created using an editor, the command
tcc hello.c
type at the DOS prompt will convert the c programs hello.c to an executable program called
hello.exe.
In both of these case (IDE or Command line ) an executable file called hello.exe would have been
generated. This program is standalone executable i.e. , it can run independently without the help of
any other file, the IDE or the compiler.
Virtually every UNIX system has a C compiler called cc. on same UNIX systems a C compiler
called gcc exits. Both are command line compilers. Their purpose is to convert the c program into
executable code.
The program has to be typed into a file separately using an editor such as vi etc. thereafter the
command
cc hello.c
will create an executable file called a.out by default. This file can be executed by typing a.out at the
prompt.
C – Basics
A programming language should be designed to support certain kind of data, such as numbers,
characters, strings etc. to get useful output known as information. A program is a set of statements for
a specific task, which will be executed in a sequential form. These statements/instructions are formed
using certain words and symbols according to the rules known as syntax rules. Every program must
follow accurately the syntax rules by the language.
C Character Set
The Characters used to form words, numbers and expressions depend upon the computer on
which the program runs. The characters in C are classified in the following categories.
1. Letters
2. Digits
3. White spaces
4. Special characters
Letters
A ……………………......Z
a…………………………z
Digits
0……………………9
White Spaces
Blank Space
Horizontal tab
Vertical tab
New Line
Form feed
Special characters
C-TOKENS:
Tokens are individual words and punctuations marks in English language sentence. The smallest
individual units are known as C tokens.
Keywords:
The C keywords are reserved words. All keywords have fixed meanings and these meaning cannot
be changed. Keywords serves as basic building blocks for programs. All keywords must be written in
lower case. The following are list of keywords.
do if static while
Identifiers:
Identifiers are names given to variables, functions and arrays etc. these are user
defined names and consist of sequence of letters and digits with a letter as a first character.
Both uppercase and lower case letters are permitted although lower case letters are commonly used.
Rules for identifiers :
1. The First character of an identifier must be alphabetic character or under score.
2. The identifiers must contain only of alphabetic characters, digits or underscore
3. The identifiers cannot be a keyword
4. No space and special symbols are allowed.
The underscore is used to link the two words in long identifiers or it is used to separate two different
words.
#define N 10
#define a 15
DATA TYPES :
To represent different types of data in C program we need different data types. A data type is
essential to identify the storage representation and the type of operations that can be performed on
that data. C supports four different
classes of data types namely
INTEGER
TYPE:
The integer
data type is
used to store the
whole numbers.
The integers
does n ’t
contain the
decimal point. They take the binary form for storage. On a 16-bit machine the range of integer values
is -32768 to +32767.
Signed integers
Signed integers are those integers which uses 15 bits for storing the magnitude of a number
and 1 bit to store the sign. The left most bit i.e., 16th bit is used for storing the sign, it is ‘1’ for a
negative number and ‘0’ for the positive number.
Unsigned integers
Unsigned integer use all 16 i.e., (15+1) bits to store the magnitude i.e.,these are the whole
numbers that always hold positive values and the sign bit(left most bit) also contains the value.
(signed integers include sign whereas unsigned integers doesn’t include sign).
CHARACTER TYPE
Characters are generally stored in 8 bits of the internal storage and a single character can be defined as
char data type. Each character has an equivalent ASCII value i.e., these characters are internally
stored as integers.
Floating point (or real ) numbers are stored in 32 bits with the 6 digits of precision. These
numbers are defined by using the keywords float and double, whereas the double data type uses the
64bits with the 14 digits of precision.
Derived datatypes are used in ‘C’ to store a set of data values. Arrays and Structures are
examples for derived data types.
C Provides a facility called typedef for creating new data type names defined by the user. For
Example ,the declaration ,
typedef int Integer;
makes the name Integer a synonym of int.Now the type Integer can be used in declarations
,casts,etc,like,
Integer num1,num2;
Which will be treated by the C compiler as the declaration of num1,num2as int variables.
“typedef” ia more useful with structures and pointers.
Variable:
A variable is an identifier that is used to store some specified type of value. The variable may
take different values at different times during the execution. i.e. , it is the named memory location.
Variable Declaration: After designing suitable variable names, we must declare the variables in
declaration part and this declaration tells the compiler what the variable name and type of the data that
the variable will hold.
Syntax
Data_type v1,v2,v3……vn;
Initializing Variables: Initialization of variables can be done using assignment operator ( = ). The
variables can be initialized while declaration itself.
Syntax :
Variable_name = constant;
Or
Example 1: int i;
float b;
char c;
i=10;
b=32.22;
c=’s’;
float b1=12.22;
char a=’k’;
printf() : printf() is a predefined or built functions in C. which is used to print message and variables
on the output screen.
Syntax : printf(“message”);
printf(“\n wel come to C programming “); // prints the data on the screen.
scanf() : scanf() is a predefined or built function in C, which is used to read information or values
from the keyboard.
Constants :
Constants are data values that cannot be changed during the execution of a program. In ‘C’
constants can be classified as follows.
Numeric Constants:
Integer Constants: These are the sequence of numbers from 0 to 9 without decimal points or
fractional part or any other symbols. There are three types of integer constants which forms different
number system.
Octal Number: Octal integer consists of any combination of digits from the set 0 through
7 , with leading 0. Some of the examples of octal integer are
Ex : 037 0 0435
Ex : 0X2 0x5F
The largest integer value that can be stored is machine – dependent. It is 32767 on 16-bit
machines and 2,1247,483,647 on 32-bit machines.
Real Constants : Integers numbers are inadequate to represent quantities that vary continuously, such
as distances , heights , temperatures , prices and so on. These quantities are represented by numbers
containing fractional parts like 17.548. such numbers are called real or floating point constants.
A real number may also be expressed in exponential ( or scientific) notation. For example
the value 215.65 may written as 2.1565e2 in exponential notation. e2 means multiply by 10
^ 2. The general form is :
mantissa e exponent
The Mantissa is either a real number expressed in decimal notation or an integer. The
exponent is an integer number with an optional plus or minus sign.
A single character constant contains a single character enclosed within a pair of single quote
marks.
It may be an alphabet, digit , white space or special character.
We can’t write more than one character in single quotes.
Ex: ‘a’ ‘A’ ‘ ‘ ‘9’ ‘^’
Character are internally represented by integers ASCII.( American Standard Code for
Information Interchange)
Ex: ‘a’ – 97 ‘A’ – 65 ‘0’ – 48 etc.
There are 256 ASCII values.
String Constant
A String constant is a sequence of characters enclosed in double quotes. The characters may
be letters, numbers, special characters and blank space.
Ex : “hello!” , “123#7” , “skr27”
Remember that a character contant (e.g., ’x’) is not equivalent to the single character string
constant(e.g., “x”). further a single character string constant does not have an equivalent
integer value while a character constant has an integer value.
BACKSLASH CONSTANTS
The backslash constants are predefined which are to be used in o/p functions.
\n new line
\t horizontal tab
\v vertical tab
\a audible alert ( bell )
\r carriage return
\b back space
\f form feed
\’ single quote
\” double quote
\? Question mark
\\ back slash
\0 null
Operators:
An operator is a symbol that tells the compiler to perform certain mathematical or logical
manipulations. They form expressions.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
6. Conditional operator
8. Special operators
+ Addition 2+9=11
- Subtraction 9-2=7
* Multiplication 2*9=18
/ Division 9/3=3
All the above operators are binary operators as they act upon two operands.
An arithmetic operation involving only real operands(or integer operands) is called real arithmetic(or
integer arithmetic). If a combination of arithmetic and real is called mixed mode arithmetic.
relation take certain decisions for that comparison we use relational operators. For example we my
compare the age or salaries of two persons or the price of two items and so on.
== Is equal to 2==2 1
It is the form of
When arithmetic expression are used on either side of a relation operator , the arithmetic expression
will be evaluated first and then the result compared.
In above
program
the true condition returns 1 and false returns 0. In this example first and third conditions are false and
second and fourth conditions are true.
/* program to accept two numbers and find out which one is greater */
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2;
clrscr();
printf("\n Enter any two integer numbers ");
scanf("%d%d",&num1,&num2);
if(num1>num2)
printf("\n %d is greater ",num1);
else
printf("\n %d is greater ",num2);
getch();
}
Output:
3. Logical Operators : Logical operators are used to combine the results of two or more conditions
or expressions. ‘C’ has the following logical operators.
|| --------- logical OR
!----------logical NOT
The logical AND (&&) operator is usually used in situation , where a set of statements are to be
executed, if two or more expressions are true.
The logical OR (||) operator is used in situation , if either of them ( at least ) one condition must be
true form two or more conditions or expressions. Then the set of statements are executed.
The logical NOT (!) operator reverse the value of the expression it operates on. i.e., if makes a true
expression false and false expression true.
Non-Zero Non-Zero 1 1
Non-Zero 0 0 1
0 Non-Zero 0 1
0 Non-Zero 0 0
Op-1 !Op-1
Non-Zero 0
0 1
Output :
/* write a program to display 1 if inputed number is either 1 or 100 otherwise 0. Use logical or
operator*/
#include<stdio.h>
#include<conio.h>
main()
{
int num,res;
clrscr();
printf("\n enter any number ");
scanf("%d",&num);
res=(num==1 || num==100);
printf("\n res : %d ",res);
getch();
}
/*In the above program the or operator checks two conditions. if one of the conditions satisfies 1 is
assigned to res otherwise 0.*/
Output :
/* write a program to display 1 if inputted number is between 1 to 100 otherwise 0. Use logical &&
operator*/
#include<stdio.h>
#include<conio.h>
main()
{
int num,res;
clrscr();
printf("\n enter any number ");
scanf("%d",&num);
res=(num>=1 && num<=100);
printf("\n res : %d ",res);
getch();
}
/* In the above program the and operator checks two conditions. if both condtions are
conditions satisfies 1 is assigned to res otherwise 0.*/
output :
5. Assignment Operators : They are used to assign the result of an expression to a variable. The
assignment operator is '='.
X = 10; // x is variable
x=x+1; or x+=1;
C provides compound assignment or short hand assignment operators are used to assign a
new value to a variable after performing a specified operation.
+= x+=y x=x+y
- = x-=y x=x–y
* = x*=y x = x*y
/= x/=y x = x/y
%= x%=y x=x%y
C has two vey useful operators , they are increment (++) and decrement (--) operators.
The operator ++ adds 1 to the variable or operand, while – subtracts 1 from the variable or operand.
Both are unary operators. Because they act upon only one variable.
A prefix increment operator first adds 1 to the operand or variable and then the result s assigned to the
variable on the left. On the other hand , a postfix increment operator first assigns the value to the
variable on left and then increments the operand.
Output :
7. Conditional Operator : A ternary operator pair "? :" is available in C to construct conditional
expressions of the form
exp1 or condition? exp2 : exp3;
It work as
the ‘ ? : ’ operator acts as a ternary operator, it first evaluate the condition , if it is true (non- zero)
then exp1 is evaluated , if the condition is false (zero) then the exp2 is evaluated.
8. Bit wise Operators : C supports special operators known as bit wise operators for manipulation of
data at bit level i.e., these operations on the bits of a binary format of an integer. They are not applied
to float or double.
Operator Meaning
| Bitwise OR
^ Bitwise exclusive OR
~ one's complement
9. Special Operators : These operators which do not fit in any of the above classification are
,(comma), sizeof, Pointer operators(& and *) and member selection operators (. and ->).
The operations are performed from left to right and the result obtained at last operation is
assigned to a variable.
j=(i+=2,++i,i*3);
Here first i+=2 is performed (result is i=2) then ++i (result is i=3 and at last i*3 is performed
(result is i=9) and the resultant value is stored in j.
j=9
#include<stdio.h>
#include<conio.h>
main()
{
int n1,n2,n3;
clrscr();
printf(“\nEnter two integers : “);
scanf(“%d%d”,&n1,&n2);
printf(“\n-----Before Swaping-----\n”);
n3=n1,n1=n2,n2=n3;
printf(“\n-----After Swaping-----\n”);
getch();
Syntax : sizeof(operand)
Syntax : &(variable)
/* program to use & and sizeof operator and determine the size of integer and float variables*/
#include<stdio.h>
#include<conio.h>
main()
{
int x=2;
char c='a';
float y=2;
clrscr();
printf("\n sizeof(x) = %d bytes",sizeof(x));
printf("\n sizeof(c) = %d bytes",sizeof(c));
printf("\n sizeof(y) = %d bytes",sizeof(y));
printf("\n address of x = %u bytes and y = %u",&x,&y);
getch();
}
Type Casting:
Type Casting or Type conversion refers to the process of conversion of one data type to
another data type.
type – name is one of the standard C data types whereas expression may be a constant,
variable or an expression.
Ex: float a=9.6;
float b=3.2;
int c = (int)a%(int)b;
Expression
Precedence is used to determine the order in which the different operators in a complex
expression are evaluated. Associativity is used to determine the order in which operators with the
same precedence are evaluated in a complex expression. Precedence is applied before associativity
the order in which expressions are evaluated. Associativity is then applied , if necessary.
() Parentheses
[] Brackets(array subscript)
-- Post decrement
+ Unary plus
- Unary minus
++ Pre increment
-- Pre decrement
~ One’s complement
* Multiplication
/ Division Left-to-right 3
% Modules
+ Addition
- Subtraction Left-to-right 4
== Equal to Left-to-right 7
!= Not equal to
| Bitwise OR Left-to-right 10
|| Logical OR Left-to-right 12
?: Ternary Right-to-left 13
+=
-=
*=
/=
&=
^=
|=
<<=
>>=
, Comma Left-to-right 15
Associativity:
Left-to-right Associativity:
The following shows an example of left-to-right associativity. Here we have four operators of
the same precedence (* / % ).
3*8/4%4*5
Associativity determines how the subexpressions are grouped together. All of these operators have the
same precedence(3). Their associativity is form left to right. So they are grouped as follows:
(((3*8)/4)%4)*5)
The value of this expression is 10.
Several operators have right-to-left associativity as shown in the precedence table. For
example , when more than one assignment operator occurs in an assignment expression , the
assignment operators must be interpreted form right-to-left. This means that rightmost expression will
be evaluated first then its value will be assigned to the operand on the left of the assignment operator
and the next expression will be evaluated.
a+=b*=c-=5
is evaluated as
(a + = (b*=(c-=5)))
Which is expanded as
(a=a+(b=b*(c=c-5)))
If a has an initial value of 3 , b has an initial value of 5 , and c has an initial value of 8 ,these
expressions become
(a=3+(b=(5*(c=8-5)))
Which results in c being assigned a value of 3 , b being assigned a value of 15 , and a being assigned a
value of 18. The value of the complete expression is also 18.
Evaluation of Expression:
While evaluating an expression the operator with highest precedence will be evaluated first,
then the second highest precedence operator and the operator with least precedence will be evaluated
last.
* / % have higher priority level (3)
+ - have lower priority level(4)
Let us consider the following expression a%3-b/2+(c*d-5)/e
Where a=30,b=10,c=11,d=5,e=10
Replacing the values of a, b, c ,d, e in the expression we get
Step 1 30%3-10/2+(55-5)/10
Step 6 0 (+ operation )
/* program to demonstrate operator precedence */
#include<stdio.h>
#include<conio.h>
main()
{
int a=30,b=20,c=10;
clrscr();
printf(" \n a*b+c : %d", a*b+c); // 610
printf(" \n a*(b+c) : %d", a*(b+c)); // 900
printf(" \n a+b*c : %d", a+b*c); //230
printf(" \n a-b/c : %d", a-b/c); //28
printf(" \n --a+b*c : %d", --a+b*c); //29+200=229
printf(" \n a-b++/(c-3) : %d",a-b++/(c-3)); //27
getch();
}
Output :
Input / Output
We know that input , process, output are the three essential features of computer program. The
program takes some input data, processes it and gives the output. we have two methods for
providing data to the program.
Assigning the data to the variables in a program
By using the input/output statements.
In ‘C’ language two types of Input/Output statements are available , and all input and output
operations are carried out through function calls. Several functions are available for input/output
operations in C. These functions are collectively known as the standard I/O library.
These statements are used to Input or Output a single/group of characters. Or these statements
or functions are used to accept/display the single or group of characters from/to the user.
getchar() : getchar() is used to read a single character from the input device(keyboard).
varname=getchar();
Ex : char x;
X=getchar();
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main()
{
char ch;
printf("\n Enter any character ...");
ch=getchar();
if(isalpha(ch)>0)
printf("\n It is a alphabet ");
else if(isdigit(ch)>0)
printf("\n It is a digit ");
else
printf("\n It is alphanumeric ");
getch();
}
/* isalpha() is predefined function from ctype.h file. It is used to check whether the character variable
consists of alphabet or not. If it consist of alphabet it returns 1 otherwise 0. */
Output :
putchar() : The putchar() function is used to display one character at a time on the standard output
device.
Syntax : putchar(character_variable);
Ex : char ch=’a’;
putchar(ch);
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\n Enter any Alphabet in lower case \n....");
ch=getchar();
ch=ch-32;
putchar(ch);
getch();
}
/* a to z is 97 to 122
A to Z is 65 to 90
0 to 9 is 48 to 57
back space is 8
enter key is 13
space bar is 32 */
output :
getc() : the getc() is used to accept a single character from the standard input to a character variable.
putc() : the putc() is used to display a single character on the standard output device.
char ch=’y’;
putc(ch);
gets() : the gets() function is used to read the string from the standard input device(keyboard).
puts() : the puts() function is used to display the string to the standard output devive(monitor).
The getch() read a single character directly from the keyboard , without echoing to the screen.
The getche() reads a single character form the keyboard and echoes it to the screen.
#include<stdio.h>
#include<conio.h>
main()
char c,ch;
clrscr();
c=getch();
ch=getche();
getch();
Output :
Formatted input/output refers to input and output, that has been arranged in a particular
format. The following are the input and output functions
we have already used this input function in number of examples. the scanf() functions is used to read
data from the standard input device i.e, keyboard.
Scanf() : The scanf() statement or function reads all types of data values. It is used for runtime
assignment of variables. The scanf() statement also requires conversion symbol to identify the data to
be read during the execution of a program.
The scanf() function requires ‘&’ operator called address operator. The role of address
operator in scanf() function is to indicate the memory location of the variable , so that the value read
would be placed at that location. The scanf() function also returns values. The return value is exactly
equal to the number of values correctly read.
%c Single character
%s String
%f Float values
%u Unsigned decimal
%o Octal number
#include<stdio.h>
#include<conio.h>
main()
int n1,n2,n3,sum;
float avg;
clrscr();
scanf("%d%d%d",&n1,&n2,&n3);
sum=(n1+n2+n3);
avg=(float)sum/(float)3;
getch();
Output :
printf() : The printf() function prints all types of data values to the console. It requires conversion
symbol and variable names to print the data. The conversion symbol or control string and variable
names should be same in number.
main()
int x=2;
float y=2.2;
char z=’c’;
printf(“\n %d %f %c”,x,y,z);
main()
int y=65;
clrscr();
printf(“ %c %d “,y,y);
Output :
A 65
In the above example the integer variable ‘y’ contains value 65 , the variable ‘y’ is printed using
conversion symbols integer and character. As shown in the output , the %c converts numberic 65
value to its corresponding character A. The %d prints the value of 65, as it is , because the variable is
of an integer type. Some times if no conversion is possible between two data types ; some garbage
value is printed.
7. Write a program to find the size of integer variable , character variable , float variable.
8. Write a program to accept the length and breadth of a rectangle and calculate the area of
rectangle.
9. The total distance travelled by vehicle in ‘t’ seconds is given by distance = ut+1/2at*t where
‘u’ is the initial velocity(m/sec).
‘a’ is the accerleration(m/sec*sec).
Write a C program to find the distance travelled at regular intervals of time given the values of
‘u’ and ‘a’.
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
double a,u,t,d;
clrscr();
printf("\n Enter the values of initial velocity(u), acceleration(a) and time(t) :");
scanf("%lf%lf%lf",&u,&a,&t);
d=u*t+0.5*a*t*t;
printf("\n Distance travelled by vehicle = %lf meters",d);
getch();
}
10. Write a program to calculate slope and midpoint of a line (by giving input as two points).
#include<stdio.h>
#include<conio.h>
main()
float x,y,x1,x2,y1,y2,slope;
clrscr();
scanf("%f%f",&x1,&y1);
scanf("%f%f",&x2,&y2);
slope=(y2-y1)/(x2-x1);
x=(x1+x2)/2.0;
y=(y1+y2)/2.0;
getch();
11. Write a program to read the values of x,y and z and print the results of the following
expressions
a=(x+y+z)/(x-y-z) , b = (x+y+z)/3 , c=(x+y)(x-y)(y-z)
12. Write a program to display the system current date and time.
13. Write a program to accept the values of a,b,c and calculate b*b-4*a*c
14. Write a program to print the numbers from 1 to 10.
*********************************************************************************
***************************************************************************
Statements :
A statement causes an action to be performed by the program. It translates directly in to one or more
executable computer instructions.
1. Null Statements
2. Expression Statements
3. Return Statements
4. Compound Statements
5. Conditional Statements
6. Labeled Statements
7. Switch Statements
8. Iterative Statements
9. Break Statements
10. Continue Statements
11. Goto Statements
Null Statements
Eg //null statement
Although they do not arise often, there are syntactical situations where we must have a statement but
no action is required .In these situations we use the null statement.
Expression Statements
Eg : a=2;
Return Statement
A Return Statement terminates a function. All functions ,including main, must have a return
statement. Where there is no return statement at the end of the function ,the system inserts one with a
void return value.
The return statement can return a value to the calling function. In case of main ,it returns a value to
the operating system rather than to another function. A return value of zero tells the operating system
that the program executed successfully.
Compound Statement
A Compound Statement is a unit of code consisting of zero or more statements .It is also known as a
block. The compound statement allows a group of statements to become one single entity.
A Compound Statement consists of an opening brace ,an optional declaration and definition
section ,and an optional statement section ,followed by a closing brace.
Eg: {
int y;
int z;
x=1; //Statements
y=2;
} //End Block
Selection Statements :
A Program is nothing but the execution of sequence of one or more statements. This is known as
sequential flow of control. In practical applications there are a number of situations where one has to
change the order of the execution of statements based on the conditions. This involves a decision
making condition to see whether a particular condition is satisfied or not. If the condition is true then
a set of statements are executed otherwise another set of statements are executed.
The C language provides a numbers of program control statements or selection statements that can
be used to control the way of execution of the program. These include
1. IF statements
2. Switch
3. Goto
The if statements is a powerful decision making statement and is used to control the flow of execution
of statements. It is basically a two-way selection or decision statement. It takes the following form :
1. Simple if
2. if…..else statement
3. Nested if….else statement
4. else if ladder
Simple if :
Syntax :
if ( Test Expression )
Statement-block;
Statement-x;
The statement block may be a single or group of statements. if the test expression or condition is true
then the statement block will be executed otherwise the statement block will be skipped and the
execution will jump to the statement-x.
Remember , when the condition is true both the statement-block and the statement-x are executed in
sequence.
In the above program the values of the variable num is entered through the keybord. The value
of num is checked with if statement num<10. If the num value is less than 10 then print the message
“Entered number 8 < 10”.
Note: If we want to execute multiple statements in the if statement, that statements must be blocked
with in braces.
The program reads the value of n1,n2 through scanf() function and assigned to variable m. if
statement checks the condition and executes the block of statements.
if…..else statement
It is observed that if statement in the previous programs executes only when the condition is true. It
does nothing when the condition is false.
The if….else statement takes care of true as well as false conditions. it has two blocks. One
block is for if and it is executed when the condition is true. The other block is of else and it is
executed when the condition is false.
/* program to convert a character from lower case to upper case by using predefined functions */
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main()
{
char ch;
clrscr();
printf("\n Enter any alphebet in lower case or upper case ");
ch=getchar();
if(islower(ch))
putchar(toupper(ch));
else
putchar(tolower(ch));
getch();
}
/* toupper and tolower are predefined functions from ctype.h file.
islower is used to check whether the character is in lowercase or not
if it is lower case character then it returns 1 otherwise 0.
toupper is used to convert the given character into uppercase.
tolower is used to convert the given character into lowercase.*/
output :
/* write a program to read the values of a,b,c through the keyboard. add them
and after addition check if it is in the range of 100 & 200 or not.*/
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c,d;
clrscr();
printf("\n Enter three numbers :");
scanf("%d%d%d",&a,&b,&c);
d=a+b+c;
if(d<=200 && d>=100)
printf("\n sum is %d which is in between 100 & 200 " ,d);
else
printf("\n sum is %d which is out of range ",d);
getch();
}
Output :
Nested If :
When a series of if..else statements are occurred in a program. We can write one if..else statement in
another if…else statement called nested if. (simple if…else within another if…else is referred as
nested if.
--------------------------------------------------------------------------------------------------------------------
If…else ladder
There is another way of putting ifs together when multipath decisions are involved. A multipath
decision is a chain of ifs in which the statement associated with each else is an if.
The conditions are evaluated from the top, downwards. As soon as condition is found to be true,
statement associated with it is executed. When all the n conditions become false, then the final else
containing the default statement will be executed.
/* write a program to accept a character and check whether it is vowel or consonant or digit or
special symbol*/
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\n Enter any character ");
scanf("%c",&ch);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("\n ***********v o w E L **************");
else if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
printf("\n***********v o w E L ************** ");
else
printf("\n ***********C O N S O N A N T**************");
getch();
}
Output :
Switch Statement :
Switch statement tests the value of a given variable or result of the expression against a list of
case values and when a match is found a block of statements associated with that case is
executed.
The expression or variable must be an integer or character type.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("\n Enter any character ");
scanf("%c",&ch);
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : printf("\n Vowel ");
break;
default : printf("\n Consonant ");
break;
}
getch();
}
Output :
switch(choice)
{
case 1 : printf("\n Enter any two numbers ");
scanf("%d%d",&a,&b);
res=a+b;
printf("\n Sum of two numbers : %d ",res);
break;
While Loop :
while is an entry controlled loop. First condition is evaluated if it is true then body of the loop
is executed. After executing the body, condition is once again evaluated ,if it is true body is executed
once again. This process continues as long as condition is true. The body of the loop may have one or
more statements.
Note: The braces are not required if body contains only one statement.
Programs
/*write a program to find the sum of numbers from 1 to n( the value of n is accepted from the
keyboard)*/
Output : suppose the value of n is 10 then the output must be 1+2+3+4+5+6+7+8+9+10=55
#include<stdio.h>
#include<conio.h>
main()
{
int i=1,n,sum=0;
clrscr();
printf("\n %d * %d = %d ",n,i,n*i);
i++;
}
getch();
}
/* write a program to find the sum of all digits in a given number*/
Explanation : let us consider n=123 then we need find sum of all digits in it i.e, 1+2+3=6
#include<stdio.h>
#include<conio.h>
main()
{
int n,sum=0,rem=0,n1;
clrscr();
printf("\n Enter any number ");
scanf("%d",&n);
n1=n;
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
printf("\n Sum of digits in %d numbers is %i ",n1,sum);
getch();
}
Output :
}
Output :
{
f3=f1+f2;
f1=f2;
f2=f3;
printf("\t%d",f3);
i++;
}
getch();
}
Output :
do while:
do-while is exit controlled loop. In some cases it might be compulsory to execute the body of
the loop before the test is performed. Such situations can be handled with the help of the do
statement.
It is also repetitive statement and executes the body of the loop once irrespective of the
condition , then checks the condition and continues the execution until the condition becomes
false.
For Statement :
For is an another entry controlled loop. The general form of the for loop is
Syntax :
This process continues till value of the control variable fails to satisfy the condition.
/*write a program to print all even numbers from 1 to 100 and also print sum and count of all even
number */
#include<stdio.h>
#include<conio.h>
main()
{
int i,count=0,sum=0;
clrscr();
printf("\n All Even Numbers from 1 to 100 ");
for(i=1;i<=100;i++)
{
if(i%2==0)
{
printf("\t %d" ,i);
sum=sum+i;
count++;
}
}
printf("\n Sum of all Even Numbers from 1 to 100 is %d ",sum);
printf("\n Count of all Even Numbers from 1 to 100 is %d ",count);
getch();
}
Output:
if(sum==n1)
printf("\n %d is Armstrong ",n1);
else
printf("\n %d is not Armstrong ",n1);
getch();
}
Output :
for(i=0;i<n;i++)
res=res*x;
printf("\n %ld^%ld is %ld ",x,n,res);
getch();
}
Output :
/* write a program to print numbers from 9 to 1 and display their square root*/
#include<stdio.h> Output :
#include<conio.h>
#include<math.h>
main()
{
int i;
clrscr();
printf("\n=====================================");
printf("\n\tNumber\tSquare Root");
printf("\n=====================================");
for(i=9;i>0;i--)
printf("\n\t%d\t%.2f",i,sqrt(i));
getch();
}
Unconditional Statements :
There are two statement built in C, break; and continue; to interrupt the normal flow of control of a program.
Loops performs a set of operation repeately until certain condition becomes false but, it is sometimes desirable
to skip some statements inside loop and terminate the loop immediately without checking the test expression.
In C programming, break is used in terminating the loop immediately after it is encountered. The break
statement is used with conditional if statement.
break;
The break statement can be used in terminating all three loops for, while and do...while loops.
The figure below explains the working of break statement in all three type of loops.
Write a C program to find average of maximum of n positive numbers entered by user. But, if the input
is negative, display the average(excluding the average of negative input) and end the program.
/* C program to demonstrate the working of break statement by terminating a loop, if user inputs negative
number*/
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break; //for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}
Output :
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are used.
Continue Statement :
Continue;
For better understanding of how continue statements works in C programming. Analyze the figure below
which bypasses some code/s inside loops using continue statement.
Write a C program to find the product of 4 integers entered by a user. If user enters 0 skip it.
Output :
Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30
goto statement :
C supports the go to statement to branch unconditionally from one point to another in the
program. Although it may not be essential to use the go to statement in a highly structured language
like C, there may be occasions when the use of go to might be desirable.
The goto requires a label in order to identify the place where the branch is to be made.
A label is any valid variable name, and must be followed by a colon.
The label is placed immediately before the statement where the control is to be transferred.
The general forms of goto and label statements are shown below :
----------- statements;
----------- -------------;
(b) What is the implicit type conversion hierarchy that is applied while evaluating expressions?
(c) List and give examples for different bitwise operators available in ‘C’?{R09 DEC 2010 set 2}
16. (a) Differentiate between application software and system software?
(b) Draw a flowchart for finding the sum of ‘n’ numbers starting from 1?
(c) Briefly discuss various computing environments with neat diagrams? {R09 DEC 2010 set 3}
17.(a) What do you mean by operator precedence and associativity? How one can
override the precedence defined by C language? Give illustrative examples?
(b) Explain the structure of a C program? {R09 DEC 2010 set 3}
18.(a) List the activities involved in each phase of waterfall system development life cycle model?
(b) What are the different types of errors one can encounter during the program execution? [10+5]
{R09 DEC 2010 set 4}
19.( a) What is an identifier? What are the naming rules for identifiers in C?
(b) List different categories of C operators based on their functionality? Give examples?
(c) Explain different types of coding constants in a C? {R09 DEC 2010 set 4}
20. (a) Explain the functions of the following:
(i) Preprocessor
(ii) Compiler
(iii) Linker.
b) Draw a flowchart to find maximum and minimum of the given three input numbers.{R09 June
2010 set-1}
21.(a) Write minimal C-expressions for the following:
i)3x4+5x3-4x2+7x+20
ii) abcbccaab−−
iii) Digit at 100’s place of the given integer x. (Ex. Digit at 100’s place in 2578 is 5).
iv) If a > b then the value of expression is a-b, otherwise b-a
v) True if 5 <, otherwise false x < 10
vi) Divide the integer variable x by 16 using bit-wise operators
(b) What is the difference between the following c-words?
(i) amount and “amount”
(ii) 200 and 200.0
(c) A number is said to be prime, if it is not exactly divisible by any other numbers other than 1 and
the number it self. For example 7 and 11 are primes. Write C- language program that reads a number
from input and determine whether it is a prime or not. [6+2+7] {R09 June 2010, set-1}
22.(a)List out the various steps in software development.
(b) Given the 3 sides of triangle a, b and c as input, Draw a flowchart to test whether it is
isosceles, equilateral or not. It should also validate whether the input forms a triangle or not. (Ex. 10,
3, 3 is not a triangle) [6+9] {R09 June 2010, set-2}
23.(a) Write minimal C-expressions for the following:
4 3 2
i) 5a +3a -4a +6a+12
ii) abcbccaab−−
iii) If the given integer value of x is treated as binary, the fifth bit from the right.
iv) Absolute value of variable x.
v) True if x is exactly divisible by 5 but not divisible by 3, otherwise false.
vi) Subtract x from y and then increment x.
(b) What is the difference between the following C-words?
i) 253 and 0253
(b) A university gives grades based on the percentage of marks obtained in the examinations as
follows:
Percentage of marks Grade
70 and above Distinction
60 and above but below 70 First
50 and above but below 60 Second
40 and above but below 50 Third
below 40 Fail
Write a flowchart that inputs the percentage marks and output the division. [6+9]{ R09 june2010 set-
4}
27.a) Write minimal C- expressions for the following:
4 3 2
i) 6a +3a -5a -6a+22
ii) 1235abbc+
iii) Equivalent to C-statement while (a > = b)a = a-b where a and b are unsigned integers.
iv) True if x/y >3 without zero divide, false otherwise
v) If x<y then -1 else if x = = y then 0 else 1(use ternary operator)
vi) Fourth bit from the right if the number x is treated in binary representation.
(b) What is the difference between the following C-words?
i) count and int ii) 526 and “526”
(c) Write C-program that reverses the decimal digits of integer value at input. For example, for input
5379, the program need to output 9735. { R09 june2010 set-4}
28.(a) What is an algorithm? Write an algorithm to read five integers and find out if the values are in
ascending order.b) Draw a flow chart to read ten integer values and print the sum of squares of the
values.{R09 June-11 s1}
29.(a) Write minimal C expressions for the following:
4 3 2
(i) 2x + 3x - 4x + 7x -10
(ii) Digit at the 10's place of the given positive integer x (for example, digit at the 10's place in
3458 is 5)
(iii) True if the given positive integer x is odd, false otherwise
(iv) Add x to y, and then decrement x
(v) True if 5 <= a <= 10, false otherwise
(vi) Fourth bit from the right if the number x is treated in binary representation.
(b) Write a complete C Program to print all the prime numbers between 1 and n. Where ‘n’ is the
value supplied by the user. {R09 June-11 s1}
30.(a) What is an algorithm? Write an algorithm to find out if a given number is a prime.
(b) Draw a flow chart to read ten positive integers and print how many are multiples of 7. {R09
June-11 s2}
31(.a) Write minimal C expressions for the following:
4 3 2
(i) 3x + x - 4x + 7x
(ii) Maximum of the values of three variables a, b and c
(iii) Digit at the 100's place of the given positive integer x (for example, digit at the 100's
place in 3458 is 4)
(iv) True if the given positive integer x is even, false otherwise
(v) Increment x, and then add to z
(vi) True if the given positive integer x is a multiple of 3 and 7, false otherwise.
(b) What are the bitwise operators in C? Explain the same with examples. {R09 June-11 s2}
32.(a) Write an algorithm to find out all the factors of a given positive integer.
(b) What is a flow chart? Draw a flow chart to read ten integers and print the sum of squares of all
ten values. [8+7] {R09 June-11 s3}
33.(a) Write minimal C expressions for the following:
3 2
(i) x - 4x + 7x -12
(ii) Absolute value of (a-b)
(iii) Remainder when unsigned integer variable x is divided by 8, using bitwise operators.
(iv) True if the given positive integer x is even and is also a multiple of 7, false otherwise.
(v) Minimum of the values of three variables a, b and c.
(vi) True if the given character variable c represents a numeral (that is '0'...'9'), false otherwise.
{R09 June-11 s3}
34.(a) Write an algorithm to read ten positive integers and find out how many are perfect squares
(such as
49, 81). You may assume that the input values read are in the range 1 to 10000.
(b) List the various steps in software development. [8+7] {R09 June-11 s4}
2.(a) Write minimal C expressions for the following:
3 2
(i) x -3x + 3x -1
(ii) Digit at the 10's place of the given positive integer x (for example, digit at the 10’s place in
3458 is 5)
(iii) True if the given positive integer x is a multiple of both 17 and 11, false otherwise.
(iv) Remainder when unsigned integer variable x is divided by 8, using bitwise operators.
(v) True if 25 > a ≥ 10, false otherwise
(vi) Second bit from the right if the number x is treated in binary representation.
b) Write a complete C Program to read ten integers and find:
(i) The number of even integers and their sum, and
(ii) The number of odd integers and their sum. {R09 June-11 s4}
OBJECTIVE QUESTIONS:
18. The ______ statement is used to terminate the execution of the nearest enclosing loop in
which it appears.
a) break b) goto c) loop d) continue
19. The series of interrelated phases that is used to develop computer software is known as
a) Program development b) Software engineering
c) System design d) Software Development Life Cycle
20. Which of the following statements about the do-while loop is false?
a) a do-while loop executed one or more iterations
b) any statement may be used as the action in a do-while
c) The do-while is best suited for use as an event-controlled loop
d) the do-while is the only loop that requires a semicolon
21. The ___________ function reads data from the standard input file keyboard.
a) write b) printf c) read d) scanf
22. What will be sum of the binary numbers 1111 and 11001
a) 111100 b) 100010 c) 11110 d) 101000
23. Which one of the following is known as the language of the computer
a) Programming language b) Machine language
c) High level language d) Assembly level language
24. Find the output
Void main()
{char a[]=”12345\0”;
int i=strlen(a);
printf(“here in 3 %d\n”,++i);}
a) here in 3 b) here in 3 6 c) 6 d) 3
25. Which of the following is syntactically correct
a) for(;); b) for(); c) for(,); d) for(;;);
26. Find out the output for the following
#include<stdio.h>
main() {
int c=--2;
printf(“c=%d”,c);}
a) -2 b) 0 c) 2 d) None
27. Identify the result
Void main()
{ int i=5;
Printf(“%d”,i+++++i);}
a) 5 b) 6 c) 10 d) compiler error
28. What will be the ASCII Octal value of A
a) 100 b) 101 c) 110 d) 111
29. a<<1 is equal to
a) multiplying by 2 b) dividing by 2 c) added 2 d) None
30. Consider the following and find the output
Main()
{ int a=0;int b=30;char x=1;
If (a,b,x)
Printf(“Hello”);
}
a) compiler error b) abxHello c) Hello d) None
31. What type of errors are checked during compilation
a) logical errors b) divide by zero error
c) run - time errors d) syntax errors
32. Which one of the following numeric value is used to represent base of the binary number
a) 8 b) 10 c) 2 d) 16
33. What will be the binary value of B
a) 1001 b) 1011 c) 1100 d) 1101
34. The program fragment
int a=5, b=2;
printf(“%d”,a+++++b);
a) prints 7 b) prints 8 c) prints 9 d) none of the above
35. Consider the following program segment. i=6720; j=4;
while((i%j)==0)
{ i=i/j; j=j+1;
}
On termination j will have the value
a) 4 b) 8 c) 9 d) 6720
36. #include<stdio.h>
main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}
a) GOOD b) BAD c) GOOD BAD d) Compiler Error
37. How many times the body of the following loop executed? x=5; y=50; while(y! = 0) {y/=x;}
a) 4 b) 1 c) 4 d) 2
38. _____________ is very similar to the while loop except that the test occurs at the end of the
loop body
39. _______ is the largest value that an unsigned short int type varible can store
40. The hardware along with the read-only software that resides on this hardware is combinely
called as _________
41. _______ logical operator is true only when both operands are true
42. The order of evaluation can be changed by using _____ in an expression
43. A for loop with no test condition is called as _______ loop
44. Execution of a C program begins at _______
45. ______ loop in C is both counter controlled and pretest loop
46. In menu driven programs _______ loop statement is used
47. In flowcharts, decisions are represented by using ______ symbol
48. ______ acts as an interface between the computer hardware and user of the computer