0 ratings0% found this document useful (0 votes) 70 views20 pagesPps Module 1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
method of describing computer algorithms using a
g g ing language.
Js an intermittent step towards the development of th
ItallowS the programmer to formulate their thoughts on the organization
sequence of a computer algorithm without the need for actually following the
exact coding syntax.
Although pseudocode is frequently used there are no set of rules for its exaet
implementation. In general, here are some rules that are frequently followed when
writing pseudocode:
The usual Fortran symobols are used for arithmetic operations (~~ +1, **)
Symbolic names are used to indicate the quantities being processed
* Gertain Fortran keywords can be used, such as PRINT, WRITE, READ, ete.
| Indentation should be used to indicate branches and loops of instruction.
Here is an example problem, including a flowchart, pseudocode,
Pseudocode:
Input: An integer Limit
‘Ouput: Two integers: Number and Sun
by one,
‘Sum and set equal to Sum.rr anez ~ .
ee egmmine eegeinee 1
\ Omit-4 oe
Topie: Programming Basi
: Structure of C program, Syntax , errors
STRUCTURE OF A C PROGRAM
e structure of a C program is a protocol (rules) to the ich he ha
ram is a protocol (1 programmer,-sehich fol
ig a C program. The gencial basic structure of C program is shown in the Thee belo
‘Geaumetiatons)
ain
¢
Local siacterations:
EiSSrem otoremonte Sey er the
Coting ner denned tuncton= (option te user) al
:
ieee nee
eer Jf comonte need
Bused on this structure, we can sketch a C program.
Example:
/* This program accepts a number & displays it to the user*/
#include void main(void)
{int number;
printf{ "Please enter a number:
scanf{ "%di", &nummber );
printf "You entered %d", number );
return 0;
i
Stepwise explanation:
#include
The part of the compiler whic)
‘preprocessor.
#include a
rogram, but instead it is an instruction
dinelude is a prscprocessor dirctive,'t is not really part of our p:
‘10 the compiler to make if do something, It tells the C compiler to include the contents of a file (in
hy.
this case the system file called stdic
‘The compiler knows it is a system file, and therefore must be looked for in a special place, by the fact
that the filename is enclosed in <> characters
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
ieeyboard, and stdio.h is the name ofthe file in which the funetions that we want fo ust Ret defined.
“The favction we want fo use is called printf, The eotual code of printf wil be tied in tater by the linker.
‘The "h portion of the filename is the language extension, which denotes an include file.
void
This literally means that this means nothing. In this ease, itis referring to the function whose name
follows.Void tells (0 C compiler that a given entity has no meaning, and produces no error,
Main In this pavticular example, the only function in the program is ealled main. A C programy is
typically made up of large nuraber of functions. Each of these is given a name by the programmer
and they refer to each other as the program runs.C regards the name main as 9 special case and will
ee
h actually gets your program from the source file is called theData Type
Inthe C programming language, data_types refer to_a_domain of allowed values & the
operations that can be performe Fortes valies, The type of a variable determines how
Fach space it occupies in storage and how the bit pattern stored is interpreted: There are 4
= Char is used tp store any
fundamental data types in C. which are- char, int, float &, doub!
fe character: int is used to store any integer valu, float is used to store any sin
any double precision floating
sin
precision floating point number & double is used to store
Boint number
We can use 2 qualifiers with these basic types to get more types.
There are 2 types of qualifiers-
qualifier signed & unsigned
Size qualifier short & lo
- data types in C can be classit
das follows:
Type Storage size Value range
Char |_| byte =128 10 127
unsigned char T byte Dw?
Integrity [2 or 4 bytes 32,768 to 32,167 oF -2,147, 483,048 t
147,483,047
hnsigned imegrity [2 or 4 bytes
or 0 10 4,294,967,295
\ Short | 2 bytes
unsigned short [2 bytes
I
long | 4 bytes =2, 147,483,048 to 2, 147,483,604
| unsigned long | 4 bytes 0 to 4,.294,967,295
Type | Storage size Value range Precision
float [4 bytes 1.2E-38 to 34E=38 6 decimal places
double [8 bytes 2.3E-308 to 1.7E=308 15 decimal places
long double [10 bytes aes 1TE+4932 19 decimal placesFopic: Components of C larguage, Standard /O in C, Fundamental data types,
Variables and memory locations
EMENTS OF ©
Every language has some basic elements & grammatical rules. Before starting with
programming, we should be acquainted with the basic elements that build the language.
Character Set
Communicating with a computer involves speaking the language the computer understands. In
——~C. various characters have heen given to communicate. Character set in C consists of;
Types Character Set
[Lower ease fez
JUpper case AZ
[Digiss 9
Special Character [(@#S%°&*
Vhite space [Tab or new lines or space
Keywords
Keywords ere the words whose meaning has already been explained to the C comp:
"keywords cennot be used 2s variable names becuse i ng 10 a
yew meaning to the keyword, which is not allowed by the computer. There are only 32
words available in C. Below figure gives a list of these keywords for your ready
reference,
KEYWorDS
. auto do goto signed unsigned
break = double if sizeof void
case else int static volatile
chat enum — tong struct while
const extern register switch
continue — float return typeodef
default for short
identifier
In the programming language C, an identifier is a combination of alphanumeric characters, the
first being a letter of the alphabet or an underline, und the remaining being any letter of the
abet, any numeric digit, or ihe underiine, —
Two rules must 6¢ kept in mind when naming identi
1. The case of aaphabetic: characte-s nificant, Using "INDEX" for a variable is no: the
samé as using "index" and né.. icf 1 them is the same as using "InDeX" for a variable, All
three refer to different ve
2. As C is defined, up t. ¢
ignificant by mos: compilers. 1f ©
compiler.
jables.
nificant characters ean be used and will be considered
re than 32 are used, they will be ignored by theConstants
A constant is an entity that doesn’t change whereas a variable is an entity that may change constants
1 be divided into two major categories: Primary Constants, Secondary Constants
Constant
Primary constant Secondary Constant
Array
Integer constant Pointer
Real integer Structure
Character constant Union
Enum. Ete
Rules for Constructing Integer Constants:
* An integer constant must have at least one digit
© [tmust not have a decimal
«© Itcan be either positive or »
* Inno sign precedes an integer cons med to be positive.
© No commas or blanks are allowed within an integ
* The allowable range for integer constants is -32768to 32767
Ex.: 426, +782.-8000. -7605
ant it is as:
oF constant
Rules for Constructing Real Constants:
© Real constants are often called Floating Point constants, The real constants could be written
in two forms—Fractional form and Exponential form.
* A real constant must have at least one digit
# It must have a decimal point
# It could be either positive or negative
* Default sign is positive
* No commas or blanks are allowed within a real consta
48.5792
4325.34, 426.0, -32.76, -
Rules for constructing real constants expressed in exponential form:
© The mantissa part and the exponential part should be separated by a letter e.
* The mantissa part may have a positive or negative sign
* Default sign of mantissa part is positive.
Lecture Notes| | Programming for Problem Solving (KCS-101/KCS-201) | |.K. Swarnakar@IT-GCET© The exponent must hi by ni
‘Xponent must have at least one digit, whiel
Define + Which must be a positive oF negative integer
* Range of real constants expressed in tial form is -3.4) 403:
is essed in exponential form i
8 “3.4038 to 3.4e38,
© EX. +3.2e-5. 4 1e8, -0.2¢+3
3.2e-5,
Rules for Constructing
A character constant
Character Constants:
is @ single alphabet, a single digit or a sin
single inverted commas.
special symbol enclosed wishin
The maximum length ofa character constant can be | character
Bs tMg, sae
VARIABLES,
Variables are na
time, A data type
that are used to store valugs. It can take different values but one at &
s associated with each variable & it decides what values the variable ean
take, Variable declaration requires that you inform C of the variable’s name and data type
Syntax — data type variable name;
Egcim page_no;
char grade:
float salary:
long y;
Declaring Variables:
‘There are two places where you can declare a variable:
After the opening brace of a block of code (usually at the top of a function)
Before a function name (such as before main() in the pro
va
am) Consider various examples:
Initialization of Variables
When a variable is declared, it contains undefined value commonly known as garbage value, Lf
we want we can assign some initial value to the variables during the declaration itself, This
called initialization of the variable.
no= 10;
expressions
An expression consists of a combination of operators. ope!
be , logical or relational. Tei
nds, variables & function calls, An
‘are some expressioi
atb~ arithmetic operation
a>b- relational operation a
b- logical operation
fune (a,b) — function eall
Statements
Statements are the primary building blocks of a program. A program is as st
7 an RUNCHIATTON. A SATEMENU 1s @ comiplete instruction to the computer. In
val d_a semicolon is needed to identity
am is a series of statements
a setticolon at the end.
INPUT-OUTPUT IN C
‘am, This can be
provides a set of built-in
yen in
When we are saying Input that means we feed some dans ins Pe
the form of file or fram command Tine. C programming fanguags DS
functions 1o read given input and feed it to the program as per restWhen we are saying
f et ea eae pate to display some data on sereen, printer or in any file.
2 guage provides a se! f built-i rn AG
Same set of built-in functions to output the data on the
Functions print) and.
inf) are the most com:
tions rit monly used to disphry e
respectively. Let us consider an example > oT |
#include //This is needed to run printil) function,
int main()
{ printt"C Programming")
1
Output:C Programming
Explanation:
‘displays the content inside quotation return 0:
Every program starts from maing) function.
printi() is a library function to display output whieh only works if #include
int main()
qint ¢
printit"Number="%
return 0;
OurputNumber=5
Input - Output of characters
include
int main()
tehar varl:
printii"Enter chara
scanfi"%c".&varl);
printf" You entered %c.
return 0;
tel
var);
Output-Enter character: g You entered gCe
Syotax eau
~> Synters cmrvr by au eur ur he Bee cod obo beg
> Comput pr ds
erg wut fellas abit x to lmprle
aspect of tre ela, frat + mot :
t $ ‘ angeeg® wl
\
Conve tt
imi fo
enfrem He mK
ee
qe bgt |
/
43 stake
2 mussig cut quotes
7 pesos out Bracke
7 Uy Supper cone cheater tun kepuseelt J GE ivshead :
oh 4
2 Mini mut a Clon ot semicolon at fie endef 4
Bratt
s veg deka 1 He we ovolt
eal err
“ a pawns Aorta cola.
2D ao ag" ot anustake.
fat gtealt a 7 tone et
ot a the of Aan bm
ms unerpected belauicurn -
ema Hab ferduce deeTopic: Arithmetic exp
OPERATORS
logical m
Operators,
operators,
An operator is as}
Module ~ 2: (Arie
sions and precedence: Operators
ional operators, mixed operands, type
NS, assignment operator, operator precedence
anipulations. C lan is rich in buil
Mise Operators
etic expressions & Conditional Branch
Arithmetic operator: Assume variable A holds 10 and variable B holds 20 then}
operators and provides the fol
“DPES UT OPERATE Arithmetic Operators. Relational Operators. Logical Operators. Batwise
Assignment Operators, Increment and decrement operators,
bol that tells the compiler 1 perlorm specific mathematical or
Conditional
Operator
Des
ription
Fxample
two operands
A> Buwillgnve
‘Subtracts second operand from the first
Bwillgive-10
Multiplies both operands
|
|
A* Bwill give 200
Divides nam,
oF by de-numerator
Modulus Operator and remainder oF alier an integer
Division
Increments operator increases inicyer value by one
B
A will
Decrements operator decreases integer value by one
»
iation
ste
WOper
variable
operat
ators:
\ holds 10 and variable B holds 20, then:
or Description
Example
—T Cheeks ifthe values of two operands are equal or not, if yes
then condition becomes true.
(A == B) isnot
truc.
! Checks if the values of two operands are equal or not. il
values are not equal then condition becomes true
(A! B) is true.
ST Cheeks ithe value of left operand is greater than the value
of right operand, if yes then condition becomes true
(A > B) is not
true.
Checks if the value of leit operand is less than the value of
right operand, if'yes then condition becomes tue
(A = B)is true.
IChecks if the value of left operand is greater than or equal to
(A >= B) is not
the value of right operand, if yes then condition becomes true
true,
| <= Checks if the value of lef operand is less than or equal to the | (A <= B) is Gue
| value of right operand, if yes then condition becomes true,
\
eal Operators:
Assume variable A holds and variable B holds 0, then:
Operator | Descrip!
Example
Called Logical AND operator. Ifboth the operands are
&E
nonzero, then condition becomes true.
(A && Byis
false
Called Logical OR Operator, [any of the wo operands is
non-zero, then condition becomes true.
(A || B) is vue
Called Logical NOT Operator. Use to reverses the |
Late of its oper
nd. If'a condition is true then Logical NOT.
operator will make false.
WA && Bris
true |irks on bits and performs bit-by-bit operation. Th
OR). ’ (XOR). << (left shifty and >~ (r
operators can operate
and double..Bit wise operators in C language are. & (bewice AND).
1 se AND).
shift). The truth tables for &,
Q p&q pig p’q ]
0 0 0 0
a
| ) 1 0 ! 1
1 y 1 1 0 |
1 0 0 T T |
able A holds 60 (00111100) and variable B holds 13 (00001101), then
Operator Description | Example
& | Binary AND Operator copies a bit to the result
exists in both operands.
\
(A & B) will give 12.
which is 0000 1100
one operand but not both.
\ [Binary OR Operator copies a bit fit exists in either (A] B) will give 61.
and. | which is 0011 1101
| | | \
[ Zi Binary XOR Operator copies the bit if it is set in (A By will give 49. |
which is 0011 0001 |
~ [Binary Ones Complement Operator is una}
the effect of “flippi
(A ) will give -61. which
is 1100 0011 in 2's
value is moved right by the number of bits specitied
by the right operand.
complement form.
==_| Binary Left Shift Operator. The left operands value Twill give 240
is moved left by the number of bits specified by the which is FEET 0000
right operand,
>> Binary Right Shift Operator. The left operands A>>2willgive
which is 0000 1111orators
ssignmen ys sues for the variables arc a ed using assignment operators,
rene wing assignment operators supported by C language
he gfe folowing aril ;
: ‘operato Description Example |
rt —fiple assignment operator, Assigns values rom right side CATR WIT
operands to left side operand assign value of A+
B into
] AND assignment operator, Itadds right operand to the his
left operand and assign the result tv left operand equivalent to C=C
+A
> Subtract AND assignment operator, It subtracts right Ais
bperand fiom the left operand and assign the result to left equivalent to C=C
Operand -A
T=] Multiply AND assignment operator, It multiplies right C= Ais
loperand with the left operand and assign the result t0 left equivalent to C=C
Operand A
= [Divide AND assignment operator, It divides le operand CHAS
itls the right operand and assign the result fo left operand equivalent 0 C= C
A
T= pdulus AND assignment operator, It takes modulus using
twvo operands and assign the result to left operand
Tet shift AND assignment operator
pe Right shift AND assignment operstor
C >>= 2 is same as
C=C>>2
Bitwise AND assignment operator
C& 2 is same as
C=C&2
™ Diwise exclusive OR and assignment oper
Dis same as C
= biawise inclusive OR and assignment operator
C |= 2 ts same: ant OPERATOR
nent/Decreme! ;
ik are cailled increment and decrement operators respectively. Both of these operators are
neve!
uscd on single operand, +f adds | to operand and ~ subtracts 1 1 operand ‘
dC ry operators, ik.
tively. For example:
J ee nd b=10
Leta
rand
a becomes 6
‘a bee
‘a becomes 6
1. a becomes 5
When i is used as prefix(like: ++var), +-+var will increment the value of va
on is used as postfix(like: var++), operator will return the value of operand first and then only
increment it. This can be demonstrated by an examp!
and then return it but, if
relude
int main()
this statement displays 2 then, only c incremented by | to 3
/ithis statement increments I to ¢ then, only ¢ is displayed
Print{%od"~=ey
Return 0:
Ourput:2 4
Conditional Operators (°
Conditional operators are used in decision making in C programming, i.e. executes different statements
condition whether itis either true or false.>
Syntax of conditional operators;
aitio ression expression l:expression?
If the test condition is true (that is, iff its value is non-zero), expression! is returned and if false
expression? is returned
(x= 523:4) :Dthis statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y
y
Mise Operators:
There are few other operators supported by c language.
Operator Description ple
sizeoh) | It is a unary operator which is used in |sizcola), where ais integer, will
finding the size of data type. constant, return 4
arrays, structure ete.
& Returns the address ofa variable. | &az will give actual address of
the variable
WHT pointer to a variable
: Pointer to a variable.7 operators Precedence in C
Gperator precedence determines the grouping of terms in an expression. This affects how an expression
js evaluated. Certain operators have higher precedence than ‘others; for example, the multiplication
operator has higher precedence than the addition operator. eae fas ae
poceeampiex= 7 #3 * 2: here, x isassigned 13, not 20 because operato!
+ so it first gets multiplied with 3#2 and then adds into
tors with the highest precedence appear at the top of the table. those with the lowest ape:
* has higher precedence than
ae
Here, ope!
ithe bottom. Within an expression, higher precedence operators will be evaluated first
Category Operator Associativity
Postfix Oe. == Left to right
Unary (iype)® &sizeor Right to lett
|
> Multiplicative *7% Tote ren |
7 Additive - Left to right
Shift Teli to ight
Relational Tefitorght |
| ead E Left to right t
| Bitwise AND & Lettto right |
Bitwise XOR Lette right
Bitwise OR Lelitor
Logical AND xx Telttonght |
Togical OR Tel
Conditional ” Right to lett 1
= Right w ett 4
Comma Let_
and else,
Topic: Conditional Branchi Applying if and switch statements, nesting.
use of break and Default with switch,
If, ifelse, Case switeh statements
CONTROL STATEMENTS,
Control states
be executed They
siglements are class
nts enable Ws to specify the order in which the various instructions in the program are to
‘efine how the control red To other parts of the program, Control
Selection/tranching
eect { ne |
==
Ce
a) If statement
Syntax:
it{boolean_expression}
1 /* statement(s) will execute if the Boolean expression is true *
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If boolean expression evaluates to false then the first set of code alter the end of the if
statement (after the closing curly brace) will be executed. C programming language assumes any
non-zero and non-null values as true and if it is either zero or null th
value
Flow Diagra
a it is assumed as false
Se EE
Nample:#include
int main ()
{ inta=10;
iff a< 20)
{ Printita is less than 20\n" );
}
Printit"value ofa is : %d\n", a);
When the above code is compiled and executed, it produces following result
a is less than 20;
value ofa is: 10
(b) if-else statement
Syntay: The syntax ofan if..clse statement in C programming language i
if{boolean_expression)
ement(s) will execute if the boolean expressivn is true "/
| /* statement(s) will execute if the boolean expression is false */
If the Boolean expression evaluates to true then the if block of code will be executed otherwise
else block of code will be executed programming language assumes any non-zero and non-null
Values as true and if it is either zero or null then it is assumed as false value.
Flow Diagram:
If condition
true
If condition
is false
Example:
Hinchide
main ()
1 inta= 100;
ifa<20)
1 Printi("a is less than 20\n" x»
else
{ Printit"a is not less than 20\n" );
i Printil"value of a is Yod\n". a);}\
When the above code is compiled and executed, it produces following result
a is not less than 20: Peo
value ofa is: 100
Ise statement
fatement is as follow
(c) Nested if
The syntax fora nested if's
if boolean_expression 1)
{Executes when the Boolean expression | is true */
if{boolean_expression 2)
* Executes when the Boolean expression 2 is true *
Example:
#include
main ()
{int a= 100;
int b = 200; \
if a== 100)
t ift 200)
{ printf("Value of a is 100 and b is 200\n" );
}
printtt"Exact value ofa is : %din", a);
print{("Exact value of b is : Yod\n", b ):
return 0:
When the above code is compiled and executed. it produces following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact, value of b is : 200
(d) A switch statement
Allows a variable to be tested for equality against a list of values. Each value is called a case, and
the variable being switched on is checked for each switch ease. Syntax.
switeh(expression)
{case constant-expression
statement(s);
break: * optional */
case constant-expression +
statement(s);
break; * optignal */
‘* you can have any number of case statements */
default: Optional *
statement(s):
The following rules apply to a switeh statement
* You can have any number of ease statements within a switch, Each case is followed by
the value to be compared to and a colonA
The constant-expression for a case must be the s
me data type as the variable in the
swviteh, and it must be at constant or a literal
© When the sariable being switehed on is equal fo a case, the statements following that case
will excette until a break statement is reached
When a break statement is reached, the swviteh terminates, and the flow of control jumps
to the nevt ling following the switeh statement
«Not every case needs to contain a break, Hino break appears. the Mow of contro! will fall
through fo subsequent cases until « break is reached
4 Aswitch statement ean have an optional default case, which must appear at the end of the
savitch ‘The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case
Flow mM:
°
Example:
main ()
4 char
case
‘Well done\n" );
‘You passed\n" );
print{("Better try again\n" );
break:
default
print{("Invalid grade\n" J;
Whe:
the abs
| prinui("Your grade is %e\n", grade );
de is compiled and executed, it produces following result
Well don
Your grade is B