Module 1
Module 1
Unit 1 : Introduction to C
Syllabus Unit 1
Introduction to C
• Basic Organization of a Computer, Types of Programming Languages,
Program Design Tools, Introduction to C, Structure of C program,
Writing the first C Program, Compiling and Executing C Programs, C
Tokens, Basic Data Types in C, Operators in C, Evaluating
Expressions, Type Conversion and Typecasting, Example Programs.
Installation of code blocks
https://www.codeblocks.org/downloads/
Basic Organization of a Computer - CLASSIFICATION OF COMPUTERS
Computers can be broadly classified into four categories based on their speed, amount of data that
they can hold, and price.
Classification of Computers
Dumb Intelligent
Terminal Terminal
A computer is an electronic device which basically performs five major operations which includes:
1) accepts data or instructions (input)
2) stores data
3) process data
4) displays results (output) and
5) controls and co-ordinates all operations inside a computer
• Input: This is the process of entering data and instructions into the computer. Different input
devices such as mouse, keyboard, scanner and trackball can be used to enter the instructions. It is
the responsibility of the input device to convert the input data into binary code.
• Storage: This is the process of saving data and instructions permanently in the computer such that
it can be used for processing. There are 2 types of storage areas
1. Primary storage (Main memory): This area stores data, intermediate results and recently generated results that
are currently being worked on.
➢ The storage area that is directly accessible by the CPU at very high speed.
➢ It is very expensive, limited capacity and volatile.
➢ Eg : Random Access memory
2. Secondary Storage (Auxiliary Memory): this area stores the data that is not accessed frequently (as compared
to the data in primary storage.
➢ It is a non-volatile memory medium that preserves data until and unless it has been deleted or overwritten.
➢ It supplements the limited storage capacity of primary memory
➢ Eg : CD , Hard disk drives, Magnetic disk
Difference between primary and secondary memory
Known as main memory or internal memory Known as auxiliary memory or External memory
Eg : RAM, ROM , Cache, EPROM Eg: HDD , CD, DVD ,Flash drives
CPU directly accesses data CPU does not directly accesses data
Power cut causes loss of data Power cut does not cause loss of data
Processing : The process of performing operations on the data as per instructions specified by the
user is called processing. Data and instructions is taken from the primary memory and transferred to
ALU for calculations. The intermediate results is stored in the main memory. When processing is
complete the final result is transferred to main memory.
Types of Programming Language
A programming Language is a language used by a user to instruct a computer to
perform certain computations.
Each programming language has its own vocabulary of syntax and semantics for
instructing a computer.
Types of programming language : C,C++,COBOL,FOTRAN,Pascal,Python,Java etc
Types of Programming Language
Programming Language can be divided into 3 types :
1. Machine level language - is a language that consists of a set of instructions that
are in the binary form 0 or 1
2. Assembly level language - is a type of low-level programming language which
consists of binary and hexadecimal characters with some English like
commands. Assembly languages are designed to be readable by humans.
3. High level Language - language that is designed to be easily understood by
humans. It uses syntax that is similar to human language to form instructions.
Program Design Tools
• Algorithms
➢ Step by step description on how to arrive at a solution.
➢It provides a blueprint of the solution
➢It should be precise , Unambiguous , Once the algorithm terminates the desired result must
be obtained.
• Flowcharts
➢ Graphical or symbolic representation of a process.
➢Helps user to visualize the logic of the process which helps them to understand the process
better , find flaws , bottlenecks.
• Pseudocodes
➢ Compact and informal high level description of an algorithm
➢Helps user to focus on the logic of the algorithm without worrying about the details of
language syntax.
➢An ideal pseudocode must be complete , descriptive such that it can be translated to a
programming language straightaway.
Algorithm
What is an Algorithm?
Step 1: Start
Step 2: Print “Hello World”
Step 3: Stop
Write algorithm to calculate the sum
and average of two numbers.
◼ Step1 : Start
◼ Step2: Declare two variables n,m,sum,avg
◼ Step3 : Read two numbers n,m
◼ Step4 : Calculate sum=n+m
◼ Step5 : Calculate avg=sum/2
◼ Step6 : Print sum,avg
◼ Step7 : Stop
Write algorithm to calculate simple interest.
Step 1: Start
Step 2: Read Principal Amount, Rate and Time
Step 3: Calculate Interest using formula SI=
((amount*rate*time)/100)
Step 4: Print Simple Interest
Step 5: Stop
INTRODUCTION TO
FLOWCHARTS
FLOWCHARTS
• The first flowchart was created by Von Neumann in 1945.
• Flowchart are the graphical representation of a solution to a
particular problem, which comes under the category of programming
practices and techniques.
• In simple words flowchart is a graphical representation of a program.
• Flowchart are symbolic diagram which shows type of data(numeric ,
character), data flow, control flow, and programming logics and
alogorithms.
Introduction to C
Characteristics of C
Robust language which consists of a number of built- in
function & operators which can be used to write complex
programs
Easy to learn
Used in development of Software (both application/system)
C programs are efficient and fast
Highly portable- works on different OS
Structured programming
BASIC STRUCTURE / FUNCTIONAL UNITS OF COMPUTER
4 steps of C program
1. The Preprocessor
❖ Preprocessor reads the source code and prepares it for translator.
❖ The preprocessor scans for preprocessor commands and makes substitution in special
library codes.
2. The Translator
❖ The translates preprocessed code and results a object module is the code in
machine language.
❖ Translator is the one which does the actual conversion of program into machine
language.
LINKING & LOADING PROGRAMS
The linker assembles input/output processes and
mathematical library functions and the various
files together
To execute a program, we use an operating
system command such as run, to load the program
into primary memory (loader) and execute it.
Basic Structure of C program
Sample C programs
auto , double , int, struct , break, else, long , switch, case, char, do , while , if,
goto , const , continue , default , float , for , short , return
Identifiers (Variables)
Identifiers are user-defined names
Names of variables, functions and arrays as declared by user
Rules for identifiers
1. First character must be an alphabet or underscore
2. Remaining characters can be letters, digit or underscore
3. Must not contain white space or any special charcters
4. Keywords cannot be used as identifiers
5. There cannot be two successive underscores
Let’s Test !!!
1…2…3…
Identify valid and invalid Identifiers!!!
Sl example Sl No Example
No
1 a 8 $Sum
2 Student_name 9 _sum
3 Num1 10 Student name
4 Sum-salary 11 char
5 2names 12 int
6 HRA 13 23_student
7 DeptCode 14 @name
Answers!!!
Sl No Example Sl No Example
1 a 8 $Sum
2 Student_name 9 _sum
3 Num1 10 Student name
4 Sum-salary 11 char
5 2names 12 int
6 HRA 13 23_student
7 DeptCode 14 @name
Differences between Keyword and Identifier
Keywords Identifiers
These are instruction given to the These are not instruction to compiler
compiler
VOID DOUBLE
INTEGER
PRECISION
FLOATING
CHARACTER FLOATING POINT
POINT
A little bit about ‘BIT’
8 bits = 1Byte
int a= 5 ;
1. void data type
void type has no value
Keyword : void
Used mainly to specify the type of function – when a function is declared void
it does not return any value to the calling function
2. Character Type
Keyword: char
Defines single character – Uses upto 8 bits(1 byte) of internal storage
Signed or unsigned qualifier is used to vary the range
Format specifier ‘ %c ‘
Range : -128 to 127
0 0 1 0 0 0 1 1
ASCII Value of # is 35
Code to demonstrate unsigned char
#include<stdio.h>
int main()
{
return 0;
}
#include<stdio.h>
void main()
Output : A
{
a
char ch1=‘A’;
65
char ch2=‘a’
97
printf(“%c”,ch1);
printf(“%c”,ch2);
printf(“%i”,ch1);
printf(“%i”,ch2);
}
S Sign bit : 0
0 0011 . 00100….
E Exponent : 0011
F : Fraction :
Shift the decimal to the right of the MSB ‘1’
0.14 * 2 = 0.28 = 0
0 001. 100100…
0.28 * 2 = 0.56 = 0
Since we made only 1 position shift we need
0.56 * 2 = 1.12 = 1
to add 1 to the bias ie 127. 127 + 1= 128
0.12 * 2 = 0.24 = 0
0.24 * 2 = 0.48 = 0
Therefore the exponent value now is binary
…..
equivalent of 128 : 1000 0000
….. Therefore the Fraction part is 00100
Output :
Greeting message : Hello
Fill in the blanks
1. ____ num=9;
2. ____ amt=123.90;
3. _____ code=‘A’;
4. _____ pi=3.141519265367;
5. ______ A= 509875;
6. ______ msg[ ] =“Hi”;
7. ______ int a = 5678945679;
Constants
Constants are data values that cannot be changed during the execution of a
program.
C supports following types of constants
• Integer constants
• Character constants
• Boolean constants
• Floating point constant
• String constants
Syntax 1 : #define identifier value
Output
#include<stdio.h> area = 50
#define LENGTH 10
#define WIDTH 5
void main()
{
int area;
area=LENGTH * WIDTH;
printf(“area = %d”, area);
}
Syntax 2 : const type variable = value
Output
#include<stdio.h> area = 50
void main()
{
const int LENGTH = 10;
const int WIDTH = 5;
int area;
area=LENGTH * WIDTH;
printf(“area = %d”, area);
}
Write a c program to find area of circle
/*program to find area of circle */
#include<stdio.h>
#define PI 3.14
void main()
{
int radius ,area;
printf(“enter radius “);
scanf(“%d”,&radius);
area = PI* radius*radius;
printf(“ area = %d”, area);
}
Declaration Of data types
When we declare a variable it does 2 things
1. Tell compiler what the variable name is
2. It specifies what type of data the variable will hold
Hence declaration of variables must be done before they are used in the program
Syntax
Data_Type varlist semicolon
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int a= 10 , b=5 , sum; int a, b, sum;
sum=a+b; a=10;
printf(“sum= %d”,sum); b=5;
} sum = a+b;
printf(“sum=%d”,sum);
Output: }
sum = 15
Output:
sum=15
Let’s Ponder
int a=b=c=5; radius=5;
_____________________________ 3.14*radius*radius= area;
float x, y, z;
printf(“area=%d”,area);
x=y=z=PI ;
____________________________
______________________________
float fr , centi; 3=b=4=a;
printf(“enter farenheit “);
scanf(“%f”,&fr); ____________________________
cent = 5.0/9.0*(fr-32); count=count+1;
printf(“centigrade = %f”,cent); _____________________________
main()
________________________________
slope= (y2-y1)÷(x2-x1); {
int e,d=50,c=100;
e=c;
c=d;
d=e;
printf(“e=%d,c=%d,d=%d”,e,c,d);
}
________________________
Input and Output Operations
printf()
Operands
➢ Operand is a variable or constant which returns an value.
➢ Example: a + b
Here ‘a’ and ‘b’ are operands. + is operator.
Expression
A sequence of operands and operators that reduces to single value is an
expression.
Classification of Operators
Unary operators: Uses only one operand. Ex: unary plus(+a), unary minus
(-b), increment operator(a++,++a) , decrement operator(--a, a--)
int a=10;
int b=-(a); (i.e b=-10)
Increment & Decrement Operator
int a=2,b=10,c=0,p,q,r;
p= a++ + b-- + ++c p=? a=? b=? c=? p= 13, a=3, b=9 ,c=1
q= --a + b++ + ++c q=? a=? b=? c=? p=13 a=3 , b=10,c=2
r = a-- + --b + c++ r=? a=? b=? c=? p=14, a=4, b=9, c=3
What is the output??
#include<stdio.h>
int main()
{ 1)3
2) Compile time error
int x, y; 3) 2
x = 5; 4)None of these
y = x++ / 2;
printf("%d", y);
return 0;
}
What is the output??
#include<stdio.h>
int main() 1) Compile time error
{ 2) 29
3) 28
int a=3, b=9; 4) None of these
printf("%d ", ++(a*b+1));
return 0;
}
Work it out!!
#include<stdio.h>
int main()
{ a) a = 1, b = 1
b) a = 2, b = 1
int a = 1, b = 1, c; c) a = 1, b = 2
c = a++ + b; d) a = 2, b = 2
printf("%d, %d", a, b);
}
#include<stdio.h>
int main()
{
a) 6
int i = 2;
b) 5
int j = ++i + i; c) 4
printf("%d\n", j); d) Compile time error
}
2. Based on type of operation
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and Decrement operators
Conditional operator
Bitwise operators
Special operators
Arithmetic operators
Arithmetic operations
Integer Arithmetic
Real Arithmetic
Mixed mode Arithmetic
Integer Arithmetic
When the both the operands are integer type in a single arithmetic
expression its called integer expression and the operation called
integer arithmetic
Example:
int a=10, b=4;
a+b=14
a-b=6
a*b=40
a/b=2 (10/4=2.5 - decimal part truncated)
a%b=2 (remainder of division)
Write a C Program , taking two integer values as 10 and 2,
demonstrate the integer arithmetic operations by
Printing the following on the monitor
10+2=12
10-2=8
10*2=20
10/2=5
10 % 2 =0
#include<stdio.h> OUTPUT
void main() 10 + 2= 12
{ 10-2=8
int c,d,e,f,g; 10*2=20
int a=10,b=2; 10/2=5
c = a+b; 10 % 2=0
d=a-b;
e=a*b;
f=a/b;
g=a%b;
printf("%d + %d= %d \n",a,b,c);
printf("%d-%d=%d\n", a, b,d);
printf("%d*%d=%d\n", a, b,e);
printf("%d/%d=%d\n", a,b,f);
printf("%d %% %d=%d\n", a,b,g);
}
Write a C program to use integer
arithmetic to convert a given number of
days into months and days
/* Program to show integer arithmetic */
#include<stdio.h>
void main()
Output
{
Enter the number of days:265
int days,month,rem_day;
Months = 8
printf(“Enter the number of days :");
Days = 25
scanf("%d",&days);
month = days / 30;
rem_day= days % 30;
printf(“Months = %d \n Days = %d", month,
rem_day);
}
Real Arithmetic
An arithmetic expression involving only real operands is called real
arithmetic.
Example:-
float x, y, z;
x= 6.0 / 7.0= 0.857143
y= 1.0 / 3.0= 0.333333
z= - 2.0 / 3.0= -0.666667
The operator % cannot be used with real operands
Mixed Mode Arithmetic
When one of the operand is real and the other is integer, the expression is
called mixed mode expression.
Example:-
int a=15;
float b=10.0;
a/b=15/10.0=1.5 (if result is float variable)
== Equal to Grade==100
0 1 0 1
1 0 0 1
1 1 1 1
int j=0 , m=1 , n=-1;
float x=2.5, y=0.0;
Expression Result
j && m 0
(j<m)&&(n<m) 1
(m+n)||(!j) 1
((j<=10)&&(x>=1))&&m 1
((x*y)<(j+m)) || m 1
#include<stdio.h> Output
void main() d=0
{ d=1
int a=10,b=11,c=12,d;
d=(a<b)&&(c<b);
printf(" d = %d",d);
d= (a<b)||(c<b); Operator Priority
printf("\n d = %d",d); ! 1
} && 2
|| 3
Assignment operators(Shorthand)
Used to assign the result of an expression to a variable.
v op=exp; v=v op exp
v: variable
exp : expression
op : arithmetic operator
a= a+b can be written as a+ = b
a=a*b can be written as a *= b
a=a/b can be written as a /= b
a=a-b can be written as a -= b
a=a/(n+1) can be written as a/=n+1
a=a%b can be written as a % =b
Program to demonstrate assignment operators
#include<stdio.h>
void main()
{
Output
int a=5,b;
b= 5
b=a;
b=10
printf("\n b= %d",b);
b=5
b+=a;
b=25
printf("\n b=%d",b);
b=5
b-=a;
printf("\n b=%d",b);
b*=a;
printf("\n b=%d",b);
b/=a;
printf("\n b=%d",b);
}
Conditional Operator
Also called Ternary operator.
? : conditional operator
Expression is relational expression
Value 1 is assigned when expression is True
Value 2 is assigned when expression is False
c= a>b ? a:b;
Output
#include<stdio.h>
c=5
void main()
{
int a=5 ,b=4,c;
c=a>b?a:b;
printf("c=%d",c);
}
Write C program to find largest of 3
numbers using ternary operators
#include<stdio.h> Output
void main() enter the values of 3 numbers6
{ 45
int a,b,c; 6
21
Left shift operator (<<)
Shifts all bits towards left by a certain number of specified bits
12 << 2
0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 (Binary 12)
0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 (Binary 48)
12 << 2 = 48
The bitwise complement of 35 is -36 instead of 220 !!! The reason for this is the
system uses two’s complement when performing complement operation
One’s complement : inverts all the bits
Two’s complement: one’s complement +1
For any integer n bitwise complement of n is –(n+1)
35 : 00100011 (binary) 11011100 (one’s complement) : 210
210 : 11011100 -(00100011(one’s complement) + 1) 00100100= -36
Therefore ~n = -(n+1)
~(-n)=-(-n+1) a=-10 b=~a -(-10+1)=9
Program to demonstrate bitwise operation
#include<stdio.h>
void main()
{
int a=60 ,b=13;
OUTPUT:
int c;
bitwise and : c= 12
c=a&b;
bitwise or : c=61
printf("\n bitwise and : c= %d",c);
bitwise complement : c=-61
c=a|b;
bitwise xor : c=49
printf("\n bitwise or : c=%d",c);
left shift : c=240
c=~a;
right shift : c=15
printf("\n bitwise complement : c=%d",c);
c=a ^ b;
printf("\n bitwise xor : c=%d",c);
c=a<<2;
printf("\n left shift : c=%d",c);
c=a>>2;
printf("\n right shift : c=%d",c);
}
Special Operator
1. Comma Operator
2. sizeof() Operator
3. Address Operator
4. Dot Operator
+- Least Priority
Example : x= 9-12/3+3*2-1
Step1: 12/3 = 4 ; 3*2=6 ; 9- 4+6-1
Step 2:9-4 ; 5+6-1
Step 3: 5+6; 11-1
Step 4: 10
Expression with Parentheses
Evaluate the expression 9-12/(3+3)*(2-1)
9-12/(3+3)*(2-1)
Step 1: 9-12/6*1
Step 2:9-2*1
Step 3: 9-2
Step 4: 7
Evaluate : 17-8/4*2+3- ++a assuming a=5
17-8/4*2+3- ++a
17-8/4*2+3 – 6
17-2*2+3-6
17-4+3-6
13+3-6
16-6
10
Solve:a+2 > b && !c||a !=d&&a-2<=e
There will be instances when we would want to force a type conversion in a way
different than the automatic conversion.
SYNTAX: (type-name)EXPRESSION
Ex:
int female_students, total_students;
Ratio = female_students / total_students (decimal portion is lost and hence
doesn’t give a accurate result)
Example Action
x= (int) 7.5 x=7
A=(int)21.3/(int)4.5 A= 21/4 = 5
B=(double)(sum/n) B will have result in double precision
Y= (int)(a+b) Result a+b is converted and stored in int form
Z=(int) a + b a is converted to int and then added to b
Types of errors
1. Syntax error : Each language has a set of rules to be followed while writing a
program. The errors that are obtained if the rules are not followed are called
syntax errors.
2. Logical error : Also known as Semantic error. When a program is compiled and
executed successfully and if the desired output is not obtained then the
program is said to have logical errors.
3. Runtime Error : This occurs when a program attempts to perform a task that
is not allowed. Eg : int b=0 ; c=a/b ;
Formatted & Unformatted Input / Output Statements
I/O functions
1. Unformatted I/O Function Ex : getch , putch
2. Formatted I/O Function ex: scanf , printf
getchar and putchar
getchar() : To read a character from the keyboard and store this character into
memory location. This function reads one character at a time
ch= getchar();
putchar() : To display a character stored in a variable on to the monitor. The
variable we intend to display needs to be passed as a parameter
putchar(ch);
printf("%s \n",a);
printf("%5.10s \n ",a);
printf("%15.10s \n ",a);
}
Write a C program to find out if a triangle is equilateral or isosceles given the 3
sides of the triangle. Use Logical operator
Hint :