Module1 - PCD Engineering Notes
Module1 - PCD Engineering Notes
INTRODUCTION TO C LANGUAGE
1.1 Introduction to C
C is a general purpose programming language developed by Dennis Ritchie at AT& T Bell
laboratories in 1972.
C is closely related to UNIX system and many of the important ideas are taken from “BCPL”(Basic
Combined Programming Language) developed by Martin Richards and “B” language.
C provides variety of data types, derived data types like pointers, arrays, structures and unions.
It also provides control flow constructions like conditional and looping constructs.
1.1.2Advantages/Features of C Language
There are many features which attracted programmers for the usage of C. They are
1. Simple and Portable: it gives programmer access to all functions of the machine and can work on
different kinds of computers.
2. Powerful and Flexible: most of the functionalities like UNIX is written in C. The compiler and
interpreter is also written in C language.
3. Modularity: C is a structured programming language which mainly deals with the procedures. It is
also termed as procedure oriented language.
4. Efficient: C is more efficient which increases the speed of execution and management of memory
compared to low level languages.
5. Programmer oriented: It has many data types and flexible control structure which gives access to
hardware.
6. Other features include
Machine independent
No need to worry about machine details.
1.1.3 Versions of C:
The main is ANSI C(accepted by American National Standards Institute) under which we have
Lattice C
Microsoft C
Quick C
Turbo C
Borland C
Small C
Tiny C etc….
1.3 Algorithm
It is a step by step procedure to solve a problem
A sequential solution of any problem that is written in human language.
Using the algorithm the programmer then writes the actual program.
The main use of algorithm is to help us to translate English into C.
Algorithm consists of combination of statements of English and C, but not exactly C. It can then be
converted to C program.
It is an outline or basic structure or logic of the problem.
Ex 1: Write an algorithm to add two numbers Ex 2: Write an algorithm to compute simple interest
Algorithm: Addition of two numbers Algorithm: To find Simple Interest
Input: Two number a and b Input: p, t, r
Output: Sum of two numbers Output: si
` Step 1: Start Step 1: Start
Step 2: [input two number] Step 2: [input a principle p, time t and
rate r]
Read a and b Read p, t, r
Step 3: [compute its addition] Step 3: [compute simple interest]
Sum = a + b SI (p*t*r)/100
Step 4: print Sum Step 4: display si
Step 5: Stop Step 5: Stop
It is mainly used to help the programmer to understand the logic of the program.
Ex 1.Algorithm and Flowchart to Input the dimensions of a rectangle and print its area
Step 1: Start
Step 2: read length, breadth
Step 3: Compute ‘area’
area=length * breadth
Step 4: display area
Step 5: Stop
Ex 2.Algorithm and Flowchart to Input the dimensions of a rectangle and print area and perimeter
Step1 :start
Step 2: read length, breadth
Step3: area length * breadth
Step 4: Compute ‘perimeter’
Step 5: perimeter
2*(length+breadth)
Step 6: display area, perimeter
Step 7: stop
Step 1: start
Step 2: input a,b,c
Step 3: if a>b
Bigaba
else
bigabb
end if
Step 4: if c>bigab
display c
else
display bigab
end if
Step 5: stop
1.5Structure of C Program
Comments/Documentation Section
Preprocessor Directives
Global declaration section
Comments/Documentation Section
To specify the description so as to make understand the program or statements comments are used.
The comments are not strictly necessary used in a program.
The comment begins with /* and ends with */. The symbols /* and */ are called comment line
delimiters.
We can put any message we want in the comments.
Example: /* Program to compute Quadratic Equation */
Note: Comments are ignored by C compiler, i.e. everything within comment delimiters
Preprocessor Directives
Preprocessor Directives begins with a # symbol
Provides instructions to the compiler to link functions from system library.
A function is a building block of a program where it performs a particular task.
Some examples of header files are
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <math.h>
#include<stdlib.h> Etc…
Subroutine Section: All user defined functions that are called in main function should be defined.
1.7 C- Tokens
Tokens are the smallest individual units of C program.
A token is collection of characters.
1.7.1 Keywords
Words which have fixed meanings are called keywords.
These are basic building blocks of C program statements.
The meaning of keywords will be known to computer no new name or meaning can be defined for it.
There are totally 32 keywords supported in C they are:
Auto double if static
break else int struct
case enum long switch
char extern near typedef
const float register union
continue for return unsigned
default for short void
do goto signed while
1.7.3 Constants
Constants refers to fixed values that do not change during the execution of a program
We have different types of constants
1. Integer constant
2. Real constant/Floating Pointing
3. Character constant Ex: ‘a’, ‘9’, ‘\n’
4. String constant Ex: “INDIA”, “8”
Integer constant:
It refers to sequence of digits
Embedded spaces, commas, characters should not be included.
Must not contain a decimal point.
May be signed or unsigned. (default is +)
Three types of integers
Decimal integers:Consist of digits 0 to 9
Ex: 123 -345 0 5436 +79
Octal integers: Digits from 0 to 7 but it has to start with 0
%i or %d integer number
%c Character
%o octal number
%s String
%lf double
Escape sequence are special character denoted by a backslash (\) and a character after it. It is called escape
sequence because it causes an ‘escape’ from the normal way for characters are interpreted. For example if we
use ‘\ n’, then the character is not treated as n but it is treated as a new line. Some of the common escape
sequence characters are:
Example: int a;
float b;
scanf(“%d%f”,&a,&b);
Guidelines for scanf
No escape sequences or additional blank spaces should be specified in the format specifiers. Ex:
scanf(“%d %f”,&a,&b);//invalid
scanf(“%d\n%f”,&a,&b);//invalid
& symbol is must to read the values, if not the entered value will not be stored in the variable
specified. Ex: scanf(“%d%f”,a,b);//invalid.
Within the main program we declare the required variables for calculating the simple interest. So we
declare p, t and r as int type and si as float type.
After which we have assigned the values to p, t and r.
Computed the simple interest by the formula (p*t*r)/100 and the result is assigned to si.
Display the result si.
Operators:
What is an operator? 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.
What is an operand?
A constant or a variable or a function which returns a value is an operand. An operator may have one or two
or three operands.
Example:a+b-c*d/e%fIn this example there are
6 operands ie a, b, c, d, e, f and 5 operators i.e +,-,*,/ and %.
1.8.1 C operators can be classified into a number of categories based on type of operation
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 basic arithmetic operators. The operators are +, - ,* , / , %.
Let a=10, b=5. Here, a and b are variables and are known as operands.
Subtraction - a-b = 10 – 5 5 2
Multiplication * a* b = 10 * 5 50 1
Modulus(Remiender) % a % b = 10 % 5 0 1
2) Relational Operators
We often compare two quantities depending on their relation, take certain decisions. For example, we
compare the age of two persons, or the price of two items, and so on. These comparisons can be done with
the help of relational operators.
An expression such as
a<b or 1<20
Containing a relational operator is termed as a relational expression. The value of relational expression is
either one or zero. It is one if the specified relation is true and zero if the relation is false.
Example: 10 < 20 is true.
20 < 10 is false.
When arithmetic expressions are used on either side of a relational operator, the arithmetic expressions will
be evaluated first and then the results compared. That is arithmetic operators have a higher priority over
relational operators.
Example: a+b>c+d
In the above example first it will perform addition operation on both sides and after words it will compare the
results.Relational expressions are used in decision statements such as if and while to decide the course of
action of a running program.
3) Logical Operators
In addition to the relational operators, C has the following three logical operators.
Operator Meaning
&& logical AND
|| logical OR
! logical NOT
The logical operators && and | | are used when we want to test more than one condition and make decisions.
An example: a>b && x==10
The above logical expression is true only if a>b is true and x==10 is true. If either (or both) of them are false,
the expression is false.
4) Assignment Operators
Assignment operators are used to assign the result of an expression to a variable. We have seen the usual
assignment operator,‟=‟. 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 library arithmetic operator. The operator op= is
known as the shorthand assignment operator.
Consider an example
x + = y+1;
This is same as the statement
x = x+ (y+1);
We use increment and decrement statements in for and while loops extensively. While ++m and m++ mean
the same thing when they form the statements independently, they behave differently when they are used in
expressions on the right hand side of an assignment statement.
A prefix operand first adds 1 to the operand and then 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.
The operator ?: works as follows: exp1 is evaluated first. If it is nonzero (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 is evaluated.
For example, consider the following statements.
a=10;
b=15;
x = (a>b)? a:b;
In this example, x will be assigned the value of b. This can be achieved using the if… else statements as
follows:
if (a>b)
x=a;
else
x=b;
7) Bitwise Operators
C has a distinction of supporting special operators known as bitwise operators for manipulation of data at bit
level. These operators are used for testing the bits, or shifting them right or left. Bitwise operators may not be
applied to float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
~ Bitwise Negate
8) Special Operators
C supports some special operators of interest such as comma operator, sizeof operator.
The Comma Operator
The comma operator can be used to link the related expressions together. A comma-linked list of expressions
are evaluated from left to right and the value of right-most expression is the value of the combined
expression.
Precedence[Priority]
It is the rule that specifies the order in which certain operations need to be performed in an
expression. For a given expression containing more than two operators, it determines which operations
should be calculated first.
Associativity
If all the operators in an expression have equal priority then the direction or order chosen left to right
or right to left to evaluate an expression is called associativity.
BODMAS Rule can be used to solve the expressions, where B: Brackets O: Operators D: Division
M: Multiplication A: Addition S: Subtraction
The Precedence (Hierarchy) of Operator
Operators in Order of
Operator Category Precedence Associativity
(Highest to Lowest)
Innermost brackets/Array (), [], {} Left to Right(L->R)
elements reference
Unary Operators ++, --, sizeof(), ~, +, - Right to Left(R->L)
Member Access -> or * L->R
Arithmetic Operators *, /, % L->R
Arithmetic Operators -, + L->R
Shift Operators <<, >> L->R
Relational Operators <, <=, >, >= L->R
Equality Operators ==, != L->R
Bitwise AND & L->R
Bitwise XOR ^ L->R
Bitwise OR | L->R
Logical AND && L->R
Logical OR || L->R
Conditional Operator ?: R->L
Assignment Operator =, +=, -=,*=, /=, %= R->L
Comma Operator , L->R
1.9 Expressions
An expression is a sequence of operands and operators that reduces to a single value. Expressions can be
simpler or complex. An operator is a syntactical token that requires an action to be taken .An operand is an
object on which an operation is performed.
We can divide simple expressions into six categories based on the number of operands, relative positions of
the operand and operator
1. Primary Expressions
2. Unary Expressions
3. Binary Expressions
4. Ternary Expressions
5. Assignment Expressions
6. Comma Expressions
1. Primary Expressions
An expression with only one operand but without any operator is called primary expression. The various
types of primary expressions are:
(i) Names Ex: int a
(ii) Constants Ex: 5, 10.5
(iii) Parenthesized expressions Ex: (2+3*(4-2))
2. Unary Expressions
An expression with only one operand and one operator is called unary expression. The unary expression act
on a single operand to produce a value. The various types of unary expressions are
(i) Unary minus expression ex: -5
(ii) Unary plus expression ex: +5
(iii) Prefix expression ex: ++i (iv) Postfix expression ex: i++
3. Binary Expressions
An expression containing two operands and an operator is called binary expression. A binary operator acts on
two operands to produce a value. The various types of binary expressions are
(i) Multiplicative expressions Ex: 2*3 , 6/2
(ii) Additive expressions Ex: a-b, a + b etc
(iii) Relational expressions Ex: a>b, a<b etc
(iv) Logical expressions Ex: a && b, a || b
(v) Bitwise expressions Ex: a &b , a | b
4. Ternary Expressions
An expression containing three operands and two operators is called ternary expression. Here, the two
operators act on three operands.
Ex: a ?b:c // a,b and c are operands and ? and :are operators
5. Assignment Expressions
A statement with assignment operator is called assignment statement. The assignment statements are often
referred to as assignment expressions
Ex 1: a=10
Ex 2: a = b + c
6. Comma Expressions
A set of statements separated by commas are evaluated from left to right one after the other. Such statements
are called statements with comma operator.
Ex: a=10, b=20, c=30;
Examples:
int + int = intint + float = float
5 + 3 = 8 5 + 3.5 = 8.5
For example, we want to find the ratio of girls to boys in the college. The ratio is given by
Ratio = no_of_girls / no_of_boys.
Here, number of girls and number of boys will be of type integer. So, the compiler will not do any
implicit type conversion because, both operands are of the same data type and hence the result will be of type
integer. But, to get the ratio which is a floating point number, we are forced to convert one of the operands to
float so that the result is also float. This is the place where we require explicit type conversion.
Definition: If the Operands are of the same data type, no conversion takes place by the compiler. Sometimes,
the type conversion is required to get the desired results. In such case, the programmer can instruct the
compiler to change the type of the operand from one data type to another data type. This forcible conversion
from one data type to another data type is called explicit type conversion.
1.10.1 Now let us see “What is type casting? Explain with example?”
Definition: C allows programmers to perform typecasting by placing the type name in parentheses and
placing this in front of the value.
For instance
main()
{
float a;
a = (float)5 / 3;
}
Gives result as 1.666666 . This is because the integer 5 is converted to floating point value before division
and the operation between float and integer results in float.
IMPORTANT QUESTIONS
1. What is pseudocode? Explain with an example Dec/Jan 2015 [4M]
2. Explain the structure of C program Dec/Jan 2015 [6M/10M]
3. List out the differences between algorithm and flowchart.
4. Write a C program to find the largest of three given integer values.
5. What are the different types of operators used in C language? Dec/Jan
2015[10M]
6. Explain briefly printf() with format specifiers?
7. Write a C program to find area and perimeterof a rectangle Dec/Jan 2015 [6M]
8. With example, explain scanf() and printf() functions
9. Explain relational operators in C with example
10. Explain different unary operators in C
11. Explain any 3 bit wise operators with an example for each
12. Explain the following operators with example
a. Logical Operators
b. Relational Operators
c. Conditional Operators
13. What is type conversion? Explain types of conversion with example. Dec/Jan 2015 [6M]