Unit - 1: 1.1 Introduction To Programming
Unit - 1: 1.1 Introduction To Programming
A program is a set of instructions that tell the computer to do various things; sometimes the
instruction it has to perform depends on what happened when it performed a previous
instruction. This section gives an overview of the two main ways in which you can give these
instructions, or “commands” as they are usually called. One way uses an interpreter, the other
a compiler. As human languages are too difficult for a computer to understand in an
unambiguous way, commands are usually written in one or other languages specially designed
for the purpose.
Introduction to Computers:
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.
COMPUTER SYSTEM
HARDWARE
SOFTWARE
Computer Hardware
The hardware component of the computer system consists of five parts: input devices, central
processing unit (CPU) , primary storage, output devices, and auxiliary storage devices.
The input device is usually a keyboard where programs and data are entered into the computers.
Examples of other input devices include a mouse, a pen or stylus, a touch screen, or an audio
input unit.
The central processing unit (CPU) is responsible for executing instructions such as arithmetic
calculations, comparisons among data, and movement of data inside the system. Today’s
computers may have one ,two, or more CPUs .Primary storage ,also known as main memory, is
a place where the programs and data are stored temporarily during processing. The data in
primary storage are erased when we turn off a personal computer or when we log off from a
time-sharing system.
The output device is usually a monitor or a printer to show output. If the output is shown on the
monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard copy.
Auxiliary storage, also known as secondary storage , is used for both input and output. It is the
place where the programs and data are stored permanently. When we turn off the computer, or
programs and data remain in the secondary storage, ready for the next time we need them.
Computer Software
Computer software is divided in to two broad categories: system software and application
software .System software manages the computer resources .It provides the interface between the
hardware and the users. Application software, on the other hand is directly responsible for
helping users solve their problems.
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:
the operating system, system support, and system development.
The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this
software is to keep the system operating in an efficient manner while allowing the users access to
the system.
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 for the operational staff 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 to ensure
that the programs are error free and computer –assisted software engineering(CASE) systems.
Application software
Application –specific software can be used only for its intended purpose.
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.
The relation ship between system and application software is shown in fig-2.In this figure, each
circle represents an interface point .The inner core is hard ware. The user is represented by the
out layer. To work with the system,the typical user uses some form of application software. The
application software in turn interacts with the operating system ,which is apart of the system
software layer. The system software provides the direct interaction with the hard ware. The
opening at the bottom of the figure is the path followed by the user who interacts directly with
the operating system when necessary.
1.2.1Disk
Alternatively referred to as a diskette, a disk is a hard or floppy round, flat, and magnetic platter
capable of having information read from and written to it. The most commonly found disks with
a computer are the hard disks and floppy disks (floppy diskette) shown in the picture to the right.
When talking about a disk or diskette, you're referring to a floppy diskette or hard disk drive.
However, when talking about a Blu-ray, CD, or DVD, you should use "disc" and not "disk." For
example, saying "my movie is on that DVD disc" is the proper usage of "disc." An easy way to
remember this is that a "disk" is always a magnetic storage using magnets, and a "disc" is always
an optical media using a lasers or lights.
Hard drives
A hard-disk drive (HDD) is a non-volatile device used for storage, located inside the computer
case. Like the floppy drive, it holds its data on rotating platters with a magnetic upper exterior
which are changed or read by electromagnetic tipped arms that move over the disk as it spins.
1.2.2 Memory
A memory is just like a human brain. It is used to store data and instructions. Computer memory
is the storage space in the computer, where data is to be processed and instructions required for
processing are stored. The memory is divided into large number of small parts called cells. Each
location or cell has a unique address, which varies from zero to memory size minus one. For
example, if the computer has 64k words, then this memory unit has 64 * 1024 = 65536 memory
locations. The address of these locations varies from 0 to 65535.
Cache Memory
Secondary Memory
Cache Memory
Cache memory is a very high speed semiconductor memory which can speed up the CPU. It
acts as a buffer between the CPU and the main memory. It is used to hold those parts of data
and program which are most frequently used by the CPU. The parts of data and programs are
transferred from the disk to cache memory by the operating system, from where the CPU can
access them.
Advantages
The advantages of cache memory are as follows −
It stores the program that can be executed within a short period of time.
It is very expensive.
Primary Memory (Main Memory)
Primary memory holds only those data and instructions on which the computer is currently
working. It has a limited capacity and data is lost when power is switched off. It is generally
made up of semiconductor device. These memories are not as fast as registers. The data and
instruction required to be processed resides in the main memory. It is divided into two
subcategories RAM and ROM.
It is a non-volatile memory.
RAM (Random Access Memory) is the internal memory of the CPU for storing data, program,
and program result. It is a read/write memory which stores data until the machine is working.
As soon as the machine is switched off, data is erased.
Access time in RAM is independent of the address, that is, each storage location inside the
memory is as easy to reach as other locations and takes the same amount of time. Data in the
RAM can be accessed randomly but it is very expensive.
RAM is volatile, i.e. data stored in it is lost when we switch off the computer or if there is a
power failure. Hence, a backup Uninterruptible Power System (UPS) is often used with
computers. RAM is small, both in terms of its physical size and in the amount of data it can
hold.
There is extra space in the matrix, hence SRAM uses more chips than DRAM for the same
amount of storage space, making the manufacturing costs higher. SRAM is thus used as cache
memory and has very fast access.
Long life
No need to refresh
Faster
Large size
Expensive
Used as RAM
Smaller in size
Less expensive
ROM stands for Read Only Memory. The memory from which we can only read but cannot
write on it. This type of memory is non-volatile. The information is stored permanently in such
memories during manufacture. A ROM stores such instructions that are required to start a
computer. This operation is referred to as bootstrap. ROM chips are not only used in the
computer but also in other electronic items like washing machine and microwave oven.
Let us now discuss the various types of ROMs and their characteristics.
Advantages of ROM
The advantages of ROM are as follows −
Non-volatile in nature
Easy to test
More reliable than RAMs
1.3 Compilers:
A compiler is a software program that transforms high-level source code that is written by a
developer in a high-level programming language into a low level object code (binary code) in
machine language, which can be understood by the processor. The process of converting high-
level programming into machine language is known as compilation.
The processor executes object code, which indicates when binary high and low signals are
required in the arithmetic logic unit of the processor.
The software used to write programs is known as a text editor. A text editor helps us enter,
change, and store character data. Depending on the editor on our system, we could use it to write
letters, create reports, or write programs. The main difference between text processing and
program writing is that programs are written using lines of code, while most text processing is
done with character and lines.
Text editor is a generalized word processor, but it is more often a special editor included with the
compiler. Some of the features of the editor are search commands to locate and replace
statements, copy and paste commands to copy or move statements from one part of a program to
another, and formatting commands that allow us to set tabs to align statements.
After completing a program, we save our file to disk. This file will be input to the compiler; it is
known as a source file.
Compiling Programs:
The code in a source file stored on the disk must be translated into machine language , This is the
job of the compiler. The c compiler is two separate programs. the preprocessor and the
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
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. The translator reads the translation unit and
writes the resulting object module to a file that can then be combined with other precompiled
units to form the final program. An object module is the code in machine language. The output
of the compiler is machine language code, but it is not ready to run; that is ,it is not executable
because it does not have the required C and other functions included.
Linking Programs:
A C program is made up of many functions. We write some of these functions, and they are a
part of our source program. There are other functions, such as input/output processes and,
mathematical library functions, that exist elsewhere and must be attached to our program. The
linker assembles all of these functions, ours and systems into our final executable program.
Executing Programs:
Once program has been linked, it is ready for execution. To execute a program we use an
operating system command, such as run, to load the program into primary memory and execute
it. Getting the program into memory is the function of an operating system program known as
the loader. It locates the executable program and reads it into memory. When everything is
loaded, the program takes control and it begins execution.
In a typical program execution, the reads data for processing , either from the user or from a file.
After the program processes the data, it prepares the output. at output can be to the user’s
monitor or to a file. When the program has finished its job, it tells the operating system , which
then removes the program from memory.
CONVERSIONS:
BINARY SYSTEM :
Binary to decimal conversion
Binary to octal conversion
Binary to hexadecimal conversion
Here is an example of converting binary directly into decimal. We simply add up the place
values of each 1 digit in the binary number.
1001012 = 3710:
Exponents 25 24 23 22 21 20
Place Values 32 16 8 4 2 1
Bits 1 0 0 1 0 1
Value 32 +4 +1 = 37
number multiply the each digit in the decimal part by ,m is the position of the digit from the decimal
point
Step 3:The resultant is the equivalent decimal number for the given binary number.
Step 4: Divide the decimal with 8
Step 5: Note the remainder
Step 6: Continue the above two steps with the quotient till the quotient is zero
Step 7: Write the remainder in the reverse order
Step 8: The resultant is the required octal number for the given binary number.
OCTAL SYSTEM
by when the digit is in the mth position from the decimal point.
Step 4: Add all terms after multiplication
Step 5: The obtained value is the equivalent decimal number
Step 6: Consider the decimal number, divide it by 2
Step 7: Note the remainder
Step 8: Continue the above two steps for the quotient till the quotient is zero
Step 9: Write the remainders in the reverse order
Step 10: The obtained number is the equivalent binary number for the given octal number.
Solution:
Given number is 418
418
= (4 * 81) + (1 * 80)
=4*8+1*1
= 32+1
= 33(Decimal number)
2 | 33
2 | 16 -- 1
2 | 8 -- 0
2 | 4 --0
2 | 2 -- 0
1 -- 0
418 = 1000012
Octal to Decimal conversion
Step 8: Multiply each digit after decimal with ,when the digit is the mth position.
All other steps are same as above.
57468
= (5 * 83)+ (7 * 82) + (4 * 81) + (6 * 80)
=5 * 512 + 7 * 64 + 4 * 8 + 6 * 1
= 2560+448+32+6
= 3046
57468 = 3046
number.If the number has decimalpart the multiply digits after decimal by where m is
position of the number from the decimal
Step 3: Add the terms after multiplication
Step 4: The obtained number is equivalent decimal number to the given octal
Step 5: Consider the decimal number,divide it by 16
Step 6: Note the remainder.
Step 7: Continue the process till the quotient in zero
Step 8: Write the remainder in the reverse order
Step 9: The obtained number is equivalent hexadecimal number to the given octadecimal
number.
10028
= (1 * 83)+ (0 * 82) + (0 * 81) + (2 * 80)
=1 * 512 + 0 * 64 + 0 * 8 + 2 * 1
= 512 + 0 + 0+ 2
= 514(decimal number)
16 | 514
16 | 32 --2
2 -- 0
The hexadecimal number is 202
10028 = 20216
DECIMAL SYSTEM
16 | 146
-------------
16 | 9 -- 2
-------------
0 – 9
HEXADECIMAL CONVERSIONS
Hexadecimal to Binary conversion
Step 1: Take given hexadecimal number
Step 2: Find the number of digits in the decimal
Step 3: If it has n digits,multiply each digit with 2n-1where the digit is in the nth position
Step 4: Add the terms after multiplication
Step 5: The resultant is the decimal number equivalent to the given hexadecimal number.Now
we have to convert this hexadecimal to binary number.
Step 6: Divide the decimal number with 2
Step 7: Note the remainder
Step 8: Do the above 2 steps for the quotient till the quotient is zero
Step 9: Write the remainders in the reverse order.
Step 10: The resultant is the required binary number.
Example: Convert A2B16 to a equivalent binary number
Solution:
Given hexadecimal number is A2B
= 2603(Decimal number)
2 | 2603
2 |1301 -- 1
2 | 650 -- 1
2 | 325 -- 0
2 | 162 -- 1
2 | 81 -- 0
2 | 40 -- 1
2 | 20 -- 0
2 | 10 -- 0
2 | 5 -- 0
2 | 2 -- 1
2 | 1 -- 0
2 | 0 -- 1
A2B16 = 1010001010112
Solution:
Given hexadecimal number is C1
C116
= (C * 161) + (1 * 160)
= C * 16 + 1 * 1
=12 * 16 + 1
= 192 + 1
=193 (Decimal form)
8 | 193
8 | 24 -- 1
8 | 3 -- 0
8 | 0 --3
C116 = 3018
Definition of Algorithm
To write a logical step-by-step method to solve the problem is called algorithm, in other words,
an algorithm is a procedure for solving problems. In order to solve a mathematical or computer
problem, this is the first step of the procedure. An algorithm includes calculations, reasoning and
data processing. Algorithms can be presented by natural languages, pseudo code and flowcharts,
etc.
Definition of Flowchart
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 flow
chart.
The following are the most common symbols used in Drawing flowcharts:
Shape Type Name of the
Symbol Meaning
of the symbol Symbol
The graphics above represent different part of a flowchart. The process in a flowchart can be
expressed through boxes and arrows with different sizes and colors. In a flowchart, we can easily
highlight a certain element and the relationships between each part.
Now that we have the definitions of algorithm and flowchart, how do we use a flowchart to
represent an algorithm?
Algorithms are mainly used for mathematical and computer programs, whilst flowcharts can be
used to describe all sorts of processes: business, educational, personal and of course algorithms.
So, flowcharts are often used as a program planning tool to visually organize step-by-step
process of a program. Here are some examples:
Pseudo code is an artificial and informal language that helps programmers develop algorithms.
Pseudo code is similar to everyday English, it is convenient and user friendly although it is not
an actual computer programming language. Psuedo code programs are not actually executed on
computer rather they merely help the programmer “think out” a program before attempting to
write it in a programming language such as C.
1.7.1 Program Design Language (or PDL, for short) is a method for designing and
documenting methods and procedures in software. It is related to pseudo code, but unlike pseudo
code, it is written in plain language without any terms that could suggest the use of any
programming language or library.
PDL was originally developed by the company Caine, Farber & Gordon and has been modified
substantially since they published their initial paper on it in 1975. It has been described in some
detail by Steve McConnell in his book Code Complete.
1.7.2 Program development System Development Method
Today’s large-scale modern programming projects are built using a series of interrelates phases
commonly referred to as the system development cycle. Although the exact number and names
of the phases differ depending on the environment there is general agreement as to the steps that
must be followed. One very popular development life cycle developed, this modal consists of
between 5 and 6 phases.
The water fall modal starts with systems requirements in this phase the systems analyst defines
requirements that specify what the proposed system is to accomplish.
The requirements are usually stated in terms that the user understands.
The analysis phase looks at different alternatives from a systems point of view while the design
phase determined how the system will be built.
In the design phase the functions of the individual programs that will make up the system are
determined and the design of the files and / or the databases is completed.
Finally in the 4th phase code, we write the programs. After the programs have been written and
tested to the programmer’s satisfaction, the project proceeds to the system test.
All of the programs are tested together to make sure of the system works as a whole
The final phase maintenance keeps the system working once it has been put into production.
Although the implication of the water falls approach is that the phases flow in a continuous
stream from the first to the last, this is not really the case. As each phase is developed, errors and
omissions will often be found in the previous work. When this happens it is necessary to go back
to the previous phase to rework it for consistency and to analyze the impact caused by the
changes.
PROGRAM DEVELOPMENT STEPS:
Program Development is a multistep process that requires that we understand the problem,
develop a solution, write the program, and then test it. 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. We should also receive an overview of the complete project so that we will
take the inputs we are given and convert them to the outputs that have been specified. This is
known as program design.
The first step in solving any problem is to understand it. By reading the requirements statements
carefully, we fully understand it, we review our understanding with the user and the systems
analyst to know the exact purpose.
The structure chart is used to design the whole program .Pseudo code and flowcharts are used to
design the individual parts of the program.
Structure chart: A structure chart, also known as hierarchy chart, shows the functional flow
through our program. The structure chart shows how we are going to break our program into
logical steps each step will be a separate module. The structure chart shows the interaction
between all the parts (modules) of our program.
We can use flowchart or pseudo code to complete the design of your program will depend on
experience and difficulty of the program your designing.
Write the program
When we write a program, we start with the top box on the structure chart and work our way to
the bottom. This is known as top-down implementation. We will write the programs by using
structure chart and flowchart or pseudo code.
Program testing can be a very tedious and time- consuming part of program development. As the
programmer we are responsible for completely testing our program. In large-development
projects test engineers are responsible for testing to make sure all the programs work together.
C is the programming language most frequently associated with UNIX. Since the 1970s, the bulk
of the UNIX operating system and its applications have been written in C. Because the C
language does not directly rely on any specific hardware architecture, UNIX was one of the first
portable operating systems. In other words, the majority of the code that makes up UNIX does
not know and does not care which computer it is actually running on. Machine-specific features
are isolated in a few modules within the UNIX kernel, which makes it easy for you to modify
them when you are porting to a different hardware architecture.
C was first designed by Dennis Ritchie for use with UNIX on DEC PDP-11 computers. The
language evolved from Martin Richard's BCPL, and one of its earlier forms was the B language,
which was written by Ken Thompson for the DEC PDP-7. The first book on C was The C
Programming Language by Brian Kernighan and Dennis Ritchie, published in 1978.
Algorithms and flowcharts are two different tools used for creating new programs, especially in
computer programming. An algorithm is a step-by-step analysis of the process, while a flowchart
explains the steps of a program in a graphical way.
The program written in C language follows this basic structure. The sequence of sections
should be as they are in the basic structure. A C program should have one or more sections but
the sequence of sections is to be followed.
Documentation section
Linking section
Definition section
Global declaration section
Main function section
{
Declaration section Executable section
}
Sub program or function section
DOCUMENTATION SECTION: comes first and is used to document the use of logic or
reasons in your program. It can be used to write the program's objective, developer and logic
details. The documentation is done in C language with /* and */ . Whatever is written between
these two are called comments.
LINKING SECTION: This section tells the compiler to link the certain occurrences of
keywords or functions in your program to the header files specified in this section.
DEFINITION SECTION: It is used to declare some constants and assign them some value.
Here #define is a compiler directive which tells the compiler whenever MAX is found in the
program replace it with 25.
GLOBAL DECLARATION SECTION : Here the variables which are used through out the
program (including main and other functions) are declared so as to make them global(i.e
accessible to all parts of program)
e.g. int i; (before main())
MAIN FUNCTION SECTION: It tells the compiler where to start the execution from
main()
{
point from execution starts
}
main function has two sections
• declaration section : In this the variables and their data types are declared.
• Executable section : This has the part of program which actually performs the task we
need.
SUB PROGRAM OR FUNCTION SECTION : This has all the sub programs or the functions
which our program needs.
1.8.3 C-TOKENS :
Tokens are individual words and punctuations marks in English language sentence. The smallest
individual units are known as C tokens.
A C program can be divided into these tokens. A C program contains minimum 3 c tokens no
matter what the size of the program is.
All arithmetic operations such as Addition, subtraction, etc are possible on basic data types.
The following table shows the Storage size and Range of basic 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.
1.9 VARIABLES:
A quantity that can vary during the execution of a program is known as a variable. To identify a
quantity we name the variable for example if we are calculating a sum of two numbers we will
name the variable that will hold the value of sum of two numbers as 'sum'.
IDENTIFIERS :
Names of the variables and other program elements such as functions, array,etc,are
known as identifiers.
There are few rules that govern the way variable are named(identifiers).
Identifiers can be named from the combination of A-Z, a-z, 0-9, _(Underscore).
The first alphabet of the identifier should be either an alphabet or an underscore. digit are
not allowed.
It should not be a keyword. Eg: name,ptr,sum After naming a variable we need to
declare it to compiler of what data type it is . The format of declaring a variable is
where data type could be float, int, char or any of the data id1, id2, id3 are the names of variable
we use. In case of single variable no commas are required.
eg float a, b, c;
Int e, f, grand total;
char present_or_absent;
ASSIGNING VALUES :
When we name and declare variables we need to assign value to the variable. In some cases we
assign value to the variable directly like
a=10;
in our program
In some cases we need to assign values to variable after the user has given input for that.
Eg: we ask user to enter any no and input it.
#include<stdio.h>
main()
{
int a; float b;
printf("Enter any number\n"); b=190.5;
scanf("%d",&a); printf("user entered %d", a); printf("B's values is %f", b);
}
CONSTANTS :
A quantity that does not vary during the execution of a program is known as a constant supports
two types of constants namely Numeric constants and character constants.
NUMERIC CONSTANTS:
CHARACTER CONSTANTS:
A character constant is written as one character with in single quotes such as ‘a’. The value of a
character constant is the numerical value of the character in the machines character set. certain
character constants can be represented by escape sequences like ‘\n’. These sequences look like
two characters but represent only one.
The following are the some of the examples of escape sequences:
String constants or string literal is a sequence of zero or more characters surrounded by a double
quote. Example , “ I am a little boy”. quotes are not a part of the string.
To distinguish between a character constant and a string that contains a single character ex: ‘a’ is
not same as “a”. ‘a’ is an integer used to produce the numeric value of letter a in the machine
character set, while “a” is an array of characters containing one character and a ‘\0’ as a string in
C is an array of characters terminated by NULL.
There is one another kind of constant i.e Enumeration constant , it is a list of constant integer
values.
For compiled languages, syntax errors are detected at compile-time. A program will not compile
until all syntax errors are corrected.
1 int a,b:
The above statement will produce syntax error as the statement is terminated with : rather than ;
Logical Error: A logic error is a bug in a program that causes it to operate incorrectly, but not
to terminate abnormally (or crash). A logic error produces unintended or undesired output or
other behaviour, although it may not immediately be recognized as such.
Logic errors occur in both compiled and interpreted languages. Unlike a program with a syntax
error, a program with a logic error is a valid program in the language, though it does not behave
as intended.
For example,
a=5/0;
1.11 Object and Executable code:
The programming language code is called as Source code or object code and is obtained after
compilation. Source code extension is .c file and object code extension is .obj and executable file
is .exe
1.12 OPERATORS :
An operator is a symbol that tells the compiler to perform certain mathematical or logical
manipulations. They form expressions.
C operators can be classified as
• Arithmetic operators
• Relational operators
• Logical operators
• Assignment operators
• Increment or Decrement operators
• Conditional operator
• Bit wise operators
• Special operators
operator meaning
+ add
- subtract
* multiplication
/ division
% modulo division(remainder)
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.
operator meaning
op-1 !op-1
non-zero Zero
zero non-zero
4. ASSIGNMENT OPERATORS : They are used to assign the result of an expression to a
variable. The assignment operator is '='.
and == are called increment and decrement operators used to add or subtract. Both are unary and
as follows
Syntax: ++m or m++ --m or m--
The difference between ++m and m++ is
It work as
if exp1 is true then exp2 else exp3
7. BIT WISE OPERATORS: C supports special operators known as bit wise operators for
manipulation of data at bit level. They are not applied to float or double.
operator meaning
8. 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 comma operator is
used to link related expressions together. sizeof operator is used to know the sizeof operand.
#include<stdio.h>
main()
{
int sum, mul, modu; float sub, divi;
int i,j; float l, m;
printf("Enter two integers "); scanf("%d%d",&i,&j); printf("Enter two real numbers"); scanf("%f
%f",&l,&m);
sum=i+j;
mul=i*j;
modu=i%j; sub=l-m; divi=l/m;
printf("sum is %d", sum); printf("mul is %d", mul); printf("Remainder is %d", modu);
printf("subtraction of float is %f", sub); printf("division of float is %f", divi);
}
#include<stdio.h>
main()
{
int i, j, k;
printf("Enter any three numbers "); scanf("%d%d%d", &i, &j, &k); if((i<j)&&(j<k))
printf("k is largest"); else if i<j || j>k
{
if i<j && j >k
printf("j is largest");
else
printf("j is not largest of all");
}
}
#include<stdio.h>
main()
{
int i;
printf("Enter a number"); scanf("%d", &i);
i++;
printf("after incrementing %d ", i); i--;
printf("after decrement %d", i); }
/* program using ternary operator and assignment */ #include<stdio.h>
main()
{
int i,j,large;
printf("Enter two numbers "); scanf("%d%d",&i,&j); large=(i>j)?i:j;
printf("largest of two is %d",large);
}
An expression is a sequence of operands and operators that reduces to a single value. Expression
can be simple or complex. An operator is a syntactical token that requires an action be taken.
An operand is an object on which an operation is performed.
A simple expression contains only one operator. E.g: 2 + 3 is a simple expression whose value is
5.A complex expression contains more that one operator. E.g: 2 + 3 * 2. To evaluate a complex
expression we reduce it to a series of simple expressions. In this first we will evaluate the simple
expression 3 * 2 (6)and then the expression 2 + 6,giving a result of 8.
The order in which the operators in a complex expression are evaluated is determined by a set of
priorities known as precedence, the higher the precedence ,the earlier the expression containing
the operator is evaluated. If two operators with the same precedence occur in a complex
expression ,another attribute of an operator ,its associativity ,takes control. Associativity is the
parsing direction used to evaluate the expression. It can be either left-to-right or right-to-left.
When two operators with the same precedence occur in an expression and their associativity is
left-to-right ,the left operator is evaluated first. For example ,in the expression 3*4/6 ,there are
two operators multiplication and division ,with the same precedence and left-to-right
associativity. Therefore the multiplication is evaluated before the division.
ARITHMETIC EXPRESSIONS:
Some examples A * B – C
(M + N) * (X + Y)
Storage Classes:- Not only data type is required to declare a variable but its storage class also
has to be mentioned. (or)
The variables declared in C programs are totally different from other languages. We can use the
same variable names in the C program in separate blocks. When we declare a variable it is
available only to specific part or block of the program. Remaining block or other function
cannot get access to the variable.
The area or block of the C program from where the variable can be accessed is known as the
scope of variable. The area or scope of the variable depends on its storage class i.e. where and
how it is declared. There are four scope variables in C.
1. Function
2. File
3. Block
4. Function prototype
(ii) The Scope of the variable i.e., in which region of the program the value of variable is
actually available for us active.
(iii) Life of the variable i.e., how long the variable i.e., how long the variable would be active
in the program(longevity or alive).
Any variable declared in C can have any one of the four storage classes:
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.
The variables may also be broadly categorized, depending on the place of their declaration, as
1) Automatic variables are defined inside a function. A variable declared inside a function
without storage class name, by default is an auto variable.
These variables are created when the function is called and destroyed automatically when the
function is exited.
Automatic variables are local to the function in which they are declared. These values cannot be
accessed by any other function. The keyword used is „auto‟.
Eg:
void main ( )
clrscr ( );
getch ( );
void show ( );
void main ( )
int I;
clrscr ( );
show ( )
getch ( );
void show ( )
int a= 10;
a++;
2)External variables are also known as global variables. These variables are declared outside
the function and the values of these variables are available to all the functions of the program.
Unlike Local Variables, Global Variables can be accessed by any function in the program.
If same name is given to both the global and local variables priority is given to the local variable.
The keyword “ extern” is used to declare these variables.
Example Program:
#include<stdio.h>
#include<conio.h>
int a=20;
void main( )
clrscr( );
fun1( );
fun2( );
fun3( );
fun1( )
fun2( )
int a = 10;
fun3( )
Explanation: In this program local variable and global variables are declared with the same
name in fun2( ). In this case, when fun2( ) is called, the local variable „a‟ of fun2( ) hides the
global variable „a‟.
Note:
We can declare external variables by using extern key word inside the function body. Ex: extern
int a;
Eg 1:
void main ( )
clrscr ( );
getch ( );
3) Static variables may be of Local (or) global depending upon where it is declared. If it is
declared outside the function, it is static global otherwise if it declared inside a function block, it
is static local.
A static variable is initialized only once and can never be re-initialized. The value of static
variable persists at each call and last change made in the variable remains throughout the
program execution.
Example Programs:-
Eg 1:
void main( )
incr( );
incr( );
incr( );
void incr( )
static int x;
x=x+1;
printf(“%d”, x);
The keyword register tells the compiler that the variable list followed by it is kept on the CPU
registers. If the CPU fails to keep the variables in CPU registers, in that case the variables are
assured as auto and stored in the memory.
Note:
1. CPU registers are limited in number. So, we cannot declare more variables as register
variables. Compiler automatically converts the register variables into non-register variables
once the limit is reached.
2. We cannot use register class for all types of variables. The CPU registers in microcomputer
are 16 bit registers. The data types float and double needs space of more than 16 bits. If we
define any variable of these types with register class, no errors will be shown. The compiler
treats them as auto variables.
The features of register variables are:-
(iv) Life time :until the control remains in that function block.
Example Programs:-
Eg 1:
void main( )
{
register int i;
In an expression that involves two different data types ,such as multiplying an integer and a
floating point number to perform these evaluations ,one of the types must be converted.
We have two types of conversions
For example ,to convert an integer ,a , to a float, we code the expression like (float) a
STATEMENT TYPES:
NULL STATEMENT :
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 STATEMENT :
Syntax:
expression; //expression statement
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.
COMPOUND STATEMENTS:
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:
{
//Local Declarations int x;
int y; int z;
//Statements
x=1;
y=2;
…
} //End BlocK
We have a number of situations where we may have to change the order of execution of
statements based on certain conditions or repeat a group of statements until certain specified
conditions are met.
The if statement is a two way decision statement and is used in conjunction with an
expression. It takes the following form
If(test expression)
If the test expression is true then the statement block after if is executed otherwise it is not
executed
Syntax:
if (test expression)
{
statement block;
}
statement–x ;
/* program for if */
#include<stdio.h> main()
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):
if a>b
printf(“ a is greater”);
if b>a
printf(“b is greater”);
}
If your have another set of statement to be executed if condition is false then if-else is
used
Syntax: if (test expression)
{
statement block1;
}
else
{
statement block2;
}
statement –x ;
Example: /* program for if-else */
#include<stdio.h>
main()
{
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):
if a>b
printf(“ a is greater”)
else
printf(“b is greater”);
}
If more than one if else statement exists in the program then it is said as Nesting of
statement
Syntax:
if(text cond1)
{
if (test expression2
{
statement block1;
}
else
{
statement block 2;
}
}
else
{
statement block2;
}
statement-x ;
if else ladder
if(condition1)
statement1; else
if(condition2) statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;
The nesting of if-else depends upon the conditions with which we have to deal.
THE SWITCH STATEMENT: If for suppose we have more than one valid choices to
choose from then we can use switch statement in place of if statements.
Syntax: switch(expression)
{.
case value-1
block- 1 break;
case value-2
block- 2 break;
----------------
default:
default block; break;
}
statement–x
In case of
Syntax:
if(cond1)
{
statement-1
}
if (cond2)
{
statement 2
}
{
case 10 : case 9:
case 8: case 7:
LOOPING :
WHILE STATEMENT :
It helps to execute the statements only if the condition is true.
Syntax:
While(test condition)
{
body of the loop
}
It is an entry controlled loop. The condition is evaluated and if it is true then body of loop
is executed. After execution of body the condition is once again evaluated and if is true body is
executed once again. This goes on until test condition becomes false.
DO WHILE STATEMENT:
The while loop does not allow body to be executed if test condition is false. The do while
is an exit controlled loop and its body is executed at least once.
Syntax:
do
{
body }while(test
condition);
Example: /* printing multiplication table */
#include<stdio.h> #define
COL 10 #define ROW 12
main()
{
int row,col,y; row=1;
do
{
col=1; do
{
y=row*col;
printf(“%d”,y);
col=col+1;
}while(col<=COL);
printf(“\n”);
row=row+1;
}while(row<=ROW);
}
{
long int p; int n;
double q;
printf(“2 to power n “); p=1;
for(n=0;n<21;++n)
{
if(n==0)
p=1;
else
p=p*2;
q=1.0/(double)p;
printf(“%101d%10d”,p,n);
}
}
BREAK STATEMENT:
This is a simple statement. It only makes sense if it occurs in the body of a switch, do,
while or for statement. When it is executed the control of flow jumps to the statement
immediately following the body of the statement containing the break. Its use is widespread in
switch statements, where it is more or less essential to get the control .
The use of the break within loops is of dubious legitimacy. It has its moments, but is really
only justifiable when exceptional circumstances have happened and the loop has to be
abandoned. It would be nice if more than one loop could be abandoned with a single break but
that isn't how it works. Here is an example.
#include<stdio.h>
#include<stdlib.h> main()
{
int i;
printf("%d\n", i);
}
exit(EXIT_SUCCESS);
}
It reads a single character from the program's input before printing the next in a sequence of
numbers. If an ‘s’ is typed, the break causes an exit from the loop.
If you want to exit from more than one level of loop, the break is the wrong thing to use.
CONTINUE STATEMENT:
This statement has only a limited number of uses. The rules for its use are the same as for
break, with the exception that it doesn't apply to switch statements. Executing a continue starts
the next iteration of the smallest enclosing do, while or for statement immediately. The use of
continue is largely restricted to the top of loops, where a decision has to be made whether or not
to execute the rest of the body of the loop. In this example it ensures that division by zero (which
gives undefined behaviour) doesn't happen.
#include<stdio.h>
#include<stdlib.h> main()
{
int i;
There is an important difference between loops written with while and for. In a while, a
continue will go immediately to the test of the controlling expression. The same thing in a for
will do two things: first the update expression is evaluated, then the controlling expression is
evaluated.
goto L1;
/* whatever you like here */ L1: /*
anything else */
A label is an identifier followed by a colon. Labels have their own ‘name space’ so they
can't clash with the names of variables or functions. The name space only exists for the function
containing the label, so label names can be re-used in different functions. The label can be used
before it is declared, too, simply by mentioning it in a goto statement.
Labels must be part of a full statement, even if it's an empty one. This usually only matters
when you're trying to put a label at the end of a compound statement—like this.
It's hard to give rigid rules about the use of gotos but, as with the do, continue and the
break (except in switch statements), over-use should be avoided. More than one goto every 3–5
functions is a symptom that should be viewed with deep suspicion.
The simplest of input operator is getchar to read a single character from the input device.
The simplest of output operator is putchar to output a single character on the output device.
putchar(varname)
The getchar() is used only for one input and is not formatted. Formatted input refers to an input
data that has been arranged in a particular format, for that we have scanf.
scanf("control string", arg1, arg2,...argn);
Control string specifies field format in which data is to be entered.
arg1, arg2... argn specifies address of location or variable where data is stored.
eg scanf("%d%d",&a,&b);
Syntax:
We can also give command-line arguments in C and C++. Command-line arguments are given
after the name of the program in command-line shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments : first
argument is the number of command line arguments and second is list of command-line
arguments.
Syntax:
Ans: 0 .
2. #include <stdio.h>
int main(void) {
float x,y;
int i,j;
x = 1.5; y = 2.0;
i = 2; j = 4;
x = x * y + (float)i / j;
printf("%f",x);
return 0;
}
Ans: 3.500000 .
3. #include <stdio.h>
int main(void) {
int i = 7, j = i - i;
while(i) {
i /= 2;
j++;
}
printf("%d",j);
return 0;
}
Ans: 3 .
4. #include <stdio.h>
int main(void) {
int i, j = 1;
for(i = 11; i > 0; i /= 3)
j++;
printf("%d",j);
return 0;
}
Ans: 4 .
5. #include <stdio.h>
int main(void) {
int i = 1, j = -2, k;
k = (i >= 0) || (j >= 00) && (i <= 0) || (j <= 0);
printf("%d",k);
return 0;
}
Ans: 1 .
ASSIGNMENT QUESTIONS
SET-1:
1. Design an algorithm and flow chart to find maximum among three numbers.
2. Implement a C program to find factors of given number.
SET-2:
1. Design an algorithm and flow chart to check given number is positive or negative or zero
2. Implement a C program to print multiplication table for 1 to n numbers.
SET-3:
SET-4:
1. Implement a C program to check given number is perfect number or not.
2. Design a structure how to create and run C program.
SET-5:
1. Implement a C program to reverse a given number.
2. Design program Development steps.
SET-6:
1. Implement a C program to convert decimal number into binary.
2. Discuss about data types.
3. Implement a C program to add two numbers using command line argument.
6. Write the various steps involved in executing a C program and illustrate with the help of
flow chart?
7. What is the difference between break and continue statements ? Explain with examples.
8. What is the purpose of goto statement? How is the associated target statement identified?
9. (a) What are constants?
B.Name the different data types that C supports and explain them in detail.
10. What is meant by looping? Describe any two different forms of looping with
Examples.
(b) Write a program to print the following outputs using for loop.
i) 1
2 2
3 3 3
4 4 4 4
ii) 1
2 2
3 3 3
4 4 4 4
10 What are the logical operators used in C and illustrate with examples?
11. Whar is the purpose of switch statement ? How does this statement differ from the other
statements?
12. State and explain various identifiers in C program. And also discuss about operator
precedence in expression evaluation with a suitable example.
13. Explain with a sample program about while, for, do-while and switch statements in C
programming
14. Explain the difference between break, goto and continue statements with an example
16. Explain the difference between while and do-while statements with suitable examples.
17. Write a C program to print digits in reverse order for a given number.
20. Write C program to print prime numbers in a given series of numbers. For example:
numbers from 1 to 100.
21. What is a flowchart? Discuss various symbols used in flowchart. Illustrate with an
example.
23. What is meant by assembly language? Give example. Differentiate between pre test and
post test loops.
24. What is the need of type conversion? Discuss type casting. b) List the demerits of go to
statement. c) Why is switch statement known as multi way selection?
25. Explain switch statement. Explain its usage with a sample C-program. What are the
storage classes in C? Explain their usage with a sample C-program.
26. Explain scope of a variable with an example. Write brief notes on computer languages
OBJECTIVE QUESTIONS