Unit 1 Introduction To Computers, Algorithms & C
Unit 1 Introduction To Computers, Algorithms & C
COMPUTER SYSTEMS
A Computer is an electronic device that stores, manipulates and retrieves the data.‖ We can also refer
computer computes the information supplied to it and generates data.
A System is a group of several objects with a process. For Example: Educational System involves
teacher, students (objects). Teacher teaches subject to students i.e., teaching (process). Similarly a
computer system can have objects and process.
The following are the objects of computer System
a) User ( A person who uses the computer)
b) Hardware
c) Software
Hardware: Hardware of a computer system can be referred as anything which we can touch and feel.
Example : Keyboard and Mouse.
The hardware of a computer system can be classified as Input Devices(I/P), Processing Devices (CPU),
Output Devices(O/P).
COMPUTER SOFTWARE
Software of a computer system can be referred as anything which we can feel and see. Example:
Windows, icons
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 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. Examples of general purpose software include word processors, database
management systems ,and computer aided design systems. They are labeled general purpose because they
can solve a variety of user computing problems.
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 relationship between system and application software is shown below. 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 a part 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.
An Operating System (OS) is an interface between a computer user and computer hardware. An
operating system is a software which performs all the basic tasks like file management, memory
management, process management, handling input and output, and controlling peripheral devices such as
disk drives and printers.
Some popular Operating Systems include Linux Operating System, Windows Operating System, VMS,
OS/400, AIX, z/OS, etc.
Definition: An operating system is a program that acts as an interface between the user and the computer
hardware and controls the execution of all kinds of programs.
Following are some of important functions of an operating System.
• Memory Management
• Processor Management
• Device Management
• File Management
• Security
• Control over system performance
NUMBER SYSTEMS
Computer does not understand human language because it is arbitrary. But numbers are not arbitrary, and
that is why we prefer numbers to communicate with computer and machines. Hence, the number system
was discovered. Number System is a system through which we communicate and understand the machine.
For example, for a computer 0 is OFF and 1 is ON.
Definition of Number System in Computers
In computers, Number System is defined as a writing system to represent the numbers in different
ways i.e. we are using different symbols and notations to represent numbers. There are four ways we can
represent the number. That is, there are four types of Number System – Binary, Decimal, Octal,
Hexadecimal. Let us see each number system one by one.
As the name says, we can define the Octal number system as a number system in which we can
represent the numbers using 8 different values or digits. From 0 to 7. Since we can represent the number
using 8 different digits the base of Octal Number System is 8. Also, there is a relationship between Binary
and Octal Number system. The group of 3 binary digits makes one octal digit. Since, 2 power 3 = 8.
Decimal Number System:
In decimal number system we have 10 digits – 0 to 9 to represent the numbers. Hence, the base
value of the Decimal Number system is 10. Decimal number system is used when there are 10 possible
outputs of a system. For example, top 10 students from a class.
Hexadecimal Number System:
In Hexadecimal number system, we add 6 more digits to Decimal number system. Which means
hexadecimal number system is a number system in which we use 16 different values to represent the
numbers That is 0 to 9 and A to F. A, B, C, D, E, F represents 10, 11, 12, 13, 14, 15 respectively.
Number System Table – Binary, Octal, Decimal, Hexadecimal
Number System Base Digits used Examples
Binary 2 0 or 1 (1010111)2
Thus the fractional binary number is .01011, i.e., 0.01011. The process of multiplication by 2 will continue
till the desired accuracy is achieved.
b)Decimal to Octal Number System
In the above example, we first identified the base of Binary as 2. Then, we assigned the position to each
digit. Then we multiplied the digit with Base (2) power Position (BpP). And then we add the answers we
got from multiplication.
Octal to Decimal Number System
// printf()
#include<stdio.h>
void main()
{
int a=25,b=100;
float x=45.6789;
printf("\na=%d\tb=%d\n",a,b);
printf("\ndisplay a&b:\n");
printf("\n______________");
printf("\n%2d%2d",a,b);
printf("\n%3d%3d",a,b);
printf("\n%4d%4d",a,b);
printf("\n%5d%5d",a,b);
printf("\n%10d%10d",a,b);
printf("\n%-5d%-5d",a,b);
printf("\n%-10d%-10d",a,b);
printf("\ndisplay x:");
printf("\n______________");
printf("\n\n x=%f",x);
printf("\n\n x=%7.2f",x);
printf("\n\n x=%-7.2f",x);
printf("\n\n x=%10.4f",x);
printf("\n\n x=%-10.4f",x);
}
Output:
a=25 b=100
display a&b:
______________
25100
25100
25 100
25 100
25 100
25 100
25 100
display x:
______________
x=45.678902
x= 45.68
x=45.68
x= 45.6789
x=45.6789
for(j=0; j <= i; j++)// inner loop for displaying the pascal triangle of numbers
{
if (j==0 || i==0) // either outer loop value or inner-loop value is "0 " it prints 1
cal = 1;
else
cal = cal*(i-j+1)/j; //calculate the coefficient
printf("%4d", cal);
}
printf("\n");
}
//matrix multiplication
#include<stdio.h>
#include<stdlib.h>
void main()
{
int a[10][10],b[10][10],mul[10][10],m,n,p,q,i,j,k;
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
mul[i][j]=0;
for(k=0;k<n;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
printf("\n resultant matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
}
else
printf("multiplication is not possible\n");
COMPUTER LANGUAGES
To write a program (tells what to do) for a computer, we must use a computer language.
Over the years computer languages have evolved from machine languages to natural languages.
The following is the summary of computer languages
2 0010
+ 3 0011
5 0101
High-Level Languages
The symbolic languages greatly improved programming efficiency they still
required programmers to concentrate on the hardware that they were using working with
symbolic languages was also very tedious because each machine instruction had to be
individually coded. The desire to improve programmer efficiency and to change the focus from
the computer to the problems being solved led to the development of high-level languages.
High-level languages are portable to many different computer allowing the programmer
to concentrate on the application problem at hand rather than the intricacies of the computer.
C A systems implementation Language
C++ C with object oriented enhancements
JAVA Object oriented language for internet and general applications using basic C syntax
Advantages:
1) Easy to write and understand
2) Easy to isolate an error
3) Machine independent language
4) Easy to maintain
5) Better readability
6) Low Development cost
7) Easier to document
8) Portable
Disadvantages:
1) Needs translator
2) Requires high execution time
3) Poor control on hardware
4) Less efficient
Example: C language
#include<stdio.h>
void main()
{
int a,b,c;
scanf("%d%d%",&a,&b);
c=a+b;
printf("%d",c);
}
Difference between Machine, Assembly, High Level Languages
Language Translators
These are the programs which are used for converting the programs in one language into
machine language instructions, so that they can be excuted by the computer.
COMPILER INTERPRETER
A Compiler is used to compile an entire An interpreter is used to translate each line of
program and an executable program is the program code immediately as it is entered
generated through the object program
The executable program is stored in a disk for The executable program is generated in RAM
future use or to run it in another computer and the interpreter is required for each run of
the program
The compiled programs run faster The Interpreted programs run slower
Most of the Languages use compiler A very few languages use interpreters.
CREATING AND RUNNING PROGRAMS
The procedure for turning a program written in C into machine Language. The process is
presented in a straightforward, linear fashion but you shuld recognize that these steps are
repeated many times during development to correct errors and make improvements to the code.
The following are the four steps in this process
1) Writing and Editing the program
2) Compiling the program
3) Linking the program with the required modules
4) Executing the program
TEXT EDITOR
COMPILER
LINKE
Library R
RUNNER
OUTPUT
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 Compiler is a computer program that translates the source
code written in a high-level language into the corresponding object code of the low-level
language. This translation process is called compilation. The entire high level program is
converted into the executable machine code file. The Compiler which executes C programs is
called as C Compiler. Example Turbo C, Borland C, GC etc.,
The C Compiler is actually two separate programs:
The Preprocessor
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. 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 the machine
language.
Linking Programs
The Linker assembles all functions, the program‘s functions and system‘s functions into
one executable program.
Executing Programs
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 begin
execution.
ALGORITHM
Algorithm is a finite sequence of instructions, each of which has a clear meaning and can be
performed with a finite amount of effort in a finite length of time. No matter what the input
values may be, an algorithm terminates after executing a finite number of instructions.
We represent an algorithm using a pseudo language that is a combination of the constructs of a
programming language together with informal English statements.
The ordered set of instructions required to solve a problem is known as an algorithm.
The characteristics of a good algorithm are:
• Precision – the steps are precisely stated (defined).
• Uniqueness – results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.
• Finiteness – the algorithm stops after a finite number of instructions are executed.
• Input – the algorithm receives input.
• Output – the algorithm produces output.
• Generality – the algorithm applies to a set of inputs.
Example
Q. Write a algorithem to find out number is odd or even?
Ans.
step 1 : start
step 2 : input number
step 3 : rem=number mod 2
step 4 : if rem=0 then
print "number even"
else
print "number odd"
endif
step 5 : stop
FLOWCHART
Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing
program and explaining program to others.
Symbols Used In Flowchart
Different symbols are used for different states in flowchart, For example: Input/Output and
decision making has different symbols. The table below describes all the symbols that are used in
making flowchart
Symbol Purpose Description
Used to indicate the flow of logic by connecting
Flow line
symbols.
INTRODUCTION TO C LANGUAGE
C is a general-purpose high level language that was originally developed by Dennis Ritchie for
the Unix operating system. It was first implemented on the Digital Eqquipment Corporation
PDP-11 computer in 1972.
The Unix operating system and virtually all Unix applications are written in the C language. C
has now become a widely used professional language for various reasons.
• Easy to learn
• Structured language
• It produces efficient programs.
• It can handle low-level activities.
• It can be compiled on a variety of computers.
Facts about C
C was initially used for system development work, in particular the programs that make-up the
operating system. C was adoped as a system development language because it produces code that
runs nearly as fast as code written in assembly language. Some examples of the use of C might
be:
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Data Bases
• Language Interpreters
• Utilities
C Program File
All the C programs are writen into text files with extension ".c" for example hello.c. You can use
"vi" editor to write your C program into a file.
HISTORY TO C LANGUAGE
C is a general-purpose language which has been closely associated with the UNIX operating
system for which it was developed - since the system and most of the programs that run it are
written in C.
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards.
The influence of BCPL on C proceeded indirectly through the language B, which was written by
Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a DEC PDP-
7. BCPL and B are "type less" languages whereas C provides a variety of data types.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming
Language by Kernighan & Ritchie caused a revolution in the computing world.
In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI
C", was completed late 1988.
BASIC STRUCTURE OF C PROGRAMMING
The C compiler translates source to assembly code. The source code is received from the
preprocessor.
Assembler
The assembler creates object code. On a UNIX system you may see files with a .o suffix
(.OBJ on MSDOS) to indicate object code files.
Link Editor
If a source file references library functions or functions defined in other source files the link
editor combines these functions (with main()) to create an executable file.
C TOKENS
C tokens are the basic buildings blocks in C language which are constructed together to write a C
program.
Each and every smallest individual unit in a C program is known as C tokens.
C tokens are of six types. They are
Keywords (eg: int, while),
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg: ―total‖, ―hello‖),
Special symbols (eg: (), {}),
Operators (eg: +, /,-,*)
C KEYWORDS
C keywords are the words that convey a special meaning to the c compiler. The keywords
cannot be used as variable names.
The list of C keywords is given below:
volatile while
C IDENTIFIERS
Identifiers are used as the general terminology for the names of variables, functions and arrays.
These are user defined names consisting of arbitrarily long sequence of letters and digits with
either a letter or the underscore(_) as a first character.
There are certain rules that should be followed while naming c identifiers:
They must begin with a letter or underscore (_).
They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only first 31 characters are significant.
Some examples of c identifiers:
Name Remark
_A9 Valid
Temp.var Invalid as it contains special character other than the underscore
void Invalid as it is a keyword
C CONSTANTS
A C constant refers to the data items that do not change their value during the program
execution. Several types of C constants that are allowed in C are:
Integer Constants
Integer constants are whole numbers without any fractional part. It must have at least one digit
and may contain either + or – sign. A number with no sign is assumed to be positive.
There are three types of integer constants:
Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or + sign.
Example of valid decimal integer constants
341, -341, 0, 8972
Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is said
to be octal integer constants.
Example of valid octal integer constants
010, 0424, 0, 0540
Hexadecimal Integer Constants
Hexadecimal integer constants are integer constants having sequence of digits preceded by 0x or
0X. They may also include alphabets from A to F representing numbers 10 to 15.
Example of valid hexadecimal integer constants
0xD, 0X8d, 0X, 0xbD
It should be noted that, octal and hexadecimal integer constants are rarely used in programming.
Real Constants
The numbers having fractional parts are called real or floating point constants. These may be
represented in one of the two forms called fractional form or the exponent form and may also
have either + or – sign preceding it.
Example of valid real constants in fractional form or decimal notation
0.05, -0.905, 562.05, 0.015
Representing a real constant in exponent form
The general format in which a real number may be represented in exponential or scientific form
is
mantissa e exponent
The mantissa must be either an integer or a real number expressed in decimal notation.
The letter e separating the mantissa and the exponent can also be written in uppercase i.e. E
And, the exponent must be an integer.
Examples of valid real constants in exponent form are:
252E85, 0.15E-10, -3e+8
Character Constants
A character constant contains one single character enclosed within single quotes.
Examples of valid character constants
‗a‘ , ‗Z‘, ‗5‘
It should be noted that character constants have numerical values known as ASCII values, for
example, the value of ‗A‘ is 65 which is its ASCII value.
Escape Characters/ Escape Sequences
C allows us to have certain non graphic characters in character constants. Non graphic characters
are those characters that cannot be typed directly from keyboard, for example, tabs, carriage
return, etc.
These non graphic characters can be represented by using escape sequences represented by a
backslash() followed by one or more characters.
NOTE: An escape sequence consumes only one byte of space as it represents a single character.
STRING CONSTANTS
String constants are sequence of characters enclosed within double quotes. For example,
―hello‖
―abc‖
―hello911‖
Every sting constant is automatically terminated with a special character „‟ called thenull
character which represents the end of the string.
For example, ―hello‖ will represent ―hello‖ in the memory.
Thus, the size of the string is the total number of characters plus one for the null character.
Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be
used for some other purpose.
[] () {} , ; : * … = #
Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.
VARIABLES
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive. Based on the basic types explained in the previous chapter, there will be the
following basic variable types −
Type Description
char Typically a single octet(one byte). This is an integer type.
C programming language also allows defining various other types of variables like
Enumeration, Pointer, Array, Structure, Union, etc.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable.
A variable definition specifies a data type and contains a list of one or more variables of that
type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to
create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables are
undefined.
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the
given type and name so that the compiler can proceed for further compilation without requiring
the complete detail about the variable. A variable definition has its meaning at the time of
compilation only; the compiler needs actual variable definition at the time of linking the
program. A variable declaration is useful when multiple files are used.
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
4 Logical operators
These operators are used to perform logical
ARITHMETIC OPERATORS IN C
C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs.
Arithmetic
S.no Operators Operation Example
1 + Addition A+B
2 – Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
EXAMPLE PROGRAM FOR C ARITHMETIC OPERATORS
In this example program, two values ―40‖ and ―20‖ are used to perform arithmetic operations
such as addition, subtraction, multiplication, division, modulus and output is displayed for each
operation.
#include <stdio.h>
int main()
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
OUTPUT:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
ASSIGNMENT OPERATORS IN C
In C programs, values for the variables are assigned using assignment operators.
For example, if the value ―10‖ is to be assigned for the variable ―sum‖, it can be assigned as
―sum = 10;‖
29
Operators Example Explanation
Simple assignment
operator 10 is assigned to variable
= sum = 10 sum
30
# include <stdio.h>
int main()
int Total=0,i;
for(i=0;i<10;i++)
OUTPUT:
Total = 45
RELATIONAL OPERATORS IN C
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.
x is greater than
1 > x>y y
x is greater than
3 >= x >= y or equal to y
x is less than or
4 <= x <= y equal to y
31
5 == x == y x is equal to y
x is not equal to
6 != x != y y
int main()
int m=40,n=20;
if (m == n)
else
OUTPUT:
It returns true
when both
logical conditions
1 && AND (x>5)&&(y<5)
are true
It returns true
when at-least
one of the
logical
condition is
2 || OR (x>=10)||(y>=10)
true
It reverses the
state of the
operand
―((x>5) &&
(y<5))‖
If ―((x>5)
&& (y<5))‖
is true,
logical logical NOT
3 ! NOT !((x>5)&&(y<5)) operator
makes it false
int main()
33
int m=40,n=20;
int o=20,p=30;
if (o>p || p!=20)
else
OUTPUT:
In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
34
&& operator – ―if clause‖ becomes true only when both conditions (m>n and m! =0) is true.
Else, it becomes false.
|| Operator – ―if clause‖ becomes true when any one of the condition (o>p || p!=20) is true. It
becomes false when none of the condition is true.
! Operator – It is used to reverses the state of the operand.
If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by ―!‖
operator.
So, ―! (m>n and m! =0)‖ returns false (0).
x x
& ^
x y x|y Operator_symbol Operator_name
y y
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y= 01010000
35
All bit wise operations for x and y are given below.
x&y = 00000000 (binary) = 0 (decimal)
x|y = 01111000 (binary) = 120 (decimal)
~x = 11111111111111111111111111 11111111111111111111111111111111010111
.. ..= -41 (decimal)
x^y = 01111000 (binary) = 120 (decimal)
x << 1 = 01010000 (binary) = 80 (decimal)
x >> 1 = 00010100 (binary) = 20 (decimal)
Note:
Bit wise NOT: Value of 40 in binary
is0000000000000000000000000000000000000000000000000010100000000000. So, all 0‘s are
converted into 1‘s in bit wise NOT operation.
Bit wise left shift and right shift : In left shift operation ―x << 1 ―, 1 means that the bits will be
left shifted by one place. If we use it as ―x << 2 ―, then, it means that the bits will be left shifted
by 2 places.
int main()
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
36
printf("XOR_opr value = %d\n",XOR_opr );
OUTPUT:
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if
else
conditional statements.
EXAMPLE PROGRAM FORIC TO
IONNDAL/TERNARY OPERATORS IN C
#include <stdio.h>
int main()
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
OUTPUT:
x value is 1
y value is 2
#include <stdio.h>
int main()
int i=1;
while(i<10)
printf("%d ",i);
i++;
OUTPUT:
123456789
EXAMPLE PROGRAM FOR DECREMENT OPERATORS IN C
In this program, value of ―I‖ is decremented one by one from 20 up to 11 using ―i–‖ operator and
output is displayed as ―20 19 18 17 16 15 14 13 12 11‖.
#include <stdio.h>
int main()
int i=20;
while(i>10)
printf("%d ",i);
i--;
OUTPUT:
20 19 18 17 16 15 14 13 12 11
1 Pre increment
++i Value of i is
incremented before
assigning it to variable
i.
Value of i is
incremented after
i++ assigning it to variable
2 Post–increment
i.
Value of i is
decremented before
— –i assigning it to variable
3 Pre decrement
i.
Value of i is
decremented after
i– — assigning it to variable
4 Post_decrement
i.
#include <stdio.h>
int main()
int i=0;
while(++i < 5 )
printf("%d ",i);
return 0;
}
OUTPUT:
1234
#include <stdio.h>
int main()
int i=0;
while(i++ < 5 )
printf("%d ",i);
return 0;
OUTPUT:
12345
int main()
int i=10;
while(--i > 5 )
printf("%d ",i);
return 0;
OUTPUT:
9876
#include <stdio.h>
int main()
int i=10;
while(i-- > 5 )
{
printf("%d ",i);
return 0;
OUTPUT:
98765
Above 3 steps are continued until while expression becomes false and output is displayed
as
―9 8 7 6 5‖.
43
EXAMPLE PROGRAM FOR & AND * OPERATORS IN C
In this program, ―&‖ symbol is used to get the address of the variable and ―*‖ symbol is
used to get the value of the variable that the pointer is pointing to. Please refer C – pointer
topic to know more about pointers.
#include <stdio.h>
int main()
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
return 0;
OUTPUT:
50
#include <limits.h>
int main()
int a;
char b;
float c;
double d;
return 0;
OUTPUT:
EXPRESSIONS
Arithmetic expression in C is a combination of variables, constants and operators written in a
proper syntax. C can easily handle any complex mathematical expressions but these
mathematical expressions have to be written in a proper syntax. Some examples of mathematical
expressions written in proper syntax of C are
Note: C does not have any operator for exponentiation.
C operators in order of precedence (highest to lowest). Their associativity indicates in what order
operators of equal precedence in an expression are applied.
Operator Description Associativity
() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
45
++ -- Prefix increment/decrement right-to-left
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
*/% Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
Note 1:
Parentheses are also used to group sub-expressions to force a different
precedence; such parenthetical expressions can be nested and are
Note 2: evaluated from inner to outer.
But when parenthesis is used in the same expression, the order of evaluation gets changed.
For example,
x = 9 – 12 / (3 + 3) * (2 – 1)
When parentheses are present then the expression inside the parenthesis are evaluated first from
left to right. The expression is now evaluated in three passes as:
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3: x= 7
There may even arise a case where nested parentheses are present (i.e. parenthesis inside
parenthesis). In such case, the expression inside the innermost set of parentheses is evaluated
first and then the outer parentheses are evaluated.
For example, we have an expression as:
x = 9 – ((12 / 3) + 3 * 2) – 1
The expression is now evaluated as:
First Pass:
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2
Note: The number of evaluation steps is equal to the number of operators in the arithmetic
expression.
Else, if either of the operand is float, then others are converted to float.
Else, if either of the operand is unsigned long int, then others will be converted to unsigned long
int.
Else, if one of the operand is long int, and the other is unsigned int, then
if a long int can represent all values of an unsigned int, the unsigned int is converted to long int.
otherwise, both operands are converted to unsigned long int.
Else, if either operand is long int then other will be converted to long int.
Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable on left side
of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of double to float
causes rounding of digits and the conversion of long int to int causes dropping of excess higher
order bits.
where, data_type is any valid c data type, and expression may be constant, variable or
expression.
In this syntax format is the format specification string. This string contains, for each variable to
be output, a specification beginning with the symbol % followed by a character called the
conversion character.
Example:
printf (―%c‖, data1);
The character specified after % is called a conversion character because it allows one data type to
be converted to another type and printed.
See the following table conversion character and their meanings.
Conversion Meaning
Character
The function scanf() is used for formatted input from standard input and provides many of the
conversion facilities of the function printf().
Syntax
scanf (format, num1, num2,……);
The function scnaf() reads and converts characters from the standards input depending on the
format specification string and stores the input in memory locations represented by the other
arguments (num1, num2,….).
For Example:
scanf(― %c %d‖,&Name, &Roll No);
Note: the data names are listed as &Name and &Roll No instead of Name and Roll No
respectively. This is how data names are specified in a scnaf() function. In case of string type
data names, the data name is not preceded by the character &.
Example with program
Write a function to accept and display the element number and the weight of a proton. The
element number is an integer and weight is fractional.
Solve here:
#include<stdio.h>
#include<conio.h>
int main()
{
Int e_num;
Float e_wt;
printf (―Enter the Element No. and Weight of a Proton\n‖);
scanf (―%d %f‖,&e_num, &e_wt);
printf (―The Element No.is:‖,e_num);
printf (―The Weight of a Proton is: %f\n‖, e_wt);
getch();
return 0;
}
CONTROL STRUCTURES, ARRAYS AND STRINGS
DECISION STATEMENTS
If statement:
Syntax :
if(expression)
statement1;
Explanation :
printf("Execute me 2");
}
Output :
Execute me 1
If Statement :
if(conditional)
{
Statement No 1
Statement No 2
Statement No 3
.
.
.
Statement No N
}
Note :
More than One Conditions can be Written inside If statement.
1. Opening and Closing Braces are required only when ―Code‖ after if statement
occupies multiple lines.
if(conditional)
Statement No 1
Statement No 2
Statement No 3
In the above example only Statement 1 is a part of if Statement.
1. Code will be executed if condition statement is True.
2. Non-Zero Number Inside if means “TRUE Condition”
if(100)
printf("True Condition");
if-else Statement :
We can use if-else statement in c programming so that we can check any condition and
depending on the outcome of the condition we can follow appropriate path. We have true path as
well as false path.
Syntax :
if(expression)
{
statement1;
statement2;
}
else
{
statement1;
statement2;
}
next_statement;
Explanation :
If expression is True then Statement1 and Statement2 are executed
Otherwise Statement3 and Statement4 are executed.
Sample Program on if-else Statement :
void main()
{
int marks=50;
if(marks>=40)
{
printf("Student is Pass");
}
else
{
printf("Student is Fail");
}
}
Output :
Student is Pass
Flowchart : If Else Statement
if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is True.
if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True.
Else Part executed if Condition Statement is False.
else
{
printf("False Block");
}
Consider Example 2 with Explanation :
More than One Conditions can be Written inside If statement.
int num1 = 20;
int num2 = 40;
else
{
printf("False Block");
}
More than One Conditions can be Written inside If statement.
int num1 = 20;
int num2 = 40;
if(num1 == 20 && num2 == 40)
{
printf("True Block");
}
Opening and Closing Braces are required only when ―Code‖ after if statement occupies multiple
lines.
Code will be executed if condition statement is True.
Non-Zero Number Inside if means “TRUE Condition”
Switch statement
Why we should use Switch Case?
One of the classic problem encountered in nested if-else / else-if ladderis
called problem of Confusion.
It occurs when no matching else is available for if .
As the number of alternatives increases the Complexity of program increases
drastically.
To overcome this , C Provide a multi-way decision statement called ‗Switch
Statement‗
See how difficult is this scenario?
if(Condition 1)
Statement 1
else
{
Statement 2
if(condition 2)
{
if(condition 3)
statement 3
else
if(condition 4)
{
statement 4
}
}
else
{
statement 5
}
}
First Look of Switch Case
switch(expression)
{
case value1 :
body1
break;
case value2 :
body2
break;
case value3 :
body3
break;
default :
default-body
break;
}
next-statement;
Flow Diagram :
61
How it works?
Switch case checks the value of expression/variable against the list of case values and
when the match is found , the block of statement associated with that case is executed
Expression should be Integer Expression / Character
Break statement takes control out of the case.
Break Statement is Optional.
#include<stdio.h>
void main()
{
int roll = 3 ;
switch ( roll )
{
case 1:
printf ( " I am Pankaj ");
break;
case 2:
printf ( " I am Nikhil ");
break;
case 3:
printf ( " I am John ");
break;
default :
printf ( "No student found");
break;
}
}
As explained earlier –
3 is assigned to integer variable ‗roll‗
On line 5 switch case decides – ―We have to execute block of code specified in 3rd case―.
Switch Case executes code from top to bottom.
62
initialization;
while(condition)
{
incrementation;
}
Note :
For Single Line of Code – Opening and Closing braces are not needed.
while(1) is used for Infinite Loop
Initialization , Incrementation and Condition steps are on different Line.
While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and then
only code is executed ]
Do while:
Do-While Loop Syntax :
initialization;
do
{
incrementation;
}while(condition);
Note :
It is Exit Controlled Loop.
Initialization , Incrementation and Condition steps are on different Line.
It is also called Bottom Tested [i.e Condition is tested at bottom and Body has to execute at least
once ]
For statement:
We have already seen the basics of Looping Statement in C. C Language provides us different
kind of looping statements such as For loop, while loop and do-while loop. In this chapter we
will be learning different flavors of for loop statement.
Different Ways of Using For Loop in C Programming
In order to do certain actions multiple times, we use loop control statements.
For loop can be implemented in different verities of using for loop –
• Single Statement inside For Loop
• Multiple Statements inside For Loop
• No Statement inside For Loop
• Semicolon at the end of For Loop
• Multiple Initialization Statement inside For
• Missing Initialization in For Loop
• Missing Increment/Decrement Statement
• Infinite For Loop
• Condition with no Conditional Operator.
Way 1 : Single Statement inside For Loop
for(i=0;i<5;i++)
printf("Hello");
Above code snippet will print Hello word 5 times.
We have single statement inside for loop body.
No need to wrap printf inside opening and closing curly block.
Curly Block is Optional.
if(condition)
{
}
}
If we have block of code that is to be executed multiple times then we can use curly braces to
wrap multiple statement in for loop.
Way 3 : No Statement inside For Loop
for(i=0;i<5;i++)
{
}
this is bodyless for loop. It is used to increment value of ―i‖.This verity of for loop is not used
generally.
At the end of above for loop value of i will be 5.
if(breaking condition)
break;
i++;
}
Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause
overflow of stack.
Form Comment
for ( i=0 ; i < 10;i++) ; For Loop with no Body (Carefully Look at the
Semicolon)
JUMP STATEMENTS:
Break statement
Break Statement Simply Terminate Loop and takes control out of the loop.
68
Way 1 : Do-While Loop
Continue statement:
loop
{
continue;
//code
}
Note :
It is used for skipping part of Loop.
Continue causes the remaining code inside a loop block to be skipped and causes
execution to jump to the top of the loop block
Loop Use of Continue !!
for
while
do-while
Goto statement:
goto label;
label :
Whenever goto keyword encountered then it causes the program to continue on the
line , so long as it is in the scope .
Types
of Goto
Forward
Backwa
rd