PSPC Chapter 1
PSPC Chapter 1
TOPICS
Unit-1
Introduction to Computer Programming:
Computing Environments,
Computer Languages,
Creating and Running Programs.
Introduction to C Language:
C Identifiers,
Data Types,
Operators,
Variables,
Constants,
Input / Output,
Expressions,
Precedence and Associativity,
Evaluating Expressions,
Type Conversion,
Statements,
Bitwise Operators.
Computing Environments
Definition:
Computing environment is a collection of computers/machines, software and networks that
support the processing and exchange of electronic information.
The typical meaning of an algorithm is a formally defined procedure for performing some
calculation. If a procedure is formally defined, then it must be implemented using some
programming languages. The algorithm give the logic of the program, that is , step-by-step
description of how to arrive a solution.
2. Decision: Decision statements are used when the the execution of a process depends on
the outcome of some condition. The general form of the if construct can be given as:
A condition in this context is any statement that may evaluate either to a true value or a
false value. If the condition is true then the process is executed.
if condition
then process1
else process2
This form is commonly known as the if-else construct. Here, if the condition is true
then process1 is executed, else process2 is executed. An algorithm to check the equality of two
numbers is shown in figure.
3. Repetition: Repetition, which involves executing one or more steps for a number of
times, can be implemented using constructs such as the while, do-while, and for loops. These
loops execute one or more steps until some condition is true.
1) Start and end symbols are also known as the terminal symbols and are represented as
circles, ovals, or rounded rectangles. Terminal symbols are always the first and the
last symbols in a flowchart.
2) Input / Output symbols are represented using a parallelogram and are used to get
inputs from the users or display the results to them.
3) Generic processing step, also called as activity, is represented using rectangle.
Activities include instructions such as add a to b, save the result.
4) A conditional or decision symbol is represented using a diamond. It is basically used
to depict a yes/no question or a True/False test. The two symbols coming out of it, one
from the bottom point and the other from the right point, corresponds to Yes or True,
and No or False, respectively.
5) Arrows depict the flow of control of the program.
6) Labelled connectors are represented by an identifying label inside a circle and are used
in complex or multisheet diagrams to substitute for arrow. For each label, the ‘outflow’
connector must have one or more ‘inflow’ connectors.
Advantages of flowcharts:
• Flowcharts are very good communications tools to explain the logic of a system to all
concerned. They help to analyse the problem in a more effective manner.
• They are also used for program documentation. They are even more helpful in the case
of complex programs.
• They act as a guide or blueprint for the programmers to code the solution in any
programming language.
• They can be used to debug programs that have error(s). They help the programmers to
easily detect, locate, and remove mistakes in the program in a systematic manner.
Limitations of flowcharts:
• Drawing flowcharts is a laborious and time-consuming activity.
• Often, the flowchart of a complex, program becomes complex.
• At times, alittle bit of alteration in the solution may require complete redrawing of the
flowchart.
• There are no well-defined standards that limit the details that must be incorporated into
a flowchart.
The following flowchart is an example of a sequential execution.
Example
Draw a flowchart to find the simple interest. (Sequence)
Solution
Example
Draw a flow chart to find biggest number among n numbers.
Solution:
Example
Draw a flow chart to print the number from 1 to ∞.
Solution
In the above example “I” value is not at all incremented, so it will create endless loop.
This is also called infinite loop.
Note: Set of statements is executed again and again without any end is called infinite
loop.
ALGORITHM FLOWCHART
1. Step-by-step process 1) Pictorial representation
2. Didn’t use any symbol 2) Use symbol for processes & I/O
Example: Example:
Just like simple statements Just like maps
3. Easy to debug errors 3) Difficult to debug errors
4. Independent 4) Dependent
5. Use to solve problem with multiple 5) Use for improving process & also
solutions. show their relationships
6. No hard & fast rule to create it 6) Have some rule to create it
7. Easy to edit in process for betterment 7) Difficult to edit in process for
betterment.
Examples of Algorithms and Flowcharts:
History of C-Language:
CPL
1963 Cambridge University
( Combined Programming
Language )
BCPL
Martin Richards at
1967 ( Basic Combined Programming
Cambridge University
Language )
1970 B-Language Dennis Ritchie and Ken Thomson
• In 1972 Dennis Ritchie has taken best features of BCPL and B- language, and also
added his features, then developed C-Language compiler.
• In 1973 UNIX server was developed. It provides system calls to interact with
hardware components.
• In 1979 Kernighan & Dennis Ritchie developed UNIX based compiler, named as K
& R compiler In 1987 Borland has taken the rights on DOS based compiler and
released as TURBO-C.
• Microsoft has taken rights from Borland, modified the DOS based compiler to
Windows.
• In 1990 K & R Compiler was recognized by ANSI(American National Standards
Institute) and name as ANSI-C. In the same year ANSI-C was certified by ISO and
called ISO-C.
dependent.
Function-n
(user defined functions)
The sections contained in the ‘C’ structure are:
i. Documentation section:
It consists of a set of comment lines giving the name of the program, the author and
other details which the programmer would like to use later.
Ex:/*Program to find
1. Area of circle
2. Circumference of circle*/
Any block of comment lines must start with ‘/*’ and must ends with ‘*/’
The program execution begins at opening brace and ends as the closing brace. The
closing brace of the main() function section is the logical end of the program. ALL
statements in the declaration and executable parts end with a semicolon.
Ex: main()
{
int a;
a=10;
printf(“%d”,a);
}
vi. sub program section: The sub program section contains all the user defined functions
that are called in the main() function. User-defined functions are generally placed
immediately after the main() function, although they may appear in any order.
Ex:
void print();
void main()
{
print();
}
void print()
{
printf(“This is user-defined function”);
}
Various steps in creating and executing a C program:
Executable
Source file Compiler Object files Linker
Preprocessor file
In case of Turbo C package, the program can be typed using built-in editor. If the
operating system is unix, the program can be typed using Vi text editor.
The translation is done after examining each instruction for its correctness, if
everything is alright the compilation proceeds silently and the translated program is stored an
another file with name filename.obj.
During execution, the program may request for some data to be entered sometimes, the
program does not produce the desired results. Then it is necessary to correct the source
program (or) the data. In case the source program is modified, the entire process of compiling
and executing the program should be repeated.
Identifier :
A name in C program is called identifier. It may be variable name, function name, structure
name, union name etc.
Rule 2: If we are using any other character we will get compile time error.
Example:
1) total_number-------valid
2) Total#------------------invalid
Rule 4: C identifiers are case sensitive and C language itself treated as case sensitive language.
Example:
void main()
{
int number=10;
int Number=20;
int NUMBER=20; we can differentiate with case.
int NuMbEr=30;
}
Identifier Keyword
Identifiers are names that are given to various C take some reserved word called keyword,
program elements, such as variable, function they have predefine meaning in C
and arrays.
Identifiers consist of letters and digits. Keyword consist of only letter
Identifier’s first character must be a letter In all Keyword’s, character is letter
Identifiers Upper and lowercase letter is use. Keywords are all lowercase
Upper and lowercase are not equivalent. Uppercase and lowercase are also not
equivalent
Ex: X, sum_5,etc Ex: auto,short, long etc..
Reserved words:
In C some identifiers are reserved to associate some functionality or meaning such type of
reserved identifiers are called reserved words. There are a total of 32 keywords in C Language
which can not be used for the names of variables and functions.
Reserved words for data types: (4)
1) int
2) float
3) double
4) char
3) static
4) register
Other Keywords:(5)
1. Const
2. typedef
3. enum
4. sizeof
5. volatile
DATA TYPES
A data type defines a set of values and the operations that can be performed on them. Every
data type item (constant,variable etc.,) in a C-program has a data type associated with it. C
supports several different types of data, each of which may be represented differently with in
the computer’s memory.
Data types
struct Arrays
char union pointers
int enum functions
float typedef .
double . .
void . .
.
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. The
data items that operators act upn are called operands.
Some operators require two operands, while others act up on only one operand. The
operators are classified into unary, binary and ternary depending on whether they operate on
one, two, (or) three operands respectively.
1) Arithmetic operators
C provides all the basic arithmetic operators. They are shown in below table. These can
operate on any built-in data type allowed in C.
Arithmetic operators
Operation Operator
Multiply *
Divide /
Addition +
Subtraction -
Modulus %
In the below examples, if a and b are integers, then for a=14 and b=4 we have the
following results:
a-b=10
a+b=14
a*b=56
a/b=3 (decimal part truncated)
a%b=2(remainder of division)
If either operand is of the real type, then only the real operation is performed and the
result is always a real number. Thus 15/10.0=1.5 where 15/10=1
2) Relational operators:
Relational operators are symbols that are used to test the relationship between two
variables(or) between a variable and a constant. We often compare two quantities, and
depending on their relation takes certain decisions. These comparisons can be done
with the help of relational operators. These relationships are illustrated in table.
3) Logical operators:
Logical operators are symbols that are used to combine (or) negate expressions
containing relational operators.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
i. Logical AND:
Logical AND operator is used to simultaneously evaluate two conditions or expressions
with relational operators. If expressions on both the sides (left and right side) of the
logical operator is true then the whole expression is true. The truth table of logical
AND operator is given in Table.
Truth table of Logical AND
A B A &&B
0 0 0
0 1 0
1 0 0
1 1 1
For example, (a<b)&&(b>c)
The expression to the left is (a<b) and that on the right is (b>c). The whole expression
is true only if both expressions are true, i.e, if b is greater than a and c.
5) Assignment operators:
Assignment operators are used to assign the result of an expression to a variable.
The general format of assignment statement is:
Variable_name=expression;
The operator ‘=’ is called assignment operator. The left of assignment operator must be
a variable.
Ex:
F=1.8*C+32.0;
i=10;
a=b+c;
The usual assignment operator, ‘=’, in addition ‘C’ has a set of ‘shorthand’ assignment
operators of the form
V OP = EXP;
Some of the commonly used shorthand assignment operators are shown in below Table.
Statement with simple assignment Statement with shorthand operator
operator
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a%b a%=b
while ++m and m++ mean the same thing when they form statements
independently, they behave differently when they are used in expressions on the right
hand side of an assignment statement. Consider the following:
m=5;
y=++m;
In this case, the value of y and m would be 6. Suppose, if we rewrite the above
statements as
m=5;
y=m++;
then, the value of y would be 5 and m would be 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.
7) Conditional operator:
A ternary operator “?:” 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 nonzer(true),
then the expression exp2 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. Note that only
one of the expressions (either exp2 or exp3) is evaluated.
Bitwise operators
Operator Meaning
~ One’s complement(Bitwise NOT)
>> Right shift
<< Left shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR(Exclusive OR)
9) Special operators
These are used for special purpose in C language these operators are used in pointers,
structures and unions etc. Some types special operators as
i. unary operator
ii. comma operator
iii. sizeof operator
iv. member selection operator
i. unary operator: Those that operators on a single operand. The unary operators are +
+, --, _(underscore), &(address operator), *(indirection operator) , sizeof operator and
so on.
1. Declaring variables:
Any variable used in the program must be declared before using it in any statement. To declare
the variables we must use the following general form.
Example: int a;
float b;
char c;
double d;
In the above example a,b,c and d are the names of the variables whereas int, float, char &
double are predefined data types.
It is possible to declare multiple variables by using the single declaration statement. This can
be shown through the following example.
We can assign a value to a variable by using assignment statement. The expression having
assignment statement is also called assignment expression. In an assignment expression, an
assignment operator is used.
3.Initializing variables:
While declaring the variables, we can also initialize them with some value.
For example:
int emp_num=7;
float salary=5000;
char grade= ‘A’;
The initializer applies only to the variable defined immediately before it. Therefore, the
statement
int count,flag=1;
initializes the variable flag and not count.
CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a program. C
supports several types of constants as shown below.
I. Numeric Constants: Numeric constants are the numeric value that can be represent either
integer or floating value. It is constants are formed by using the digits 0 to 9 + or – sign. And
decimal point. Numeric constants further it can be classified into two types these are
1. Integer constants
2. Floating point constants.
1) Integer constants: These have integer data combination of 0 to 9 without any decimal
point. These have either + or – sign. Integer constants can be represented in 3 different ways.
i. Octal constants
It can be formed by using the digits 0 to 7 only. The octal constant prefixed with zero.
Example: 012,01234...
2) Floating point constant: Some constants floating which have a decimal point with in it
having +ve or -ve sign is called real or float numeric constant. These constant can be
represented two different forms. These are
i. Decimal Form: Real constants expressed in decimal form must have atleast one digit and
one decimal point. As in the case of integers, the real constants can be either positive (or)
Negative. Commas,blanks and non-digit characters are not allowed with in a real constant.
i. Single character constant: These have a single character with in asingle quote
for example: ‘s’, ‘a’ , ‘@’...
There are several header files that provide necessary information in support of the various
library functions. These header files are entered in the program using the #include directive at
the beginning of the program. For example if a program uses any function from, the standard
I/O library, then it should include the header file stdio.h as-
#include<stdio.h>
Similarly there are other header files like string.h, stdlib.h that should be included when certain
library functions are used.
A simple method for taking the data as input is to give the value to the variables by assignment
statement. For example-
int basic=2000;
char ch= ‘y’;
But in this way we can give only particular data to the variables. The second method is to use
the input function scanf(), which takes the input data from the keyboard. In this method we
can give any value to the variables at run time. For output, we use the function printf().
CONVERSION SPECIFICATIONS:
The functions scanf() and printf() make use of conversion specifications to specify the type
and size of data. Each conversion specification must begin with a percent sign(%). Some
conversion specification are as given below-
%c - a single character
%d - a decimal integer
%f - a floating point number
%o - an octal integer
%x - a hexadecimal integer
%s - a string
%u - an unsigned decimal integer
This function should have atleast two parameters. First parameter is a control string, which
contains conversion specification characters. It should be within double quotes. The
conversion specification characters may be one or more; it depends on the number of variables
we want to input. The other parameters are addresses of variables. In the scanf() function
atleast one address should be present.
The address of a variable is found by preceding the variable name by an ampersand (&) sign. A
string variable is not preceded by & signs to get the address.
In this example, it contains only one conversion specification character %d, which implies that
one integer value should be entered as input.
#include<stdio.h>
main()
{
int basic;
float hra;
char grade;
......
scanf(“%d %f %c”, &basic, &hra, &grade);
......
}
Here, it contains three conversion specifications characters %d,%f and %c, means that one
integer value, one floating point value and one single character can be entered as-
1500 200.50 A
Output data can be written from computer memory to the standard output device using printf()
library function. With this function all type of values can be written as output. The printf()
function can be written as-
In this function the control string contains conversion specification characters and text. It
should be enclosed within double quotes. The name of variables should not be preceded by an
ampersand(&) sign.
Here control string has only text and no conversion specification character, hence the output is
only text.
#include<stdio.h>
main()
{
int age;
printf(“Enter your age:”);
scanf(“%d”,&age);
printf(“age=%d”,age);
}
Output:
Enter your age:45
age=45
Here the first printf also does not contain any conversion specification and is used to display a
message that tell the user to enter his age. Scanf will read the data from keyboard and store
into the address of age variable. The second printf has the conversion specification %d which
specifies the integer prints age value on the monitor.
• These macros getchar() and putchar() can be used for character I/O.
• getchar() reads a single character from the standard input.
• putchar() outputs one character at a time to the standard output.
#include<stdio.h>
void main()
{
char ch;
printf(“enter a character:”);
ch=getchar();
printf(“The entered character is:”);
putchar(ch);
}
Output:
Enter a character:B
The entered character is: B
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
The operators of the same precedence are evaluated either from ‘left to right’ or from ‘right to
left’, depending on level. This is known as the associativity property of an operator.
Table provides a complete list of operators, their precedence levels, and their rules of
association. The groups are listed in the order of decreasing precedence. Rank 1 indicates the
highest precedence level and 15 the lowest
RANK OPERATOR DESCRIPTION ASSOCIATIVITY
1 () Function call Left to Right
[] Array subscript
. Dot operator
-> Arrow operator
2 + Unary plus Right to Left
- Unary minus
++ Increment
-- Decrement
! Logical Not
~ One’s complement
* Indirection
& Address
(datatype) Typecast
sizeof Size in bytes
<<=
>>=
15 , Comma operator Left to Right
EXPRESSIONS
An expression is a combination of operators,constants,variables and function calls. The
expression can be arithmetic,logical, or relational.
C Expression Evaluation
• In the C programming language, an expression is evaluated based on the operator
precedence and associativity. When there are multiple operators in an expression, they
are evaluated according to their precedence and associativity. The operator with higher
precedence is evaluated first and the operator with the least precedence is evaluated
last.
• An expression is evaluated based on the precedence and associativity of the operators
in that expression.
• To understand expression evaluation in c, let us consider the following simple example
expression...
10 + 4 * 3 / 2
• In the above expression, there are three operators +, * and /. Among these three
operators, both multiplication and division have the same higher precedence and
addition has lower precedence. So, according to the operator precedence both
multiplication and division are evaluated first and then the addition is evaluated. As
multiplication and division have the same precedence they are evaluated based on the
associativity. Here, the associativity of multiplication and division is left to right. So,
multiplication is performed first, then division and finally addition. So, the above
expression is evaluated in the order of * / and +. It is evaluated as follows...
• 4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
TYPE CONVERSION AND TYPE CASTING
Type conversion of typecasting of variables refers to changing a variable of one data type into
another. Type conversion is done implicitly whereas, typecasting has to be done explicitly by
the programmer.
1. Type conversion: Type conversion is done when the expression has variables of
different data types. To evaluate the expression, the data type is promoted from a lower to a
higher level where the hierarchy of datatypes (from higher to lower) can be given as: double,
float ,long , int short and char. Figure shows the conversion hierarchy of data types.
Higher level
Lower level
For example, if we need to explicitly typecast an integer variable into a floating point variable,
then the code to perform type casting can be given as,
float salary=10000.00;
int sal;
sal=(int) salary;
Operator Meaning
~ One’s complement(Bitwise NOT)
>> Right shift
<< Left shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR(Exclusive OR)
Table 1: Bitwise operators
These operators can operate upon ints and chars but not on floats and doubles.
1) Bitwise complement:
The operator ~ is called the one’s complement operator, or the bitwise complement
operator. It inverts the bit string representation of its argument; the 0’s becomes 1’s,
and the 1’s becomes 0’s.
The expression ~a is the bitwise complement of a, and this expression has the binary
representation 0111110
i) Bitwise AND:
The Bitwise AND operates on two operands. While operating upon these two operands
they are compared on a bit-by-bit basis. The symbol ‘&’ represents the bitwise AND
the rules that decide the value of the resultant bits are shown below:
a b a&b
0 0 0
0 1 0
1 0 0
1 1 1
For Example:
ii) Bitwise OR:
The Bitwise OR operations are similar to the bitwise AND and the results is 1 if any of
the bit value is 1. The symbol ‘1’ represents the bitwise OR.
The rules that decide the value of the resultant bits are shown below:
a b a|b
0 0 0
0 1 1
1 0 1
1 1 1
For example:
a b a^b
0 0 0
0 1 1
1 0 1
1 1 0
For example:
3) Shift operations:
The shift operations take binary patterns and shift the bits to the left or right, keeping
the same number of bits by dropping shifted bits off the end and filling in with zeroes
from the other end. C provides two types of shift operations, left shift and right shift.