Module 1 Backbencher - Club 1
Module 1 Backbencher - Club 1
MODULE 1
INTRODUCTION TO C LANGUAGE
Syllabus
Pseudo code Solution to Problem
Basic Concepts of C Program
Declaration, Assignment & Print Statements
Data Types
Operators and Expressions
Programming Examples and Exercise.
1.1 Introduction to C
C is a general-purpose programming language developed by Dennis Ritchie at AT&T
Bell laboratories in 1972.
Advantages/Features of C Language
C language is very popular language because of the following features:
1. C is structured Programming Language
2. It is considered a high-level language because it allows the programmer to solve a
problem without worrying about machine details.
3. It has wide variety of operators using which a program can be written easily to solve a
given problem.
4. C is more efficient which increases the speed of execution and management of
memory compared to low level languages.
5. C is machine independent. The program written on one machine will work on another
machine.
6. C can be executed on many different hardware platforms.
1.2 Pseudocode: A solution to Problem
Definition:
It is a series of steps to solve a given problem written using a mixture of English and
C language.
It acts as a problem solving tool.
It is the first step in writing a program.
Purpose:
Is to express solution to a given problem using mixture of English language
and c like code.
Advantage:
Easy to write and understand
It is relatively easy to convert English description solution of small programs to C
program.
Ex 1: Addition of two numbers
1. Get the numbers[a,b]
2. Compute addition [Sum= a + b]
3. Print the results [Sum]
Ex 2: Area of Circle
1. Get the radius[r]
2. Compute area[Area = 3.141*r*r]
3. Print the results [Area]
Disadvantage:
It is very difficult to translate the solution of lengthy and complex problem in English to
C
C Programming Concepts
Program: A program is a group of instructions given by the programmer to perform a
specific task.
1.3 Character set of C language
Definition: A symbol that is used while writing a program is called a character.
A character can be: .
Alphabets/Letters (Lowercase a-z, Uppercase A-Z)
Digits (0-9)
Special Symbols ( ~ ‘ ! @ # % & * () - + / $ = \ {
} [ ] : ; “ “ ? etc)
~ | [
Tilde Vertical bar Left bracket
^ + Plus sign ;
Caret Semicolon
Assignment
‘ Single quote . dot =
Division
, comma \ backslash /
1.4 C Tokens
Tokens are the smallest or basic units of C program.
One or more characters are grouped in sequence to form meaningful words.these
meaningful words are called as tokens.
A token is collection of characters.
Tokens are classified in to 5 types as below:
1.4.1 Keywords
The tokens which have predefined meaning in C language are called keywords.
They are reserved for specific purpose in C language they are called as Reserved
Words.
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 volatile short void
do goto signed while
2. No extra symbols are allowed other than letters ,digits and Underscore
3. Keywords cannot be used as an identifier
4. The length can be 31 characters for external, 63 for internal.
5. Identifiers are case sensitive.
Example: Area, Sum_
Ex:-
Identifier Reasons for invalidity
india06 Valid
_india Valid
india_06 Valid
india_06_king Valid
__india valid
06india not valid as it starts from digits
int not valid since int is a keyword
india 06 not valid since there is space between india and
06
india@06 not valid since @ is not allowed
1.4.3 Constants
Definition:
Constants refers to fixed values that do not change during the execution of a program
The different types of constants are:
1. Integer constant
2. Real constant/Floating Pointing constant
3. Enumeration constant
4. Character constant
5. String constant
1. Integer constant
Definition: An integer is whole number without any decimal point.no extra characters
are allowed other than + or _ .
Prof.Chandrika C N, Prof.nagashree C, Department of CSE, SVIT
Page 5
Programming in C and Data Structures Module 1
enum Boolean{NO,YES};
NO is assigned with 0
YES is assigned with value 1
enum days{ mon,tue.wed};
mon is assigned with 0
tue is assigned with 1
wed is assigned with 2
4.Character constant
A symbol enclosed within pair of single quotes is called character constant.
Each character is associated with unique value called ASCII value.
Ex: ‘9’
‘$’
Backslash constants(Escape sequence character)
Definition: An escape sequence character begins with backslash and is followed
by one character.
A backslash along with a character give rise to special print effects.
It always start with backslash ,hence they are called as backslash constants.
character name Meaning
\\ Backslash Backslash
\0 NULL
5.String constant
A sequence of characters enclosed within pair of double quotes is called string constant.
The string always ends with a NULL character.
Ex: “9”
“SVIT”
o long int
n-bit Type size Range of unsigned Range of signed int
machine int be -2n to +2n -1
0 to 2n-1
16- bit short int 2 bytes 0 to 216-1 -215 to +215 -1
machine 0 to 65535 -32768 to +32767
From the examples we will come to know that “a” is a variable of type integer and
allocates 2 bytes of memory. “x” and “y” are two variable of type float which will be
allocated 4 bytes of memory for each variable. “sum” is a double type variables
which will be allocated with 8 bytes of memory for each.
1.5 Variable Initialization
Variables are not initialized when they are declared and defined, they contain garbage
values(meaningless values)
The method of giving initial values for variables before they are processed is called
variable initialization.
General Syntax:
Var_name = expr;
Where,
Var_name is the name of the variable ,
expr is the value of the expression.
The “expr” on the right hand side is evaluated and stored in the variable name
(Var_name) on left hand side.
The expression on the right hand side may be a constant, variable or a larger formula
built from simple expressions by arithmetic operators.
Examples:
int a=10;
// assigns the value 10 to the integer variable a
float x;
x=20;
// creates a variable y of float type and assigns value 20 to it.
int a=10,b,b=a;
// creates two variables a and b. “a” is assigned with value 10, the value of “a” is
assigned to variable “b”. Now the value of b will be 10.
price = cost*3;
//assigns the product of cost and 3 to price.
Square = num*num;
// assigns the product of num with num to square.
%c Character
%o octal number
%s String
%lf double
A Simple C Program
Example 1:Let us discuss a simple program to print the Hello SVIT
/*program to print Hello svit*/
#include<stdio.h>
void main( )
{
printf(“ Hello SVIT”);
}
Output: Hello SVIT
Within the main program we declare the required variables for calculating the
simple interest. So we declare p, t and r as float type and si as float type.
After which the values to p, t and r are read from keyboard using scanf.
Computed the simple interest by the formula (p*t*r)/100 and the result is assigned
to si.
Display the result si.
Comments/Documentation Section
Preprocessor Directives
Global declaration section
void main( ) [Program Header]
{
Local Declaration part
Execution part
Statement 1
------------
------------
Statement n
}
User defined Functions
Comments/Documentation Section
Comments are short explaining the purpose of the program or a statement.
They are non executable statements which are ignored by the compiler.
Subroutine Section: All user defined functions that are called in main function should be
defined.
1.9 Algorithm
It is a step by step procedure to solve a problem
A sequential solution of any problem that is written in natural 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.
It is an outline or basic structure or logic of the problem.
1.9.1 Characteristics of Algorithm
Each and every instruction must be precise and unambiguous
Each instruction execution time should be finite.
There should be a termination condition.
It has to accept 0 or more inputs and produce compulsory an output.
It can accept any type of input and produce a corresponding output.
1.9.2 General Way of Writing the Algorithm
Name of the algorithm must be specified.
Beginning of algorithm must be specified as Start
Input and output description may be included
Step number has to be included for identification
Each step may have explanatory note provided with in square bracket followed by
operation.
Completion of algorithm must be specified as end or Stop.
rhombus is used
Ex 1.Algorithm and Flowchart to Input the dimensions of a rectangle and print its area
Step 1: Start
Step 2: [input the values of length
and breadth]
read length, breadth
Step 3: [Compute ‘area’]
area=length * breadth
Step 4: display area
Step 5: Stop
1.11.1 Operators:
“An operator is a symbol that specifies the operation to be performed on various types
of operands”. Or in other words “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 variable.
Example: +, - ,*
1.11.2 Operand:
The entity on which a operator operates is called an operand. Here the entity may be a
constant or a variable or a function.
An operator may have one or two or three operands.
Example: a+b-c*d/e%f
In this example there are 6 operands ie a, b, c, d, e, f and 5 operators i.e +,-,*,/ and %.
1.11.3 Expression:
A combination of operands and operators that reduces to a single value is called an
expression.
Eg:a+b/d
Classification of operators
1) Unary Operators
2) Binary Operators
3) Ternary Operators
4) Special Operators
1. Unary Operators: An operator which acts on only one operand to produce the result is
called unary operator. The Operators precede the operand.
Examples: -10
-a
--b
2. Binary Operators: An operator which acts on two operands to produce the result is
called a binary operator. In an expression involving a binary operator, the operator is in
between two operands.
Examples: a + b a*b
3. Ternary Operator: An operator which acts on three operands to produce a result is
called a ternary operator.
Ternary operator is also called conditional operator.
Example: a ?b : c
Since there are three operands a, b and c (hence the name ternary) that are associated
with operators ?and : it is called ternary operator.
1.12.2 C operators can be classified 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 that are used to perform arithmetic operation such as addition,
subtraction, multiplication, division etc are called arithmetic operators.
The operators are +, - ,* , / , %.
Let a=10, b=5. Here, a and b are variables and are known as operands.
Multiplication * a* b = 10 * 5 50 1 L-R
Modulus(Remainder) % a % b = 10 % 5 0 1 L-R
a÷b a/b
S=a+b+c S=(a+b+c)/2
2
Area=√s(s-a)(s-b)(s-c) Area=sqrt(s*(s-a)*(s-b)*(s-c))
ax2+bx+c a*x*x+b*x+c
e|a| exp(abs(a))
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.
The operators that are used to find the relationship between two operands are called as
relational expression.
An expression such as
a<b or 1<20
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.
3) Logical Operators
The operator that are used to combine two or more relational expression is
called logical operators.
Result of logical operators is always true or false.
Logical Operators in C are.
Operator Meaning Precedence Associativity
|| logical OR 3 L->R
Example:
36 && 0
=1 && 0
=0(False)
3.2 logical OR (||)
The output of logical operation is false if and only if both the operands are
evaluated to false.
Example:
36 || 0
=1 || 0
=0(True)
operand ! operand
True (1) False(0)
Example:
(a) !0=1 (b) !36
!1=0
NOTE: 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
An operator which is used to assign the data or result of an expression into a variable
is called Assignment operators. The usual assignment operator is =.
Types of Assignment Statements:
1.Simple assignment statement
2.Short Hand assignment statement
3.Multiple assignment statement
1.Simple assignment statement
Syntax: Variable=expression;
Ex:
a= 10; //RHS is constant
a=b; // RHS is variable.
a=b+c; //RHS is an expression
So,
1.A expression can be a constant,variable or expression.
2.The symbol = is assignment operator
3.The expression on right side of assignment is evaluated and the result is converted into type
of variable on left hand side of Assignment operator.
4.The converted data is copied into variable which is present on left hand side(LHS) of
assignment operator.
Example:
int a;
a=100; // the value 100 is assigned to variable a
int a=100;
int b;
b=a; // a value i.e 100 is assigned to b
2.Short Hand assignment Statement
C has a set of “shorthand‟ assignment operators of the form.
var op = exp;
where
Example:
Solve the equation x*=y+z when x=10,y=5 and z=3
Solution: x*=y+z can be written as
x=x*(y+z)
x =10*(5+3)
x=10*8
x=80
j=10;
k=10;
can be written as:
i=j=k=10; //Multiple assignment statement
Note:Assignment operator is right associative operator. Hence in the above statement 10 is
assigned to k first,the k is assigned to j and j is assigned to i.
Eg2:
#include<stdio.h> Output : a= 21
void main( ) b=20
{
int a=20,b;
b=a++;
printf(“a=%d”,a);
printf(“b=%d”,b);
}
Post Decrement:
Eg 1:
#include<stdio.h> Output:19
void main() Description: Initial value of a is 20 after
{ int a=20; execution of a--, the value of a will be 19.
a--;
printf(“%d”,a);
}
Pre Decrement:
Eg 1:
#include<stdio.h> Output:19
void main() Description: Initial value of a is 20 after
{ int a=20; execution of --a, the value of a will be 19.
--a;
printf(“%d”,a);
}
Consider the following(let a=20)
Post increment
b=a++ current value of a used, b=a //b=20
a is incremented by 1 a=a+1 //a=21
Pre increment
b=++a a is incremented by 1, a=a+1 //a=21
incremented value of a used, b=a //b=21
The operator which operates on 3 operands are called Ternary operator or conditional
operator.
Syntax: (exp1)? exp2: exp3
where exp1,exp2, and exp3 are expressions and
exp1 is an expression evaluated to true or false
if exp1 is evaluated to true exp2 is executed
if exp1 is evaluated false exp3 is executed
7) Bitwise Operators
Bitwise operators are used to manipulate the bits of given data. These operators are used for
testing the bits, or shifting them right or left. Bitwise operators may not be applied to float or
double.
0 & 0 0
0 & 1 0
1 & 0 0
1 & 1 1
a=10 00001010
b=6 00000110 (a&b)
c=2 00000010
2)Bitwise OR(|)
If the corresponding bit positions in both the operand are 0,then OR operation results
in 0 ;otherwise 1.
operand 1 OR operand 2 result
0 | 0 0
0 | 1 1
1 | 0 1
1 | 1 1
a=10 00001010
b=6 00000110 (a|b)
c=2 00001110
3)Bitwise XOR(^)
If the corresponding bit positions in both the operand are different,then XOR operation
results in 1 ;otherwise the result is 0.
0 ^ 0 0
0 ^ 1 1
1 ^ 0 1
1 ^ 1 0
a=10 00001010
b=6 00000110 (a^b)
c=12 00001100
First operand
{ int a,b;
a=5;
b=a<<1;
printf(“ %d<<1=%d”,a,b);
}
5)Right shift operator(>>)
The operator that is used to shift the data by a specified number of bit positions towards
right is called right shift operator.
After right shift operation, LSB bit should be discarded and MSB is empty and should be
filled with 0.
b=a>>num Second operand
First operand
The first operand is the value to be shifted.
The second operand specifies the number of bits to be shifted.
The content of first operand are shifted towards right by the number bit positions
specified in second operand.
Example:
#include<stdio.h> OUTPUT: 10>>1=5
void main()
{ int a,b;
a=10;
b=a>>1;
printf(“ %d>>1=%d”,a,b);
}
6)Bitwise negate:
The operator that is used to change every bit from 0 to 1 and 1 to 0 in the specified operand is
called bitwise negate operator. It is used to find one’s compliment of an operand.
Example:
#include<stdio.h>
void main()
{
int a=10,b;
b=~a;
printf(“Negation of a is %d”,b);
}
Tracing:
a=10 00001010
b=245 11110101
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. The comma operator has
least precedence among all operator.
It is a binary operator which is used to:
1.Sepaerate items in the list.
Eg: a=12,35,678;
2.Combine two or more statements into a single statement.
Eg: int a=10;
int b=20;
int c=30;
can be combined using comma operator as follows:
int a=10,b=20,c=30;
Examples:
1. sizeof(char); Output:1 Byte
2 int a; Output:2 Byte
sizeof(a)
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.
Associativity
Right associativity:
In an expression if two or more operators having same priority are evaluated from left
to right then the operators are called right to left associative operator, denoted as R->L
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. Integer Expressions
If all the operands in an expression are integers then the expression is called Integer
Expression.
The result of integer expression is always integer.
Ex: 4/2=2
2. Flaoting Point Expressions
Prof.Chandrika C N, Prof.nagashree C, Department of CSE, SVIT
Page 37
Programming in C and Data Structures Module 1
If all the operands in an expression are float numbers then the expression is called
floating point Expression.
The result of floating point expression is always float
Ex: 4.0/3.0=1.3333
3. Mixed Mode Expressions
An expression that has operands of different types is called Mixed Mode Expression.
Ex: 4.0/2 i.e float/int
This process of converting data from lower rank to higher rank is called as Implicit
type conversion(ITC).
For example,
If one operand type is same as other operand type, no conversion takes place and type
of result remains same as the operands
i.e int + int = int, float + float = float etc.
If one operand type is int and other operand type is float, the operand with type int is
promoted to float.
Promotion of hierarchy is as follows:
Higher rank datatype
double
float
unsigned long int
long int
unsigned int
int
Short int
char
Lower rank datatype
Examples:
i. 5+3=8
int + int = int
ii. 5 + 3.5 = 8.5
int + float = float
(type) expression
Prof.Chandrika C N, Prof.nagashree C, Department of CSE, SVIT
Page 39
Programming in C and Data Structures Module 1
Syntax:
ITC ETC
Question Bank
Module 1
Sl.No Questions Appeared in CO BT
VTU qp mappin Level
month/year g Attained
1. Define pseudocode .Write a pseudocode to find the sum June/July CO1 BT1
and average of three numbers. 2016
Dec/Jan
2015
21 Explain 5 types of data with its range and values(04 Jan 2013
marks) – CO1 BT1
22 Explain scanf( ) and printf( ) functions with syntax. Jan 2013
(06 marks) CO1 BT1
23 What do you mean by type conversion? Explain explicit Jan 2013
type conversion with examples(04 marks) CO1 BT1
26 What are c tokens? Mention then? and explain any two Dec 2011
tokens(08 marks) CO1 BT1
27 What is a datatype? explain the basic data types available Dec 2011
in c (04 marks) CO1 BT1
28 What are variables how they are declared(04 marks) Dec 2011
CO1 BT1
29 Write a program to find area of triangle given three Dec 2011
sides(06 marks) CO1 BT1
operators
41 What are escape sequences? why they are used? give -June/July
examples(04 marks) 08 CO1 BT1