Computer System:: Hardware
Computer System:: Hardware
Tech I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------
Computer System:
A computer is a system made up of two major components:
I. Computer Hardware.
II. Computer Software.
Page | 1
2
Input Devices: The input device is usually a keyboard where programs and data
are entered into the computer. Other Input Devices : a touch screen , a mouse , a pen ,
an audio input unit.
Primary Storage: It is also known as main memory. It is a place where the programs and
data is stored temporarily during processing. The Data in primary storage is erased
when we turn off a personal computer or when we log off from a time-sharing
computer (volatile).
Output Devices: The output device is usually a monitor or a printer to show output. If the
output is shown on the monitor, it is a soft copy and if the output is printed on the
printer, it is a hard copy.
Auxiliary Storage Devices (secondary storage devices): It is used for both input and output. It
is also known as secondary storage. It is a place where the programs and data are
stored permanently. When we turn off the computer the programs and data remain
in the secondary storage, ready for the next time when we need them.
II. Computer Software: Software is the collection of Programs (instructions) that allow the hardware
to do its job.
There are two types of Computer Software.
System Software
Application Software
The following figure shows the Computer Software.
ii. System Support Software: System Support Software provides system utilities and other operating
services. Examples of system utilities are sort programs and disk format programs. Operating
services consist of programs that provide performance statistics for the operational staff and
security monitors to protect the system and data.
iii. System Development Software: It includes language translators that convert programs in to
machine language for execution , debugging tools to ensure that programs are error - free and
computer -assisted software engineering ( CASE ) systems.
Application Software: It is directly responsible for helping users to solve their problems. Application
software is broken into two classes.
General - Purpose Software
Application - Specific Software
i. General Purpose Software: It is purchased from a software developer and can be used for
more than one application. Examples: word processors, database management systems, computer –
aided design systems. They are labeled general purpose because they can solve a variety of user
computing problems.
ii. Application Specific Software: It can be used only for its intended purpose. Example: A general
ledger system used by accountants.
They can be used only for the task for which they were designed. They cannot be used for other
generalized tasks.
Relationship between system and application software is shown in the figure:
Each circle is an interface point. The inner core is hardware. The user is represented by the outer layer. To work
with the system, the typical user uses some form of application software. The application software inturn interacts
with operating system ( OS ), which is part of system software layer. The System software provides the direct
interaction with the hardware. The opening at the bottom of the figure is the path followed by the user who
interacts directly with the Operating System when necessary
INTRODUCTIONTOPROGRAMMING
Page | 3
4
Before moving on to any programming language, it is important to know about the various types of
languages used by the computer. Let us first know what the basic requirements of the programmers
were & what difficulties they faced while programming in that language.
COMPUTERLANGUAGES
Languages are a means of communication. Normally people interact with each other through a
language. On the same pattern, communication with computers is carried out through a language.
This language is understood both by the user and the machine. Just as every language like English,
Hindi has its own grammatical rules; every computer language is also bounded by rules known as
syntax of that language. The user is bound by that syntax while communicating with the computer
system.
Low Level Language: The term low level highlights the fact that it is closer to a language
which the machine understands.
o Machine Language: This is the language (in the form of0’sand 1’s, called binary
numbers) understood directly by the computer. It is machine dependent. It is
difficult to learn and even more difficult to write programs.
o Assembly Language: This is the language where the machine codes comprising of
0’sand 1’s are substituted by symbolic codes (called mnemonics) to improve their
understanding. It is the first step to improve programming structure. Assembly
language programming is simpler and less time consuming than machine level
programming, it is easier to locate and correct errors in assembly language than in
machine language programs. It is also machine dependent. Programmers must have
knowledge of the machine on which the program will run.
HighLevelLanguage: Low level language requires extensive knowledge of the hardware
since it is machine dependent. To overcome this limitation, high level language has been
evolved which uses normal English, which is easy to understand to solve any problem.
Highlevel languages are computer independent and programming becomes quite easy and
simple. Various high level languages are given below:
Page | 4
5
Procedure-oriented languages
High level languages designed to solve general-purpose problems are called procedural languages or
third generation languages. These include BASIC, COBOL, FORTRAN, C, C++, and JAVA, which
are designed to express the logic and procedure of a problem.
Page | 5
6
Problem-oriented languages
Problem-oriented languages are used to solve specific problems and are known as the fourth-
generation languages. These include query languages, report generators and application generators
which have simple, english-like syntax rules.
3 . Natural languages
Natural languages are designed to make a computer to behave like an expert and solve
problems. The programmer just needs to specify the problem and the constraints for
problem- solving. Natural languages such as LISP and PROLOG are mainly used to
develop artificial intelligence and expert systems. These languages are widely known as
fifth generation languages.
PROGRAMMINGLANGUAGETRANSLATORS
As you know that high level language is machine independent and assembly language
though it is machine dependent yet mnemonics that are being used to represent
instructions are not directly understandable by the machine. Hence to make the machine
understand the instructions provided by both the languages, programming language
instructors are used. They transform the instruction prepared by programmers into a form
which can be interpreted & executed by the computer. Flowing are the various tools to
achieve this purpose:
Compiler: The software that reads a program written in high level language and translates
it into an equivalent program in machine language is called as compiler. The program
written by the programmer in high level language is called source program and the
program generated by the compiler after translation is called as object program.
Assembler: The software that reads a program written in assembly language and
translates it into an equivalent program in machine language is called as assembler.
Linker: A linker or link editor is a computer program that takes one or more object files
generated by a compiler and combines them into a single executable file, library file, or
another object file.
Page | 6
7
Step1:CreatingSourceCode
Source code is a file with Cprogramming instructions inhighlevel language. To create sourcecode,
we use any text editor to write the program instructions. The instructions written in the source
code must follow the Cprogramming language rules.
Step2:CompileSourceCode (Alt+F9)
Compilation is the process of converting high level language instructions into low level
language instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C.
Whenever we press Alt + F9, the source file is going to be submitted tot he Compiler .On
receiving a source file, the compiler first checks for the Errors. If there are any Errors then
compiler returns List of Errors, if there are no error then the source code is converted into object
code and stores it as file with .obj extension. Then the object code is given totheLinker.The
Linker combines
both the object code and specified header file code and generates an Executable file with.exe
extension.
Step3:Executing/RunningExecutableFile(Ctrl+F9)
After completing compilation successfully, an executable file is created with .exe extension. The
processor can understand this .exe file content so that it can perform the task specified in the
source file.
We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl+F9,the .exe file is
submitted to the CPU .On receiving .exefile, CPU performs the task according tothe instruction
written in the file.The result generated from the execution is placed in a window called User
Screen.Step4:CheckResult(Alt+F5)
After running the program ,the result Is placed into User Screen. Just we need to openthe
UserScreen to check the result ofthe program execution. We use the short cut key Alt+F5toopen
the User Screen and check theresult.
ExecutionProcessofaCProgram Page | 7
8
The file which contains c program instructions in high level language is said to b e source
code .Every c program source file is saved with .c extension, for example Sample .c.
Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler checks for
the errors,if there are any errors ,it returns list of errors, otherwise generates object codeine file
with nameSample.obj and submit it to the linker.
Linker combines the code from specified header file into object file and generates
executable file as Sample.exe. With this compilation process completes.
Now, weneed to Run the executable file (Sample.exe).To run a program we press Ctrl +
F9.When we press Ctrl + F9the executable file is submitted to the CPU.
Then CPU performs the task according to the instructions written in t hat program and place
the result into User Screen.
ThenwepressAlt+F5toopenUserScreenandchecktheresultof the program.
Overall Process:-
OctalNumberSystem:-
Octal number system has eight digits –0, 1, 2, 3, 4, 5, 6 and 7. Octal number system is also a
Page | 8
positional value system with where each digit has its value expressed in powers of 8, as shown
9
here −
(726)8=7×82+2×81+6×80
= 448+16+6
=((470)10
(16)16=1X161+6X60=16+6=(22)10
FEATURES OF C LANGUAGE
It is reliable ,simple and easy to use.
C is a small ,block-structured programming language.
C is a portable language, which means that C programs written on one system can be run
on other systems with little or no modification.
C has one of the largest assortments of operators, such as those used for calculations and
data comparisons.
Although the programmer has more freedom with data storage, the languages do not check data type
accuracy for the programmer
By the early 1980s, C was already a dominant language in the minicomputer world of
Unix systems. Since then, it has spread to personal computers (microcomputers) and to
mainframes.
Many software houses use C as the preferred language for producing word processing
programs, spreadsheets, compilers, and other products.
C is an extremely flexible language—particularly if it is to be used to write operating
systems.
Unlike most other languages that have only four or five levels of precedence, C has 15.
CHARECTERESTICS OF A CPROGRAM
Page | 9
Middle level language.
10
USES
Page |
The C programming language is used for developing system applications that forms a major
10
11
portion of operating systems such as Windows, UNIX and Linux. Below are some examples of C
being used:
Database systems
Graphics packages
Word processors
Spreadsheets
Operating system development
Compilers and Assemblers
Network drivers
Interpreters
STRUCTUREOFACPROGRAM
The structure of a C program is a protocol (rules) to the programmer, which he has to follow
while writing a C program. The general basic structure of C program is shown in the figure
below.
Page |
11
12
Stepwiseexplanation:
#include
The part of the compiler which actually gets your program from the source file is called
the preprocessor.
#include<stdio.h>
#include is a pre-processor directive. It is not really part of our program, but instead it is
an instruction to the compiler to make it do something. It tells the C compiler to include
the contents of a file (in this case the system file called stdio.h).
The compiler knows it is a system file,a nd there fore must be looked for in a special
place, by the fact that the filename is enclosed in <> characters
<stdio.h>
stdio.h is the name of the standard library definition file for all Standard Input and Output
functions.
Your program will almost certainly want to send information to the screen and read things
from the keyboard, and stdio.h is the name of the file in which the functions that we want
to use are defined.
The function we want to use is called printf. The actual code of printf will be tied in later
by the linker.
The".h"portion of the file name is the language extension, which denotes an include file.
Page |
12
13
void
This literally means that this means nothing. In this case, it is referring to the function
whose name follows.
Voidtellsto Ccompiler thata given entity has no meaning, and produce sno error.
main
In this particular example ,the only function in the program is called main.
A C program is typically made up of large number of functions. Each of these is given
aname by the programmer and they refer to each other as the program runs.
C regards the name main as a special case and will run this function first i.e. the program
execution starts from main.
(void)
Thisisapairofbracketsenclosingthekeywordvoid.
Ittellsthecompilerthatthefunctionmainhasnoparameters.
Aparametertoafunctiongivesthe functionsomethingtowork on.
StructureofCprogram
StructureofCprogramisdefinedbysetofrulescalledprotocol,tobefollowed by programmer
while writing C program.
AllCprogramsarehavingsections/partswhicharementionedbelow.
Documentation section
Link Section
Definition Section
Global declaration section
Function prototype declaration section
Mainfunction
Userdefinedfunctiondefinitionsection
Page |
13
14
SourceFile-This file contains the source code of the program. The file extension of any c
file is .c. The file contains C source code that defines the main function & maybe other
functions.
Header File- A header file is a file with extension .h which contains the C function
declarations and macro definitions and to be shared between several source files.
Object File-An object file is a file containing object code, with an extension .o, meaning
relocatable format machine code that is usually not directly executable. Object files are
produced by an assembler,compiler,orotherlanguagetranslator,andusedasinputtothe linker,
which in turn typically generates an executable or library by combining parts of object
files.
Executable File-The binary executable fileis generated by the linker. The linker links the
various object files to produce a binary file that can be directly executed.
Page |
14
15
Page |
15
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
ELEMENTSOFC
Tokens inC
OPERATORS
SPECIAL
STRINGS
TOKENS
C CONSTANTS
IDENTIFIERS
KEYWORDS
Identifiers
RulesforanIdentifier
IdentifiersarealsocasesensitiveinC.ForexamplenameandNamearetwo different
identifier in C.
KeywordsarenotallowedtobeusedasIdentifiers.
Nospecialcharactersarepermitted,such(,,:,..%,#,!)
NospaceisallowedinbetweentheIdentifiers.
Maximumnumberofcharactersallowedforanidentifieris63for 64 bit(31 for 32bit).
Keywords:
Page | 16
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
auto double int struct
do if static While
Letters(all alphabetsatoz&AtoZ).
Digits(alldigits0to9).
Specialcharacters(suchascolon:,semicolon;,period.,underscore_,ampersand&etc).
DATATYPES:
Data types in c refer to an extensive system used for declaring variables or functions of
differenttypes.Thetypeofavariabledetermineshowmuchspaceitoccupiesin storage
eandhowthebitpatternstoredisinterpreted.
ThetypesinCcanbeclassifiedasfollows–
Basic Types: They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types
Page | 17
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
The type void:The type specifier void indicates that no value is available.
Derived types: They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union
types and (e) Function types.
i) Integer (int)
ii) Character(char)
iii) Floating (float)
iv) Double – precision floating point(double)
Page | 18
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
DATA TYPES RANGE Size Control string
-215 to 215 -1
int 2 bytes %d
-32768 to +32767
Character type:-
Single character can be defined as a character (char) type data. Characters are usually stored in 8 bits
of internal storage. Two classes of char types are there.
signed char, unsigned char.
signed char(or) char 1 byte- -128 to +127%c
unsigned char 1 byte 0 to 255%c
Types of c constants
1. Integer constants
2. Real constants
3. Character constants
4. String constants
1. Integer constants: An integer constant refers to a sequence of digits. There are three types of
integers, namely, decimal integer, octal integer and hexadecimal integer.
Constant Meaning
‗\0‗ Null
‗\t‗ Horizontal tab
‗\b‗ Back space
‗\a‗ Audible alert
‗\f‗ Form feed
‗\n‗ New line
‗\r‗ Carriage return
‗\v‗ Vertical tab
‗\‗‗ Single quote
‗\‖‗ Double quote
‗\?‗ Question mark
‗\\‗ backslash
These character combinations are called escape sequences.
String constants: A string constant is a sequence of character enclosed in double quotes. The
characters may be letters, numbers, special characters and blank space.
Examples are: ‖HELLO!‖ ‖979‖ ‖welcome‖ ― !1‖ ―5+3‖ ―X‖
Variable: It is a data name that may be used to store a data value. It cannot be changed during the
execution of a program. A variable may take different values at different times during execution. A
variable name can be chosen by the programmer in a meaningful way so as to reflect its function or
nature in the program.
Rules:
Variable names may consist of letters, digits and under score( _ ) character.
First char must be an alphabet or an ―_‖(underscore)
Length of the variable cannot exceed upto 8 characters, some C compilers can
Recognized upto 31 characters.
White space is not allowed.
Variables name should not be a keyword.
Uppercase and lower case are significant.
Ex:- mark,sum1,tot_value,delhivalid
Prics$, group one, char invalid
Ex:
/*…………….Program Name… ................................ */
main()
{
/*……………….Declaration ....................................................... */
float x,y;
int code;
shortint count;
long int amount;
double deviation;
unsigned n;
char c;
/*…………………………Computation ..................................................... */
}/*…………………………Program ends ............................................... */
Initialization of variable: Initialize a variable in c is to assign it a starting value. Without this we
can't get whatever happened to memory at that moment.
C does not initialize variables automatically. So if you do not initialize them properly, you can get
unexpected results. Fortunately, C makes it easy to initialize variables when you declare them.
For Example :
int x=45;
char c=’a’;
Variable:Variables are means for location in memory used by a program to store data. The
size of that block depends upon the range over which the variable is allowed to vary. To
identify the variables, you have a name unique to every single variable. This is called a
variable name. Before using a variable, use variables to what is called a variable declaration
that we have to reveal the names and data types that can be stored in the variable.
Constant: Constants refer to fixed values that do not change during the execution of a
Page | 23
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
program.We have ineger constants, real constants,character constants and string constants.
Example:123,’x’\a,0.s.
Operators:
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables.
C operators can be classified into a number of categories, they are
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise Operators
8. Special operators
1. Arithmetic Operators: C provides all the basic arithmetic operators. These can operate on any
built –in data type allowed in C.
The arithmetic operators are listed as follows:
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
Integer division truncates any fractional part. The modulo division operation produces the remainder
of an integer division.
Ex: Here a and b are operands, let a=14 and b=4 we have the following results
a-b = 10
a+b = 18
a*b = 56
a/b = 3(coefficient)
a%b = 2(remainder)
2. Relational Operators:
Relational operators are used for comparing two quantities, and take certain decisions. For example
Page | 24
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
we may compare the age of two persons or the price of two items….these comparisons can be done
with the help of relational operators.
An expression containing a relational operator is termed as a relational expression. The value of a
relational expression is either one or zero. It is one if the specified relation is true and zero if the
relation is false.
Ex:- 13<34 (true) 23>35(false)
C supports 6 relational operators
Operator Meaning
< is less than
<= is less than or equal to
> is greater than t
>= is greater than or equal to
== is equal to
!= is not equal to
Ex:- 4.5<=10(true)
6.5<-10(false) 10<4+12(true)
When arithmetic expression are used on either side of a relational operator, the arithmetic expression
will be evaluated first and then the results compared, that means arithmetic operators have a higher
priority over relational operators.
3. Logical Operator:
C has 3 logical operators. The logical operators are used when we want to test more than one
condition and make decisions. The operators are as follows:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
The logical operators && and || are used when we test more than one condition and make decisions.
Ex:- a>b && x==45
This expression combines two or more relational expressions, is termed as a logical expression or a
compound relational expression. The logical expression given above is true only if a>b is true and
x==10 is true. If both of them are false the expression is false. The truth table for logical and and
logical or operators are
Page | 25
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
OP1 OP2 OP1&&OP2 OP1||OP2
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
4. Assignment operator:
These operators are used to assign the result of an expression to a variable. The usual assignment
operator is ‖=‟. In addition ,C has a set of shorthand assignment operators of the form:
v op = exp;
Where v is a variable, exp is an expression and op is a C binary arithmetic operator. The operator
op=is known as the shorthand assignment operator.
The assignment statement v op=exp; is equivalent to v =v op (exp);
Ex:- x+=y+1; is equivalent to x= x+(y+1); a*=a; is equivalent to a=a*a;
The use of short hand assignment operators has the following advantages:
What appears on the left-hand side need not be repeated and therefore it becomes easier to
write
The statement is more concise and easier to read
The statement is more efficient
Page | 26
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
y= m++;
the value of y=5 and m=6.
A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. On
the other hand, a postfix operator first assigns the value to the variable on left and then increments the
operand.
6. Conditional operator:
A ternary operator pair ‖?:‖ is available in C to construct conditional expressions of the form
exp1 ?exp2 : exp3 Where exp1,exp2 and exp3 are expressions,
The operator ?: works as follows: exp1 is evaluated first. If it is non-zero (true), then the expression
exp 2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 is evaluated and its
value becomes the value of the expression.
Ex:- a=10; b=45;
X = (a>b) ?a:b;
o/p:- X will be assigned the value of b (45).
7. Bitwise Operators:
C supports a special operator knows as bitwise operators for manipulation of data at bit level. These
operators are used for testing the bits, or shifting them right to left. Bitwise operators may not be
applied to float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left(c=30;c<<1 c value =30x2=60)
>> Shift right( c=10; c>>1 c value =10/2=5)
:Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ is as follows –
p q p &q p | q p ^ q
Page | 27
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1 1
1 1 1 1 0 0
1 0 0 1 1 0
Assume A = 60 and B = 13 in binary format, they
will be as follows − A = 0011 1100
B = 0000 1101
Special operators:
C supports some special operators such as comma operator, size of operator, pointer operators
(& and *) and member selection operators ( . and -> ).
comma operator: The comma operator is used to link the related expressions together. A comma-
linked list of expressions is evaluated left to right and the value of right- most expression is the value
of the combined expression. For example, the statement
value = (x=10, y=5, x+y);
Page | 28
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
This statement first assigns the value 10 to x, then assigns 5 to y and finally assigns 15. In for loops:
for (n=1 , m=10, n<=m; n++, m++);
sizeof operator: The sizeof is a compile time operator and when used with an operand, it returns the
number of bytes the operand occupies. The operand may be variable, a constant or a data type
qualifier.
m = sizeof (sum); n = sizeof (long int);
The sizeof operator is normally used to determine the lengths of arrays and structures when their sizes
are not known to the programmer. It is also used to allocate memory space dynamically to variables
during execution of a program.
Page | 29
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
double.
if one of the operand is float ,the other will be converted to float and the result will be float.
if one of the operand is unsigned long int, the other will be converted to unsigned long int and
the result will be unsigned long int.
if one of the operand is long int, the other is unsigned int then unsigned int can be converted
into long int, the unsigned int operand will be converted as such and the result will be long int.
else both operands will be converted to unsigned long int and the result will be unsigned long
int.
else if one of the operand is long int ,the other will be converted into long int and the result will
be long int.
else if one of the operand unsigned int ,the other will be converted into unsigned int and the
result will be unsigned int.
The final result of an expression is converted to the type of the variable on the left of the assignment
sign before assigning the value to it. The following changes are introduced during the final
assignment.
float to int causes truncation of the fractional part double to float causes rounding of digits
Page | 30
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
long int to int causes dropping of the excess higher order bits Ex: Consider the following variables
along with their datatypes:
int i,x; float f; double d; long int l;
eg:
f=f/x;
2. Explicit: In this type of conversion, the programmer can convert one data type to other data type
explicitly.
Syntax: (datatype) (expression)
Expression can be a constant or a variable
Ex: y = (int) (a+b)
y= cos(double(x)) double a = 6.5 double b = 6.5
int result = (int) (a) + (int) (b) -> result = 12 instead of 13.
int a=10
float(a)->10.00000
24. : Expressions:
An expression in C is some combination of constants, variables, operators and function calls.
Sample expressions are: a + b tan(angle)
• Most expressions have a value based on their contents.
• A statement in C is just an expression terminated with a semicolon. For example:
sum = x + y + z; printf("Go Buckeyes!");
The rules given below are used to evaluate an expression,
o If an expression has parenthesis, sub expression within the parenthesis is evaluated first
and arithmetic expression without parenthesis is evaluated first.
o The operators of high level precedence are evaluated first.
o The operators at the same precedence are evaluated from left to right or right to left
depending on the associativity of operators.
Expressions are evaluated using an assignment statement of the form: variable = expression;
variable is any valid C variable name. When the statement is encountered, the expression is evaluated
first and the result then replaces the previous value of the variable on the left-hand side. All variables
used in the expression must be assigned values before evaluation is attempted.
Ex:- x = a*b-c; y = b/c*a; z = a-b / c+d;
Ex:- x= a-b/3+c*2-1 when a=9, b=12, and c=3 the expression becomes.
x = 9-12/3 +3*2-1
Step1: x = 9-4+3*2-1 Step2: x = 9-4+6-1
Page | 31
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
Step3: x = 5+6-1 Step4: x = 11-1 Step5: x = 10
Syntax:
if ( condition )
{
stmt block;
}
stmt-x;
In this syntax,
if is the keyword. <condition>is a relational expression or logical expression or any expression
Page | 32
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
that returns either true or false. It is important to note that the condition should be enclosed
within parentheses ‗(‗and ‗ ) ‗.
The stmt block can be a simple statement or a compound statement or a null statement.
stmt-x is any valid C statement.
The flow of control using simple if statement is determined as follows:
Whenever simple if statement is encountered, first the condition is tested. It returns either true or false.
If the condition is false, the control transfers directly to stmt-x without considering the stmt block. If
the condition is true, the control enters into the stmt block. Once, the end of stmt block is reached, the
control transfers to stmt-x
Page | 33
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
Program for if statement:
#include<stdio.h>
int main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n");
}
Output: enter age 57 person is retired
2. if—else statement
if…else statement is used to make a decision based on two choices.
It has the following form:
Syntax:
if(condition)
{
true stmt block;
}
else
{
false stmt block;
}
stmt-x;
In this syntax,
if and else are the keywords.
<condition>is a relational expression or logical expression or any expression that returns either
true or false. It is important to note that the condition should be enclosed within parentheses (
and ).
The true stmt block and false stmt block are simple statements or compound statements or null
statements.
stmt-x is any valid C statement.
Page | 34
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
The flow of control using if...else statement is determined as follows:
Whenever if...else statement is encountered, first the condition is tested. It returns either true or false.
If the condition is true, the control enters into the true stmt block. Once, the end of true stmt block is
reached, the control transfers to stmt-x without considering else-body.
If the condition is false, the control enters into the false stmt block by skipping true stmt block. Once,
the end of false stmt block is reached, the control transfers to stmt-x.
Page | 36
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
Page | 37
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
if(b>c)
printf("%d\n",b);
else
printf("%d\n",b);
}
}
Output: enter three values 3 2 4
4
4. else—if Ladder
else-if ladder is one of the conditional control-flow statements. It is used to make a decision among
multiple choices. It has the following form:
Syntax: if(condition 1)
{
statement 1;
}
else if(condition 2)
{
statement 2;
}
else if(condition 3)
{
statement 3;
}
else if(condition n)
{
statement n;
}
else
{
default statement;
}
stmt- x;
Page | 38
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
In this syntax,
if and else are keywords. There should be a space between else and if, if they come together.
<condition1>,<condition2>….<condtionN>are relational expressions or logical expressions or
any other expressions that return either true or false. It is important to note that the condition
should be enclosed within parentheses ( and ).
statement 1, statement 2,statement 3……,statement n and default statement are either simple
statements or compound statements or null statements.
stmt-x is a valid C statement.
avg=(m1+m3+m3)/3;
if(avg>75){
printf("distinction");
}
else if(avg>=60 &&avg<75)
{
printf("first class");
}
else if(avg>=50 &&avg<60)
{
printf("second class");
}
else if (avg<50)
{
printf("fail");
}
}
Output: enter three subject marks85 80
81Distinction
Forloop:
The general form of a for loop is
for(initialization; test-condition; increment;)
{
Body of the loop.
}
The execution of a for loop is as follows:
7. The initialization statement is executed only once
8. Then, the test expression is evaluated. If the test expression is evaluated to
9. False,the for loop is terminated.
10. however,if the test expression is evaluated to true,statements inside the body of for loop are
executed,and the update expression is updated.
11. Again the test condition is evaluated. Page | 40
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
12. This process goes on until the test expression is false.When the test expression is false,the loop terminates.
Example:
Syntax:,while(condition),{ Syntax:,do,{
} }while(condition);
Since condition is checked first, statements may or Since condition is checked later, the body
may not get executed. statements will execute at least once.
The main feature of the while loop is,its an entry The main feature of the do while loops is it is an exit
controlled loop. controlled loop
Page | 41
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
Using do whileloop
NESTINGOFLOOPS
Cprogramminglanguageallowsusingoneloopinsideanotherloop.Followingsectionshowsfew examples to
illustrate the concept.
Syntax:
for(init;condition;increment)
{
Page | 42
for(init;condition; increment)
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
{
statement(s);
}
statement(s);
}
Thesyntaxforanestedwhileloop statementinC programminglanguageisas follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
do
{
statement(s);
do
{
statement(s);
}while(condition);
} while(condition);
1. Programtoprint seriesfrom10 to1 usingnested loops.
#include<stdio.h>
void main ()
{
int a;
a=10;
for (k=1;k=10;k++)
{
while(a>=1)
Page | 43
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
{
printf ("%d",a);
a--;
}
printf("\n");
a= 10;
}
}
Output:
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
Switch Case
Consider a situation in which we have more number of options out of which we need to select only one option
that is to be executed. Such kind of problems can be solved using nested if statement. But as the number of
options increases, the complexity of the program also gets increased. This type of problems can be solved
very easily using switch statement. Using switch statement, one can select only one option from more number
of options very easily. In switch statement, we provide a value that is to be compared with a value associated
with each option. Whenever the given value matches with the value associated with an option, the execution
starts from that option. In switch statement every option is defined as a case.
Page | 44
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
The switch
statement is a multi-way branch statement
i. It is a multi way decision making statement. It is used in the case of multiple conditions.
ii. In a program if there is a possibility to choose a choice from a number of options, this
structure is useful.
iii. The switch statement requires one argument of int or char data type known as switch
variable; it is compared with number of case options.
iv. If the value of any case constant matching with case variable/expression, then that
particular block of statements will be executed.
v. If there is no such matching case constant then default block will be executed.
Jump statements
:The break statement in C programming has the following two usages −
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops, the break statement will stop the execution of the innermost
loop and start executing the next line of code after the block.
Syntax
The syntax for a break statement in Page | 45
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
C is as follows
break;
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; Page | 46
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
Page | 47
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
The continue can be used in other parts of a loop, too, where it may
occasionally help to simplify the logic of the code and improve readability.
continue has no special meaning to a switch statement, where break does have.
Inside a switch, continue is only valid if there is a loop that encloses the switch,
in which case the next iteration of the loop will be started.
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 */
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.
The goto works in an obvious way, jumping to the labelled statements. Because
the name of the label is only visible inside its own function, you can't jump from one
function to another one.
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
Page | 48
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
deep suspicion.
ALGORITHM
refers to the logic.
it is step by step description how to arrive at the solution to the problem.
algorithm is define as sequence of instruction that when executed in the specified
sequence the desired results are obtained .
2. Input : Zero or more quantities are externally supplied.
3. Output: At least one quantity is produced.
4. Definiteness : Each instruction is clear and unambiguous. Ex: Add B or C to A
5. Finiteness : Algorithm should terminate after finite number of steps when traced inall
cases. Ex: Go on adding elements to an array
6. Effectivenes: Every instruction must be basic i.e., it can be carried
out, by a personusing pencil and paper.
7. Algorithm must also be general to deal with any situation.
8. Advantages of Algorithms:
9. It provides the core solution to a given problem. the solution can be implemented on a
computer system using any programming language of user‗s choice.
10. It facilitates program development by acting as a design document or a blue print of
a givenproblem solution.
11. It ensures easy comprehension of a problem solution as compared to an
equivalent computer program.
12. It eases identification and removal of logical errors in a program.
13. It facilitates algorithm analysis to find out the most efficient solution to a given
problem.
14. Disadvantages of Algorithms:
15. In large algorithms the flow of program control becomes difficult to
track. Algorithms lack visual representation of programming constructs
like flowcharts;
16. thus understanding the logic becomes relatively difficult
Page | 49
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
Flow chart
It is pictorial representation of step by step solution of a problem.
Programmer often uses it as a program planning tool for visually organizing step necessary to solve a
problem.
It uses boxes of different shapes that denote different type of instruction.
While making a flow chart a programmer need not to pay attention on the elements
of the programming language, he has to pay attention to the logic of solution to the
problem
Page | 50
Subject: Programming for Problem Solving(B.Tech. I Year)
---------------------------------------------------------------------------------------------------------------------------------------------------------
num1 , num2
Step 3 : temp
= num1 Step
4 : num1 =
num2
Step 5 : num2
= temp
Step 6 : Output
num1 , num2
Step 7 : Stop
Flowcharts:
Page | 51