0% found this document useful (0 votes)
411 views68 pages

Unit I Notes-C Prog

C Programming unit I notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
411 views68 pages

Unit I Notes-C Prog

C Programming unit I notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

UNIT 1 BASICS OF C PROGRAMMING 6


Problem Solving Techniques: Introduction to Algorithm, Pseudo code, Flow Chart, Structure of
‘C’ program. C Tokens: Keywords, Data Types, Constants, Variables - Declaration - Qualifiers –
typedef

1.1 PROBLEM SOLVING TECHNIQUES.


Problem Solving is a scientific technique to discover and implement the answer to a
problem. The computer is the manipulating device that follows the set of commands known as
program.

Program:
Program is the set of instructions which is run by the computer to perform specific task.
The task of developing program is called programming.

Problem Solving Technique:


Here are some basic steps to solve the problems
Step 1: Identify and Define Problem
Explain your problem clearly as possible as you can.
Step 2: Generate Possible Solutions

 List out all the solution that you find.


 Generate the maximum number of solution as you can without considering the
quality of the solution.
Step 3: Evaluate Alternatives
After generating the maximum solution, Remove the undesired solutions.
Step 4: Decide a Solution

After filtering all the solution, you have the best solution only. Then choose one of the best
solution and make a decision to make it as a perfect solution.
Step 5: Implement a Solution:
After getting the best solution, implement that solution to solve a problem.
Step 6: Evaluate the result
After implementing a best solution, evaluate how much your solution solve the problem.
If your solution will not solve the problem, then you can again start with Step 2.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

The following are the Problem solving Techniques used to develop solutions for a problem.
 Algorithms
 Flowcharts
 Pseudocode

1.1.1 ALGORITHM

 It is a step by step description for solving a task or a problem. The ordered sequence of
instructions is executed in the specified sequence, to get the desired results.

Characteristics of Algorithm:

 In the algorithms each and every instruction should be precise and unambiguous.

 The instructions in an algorithm should not be repeated infinitely.

 Ensure that the algorithm will ultimately terminate.

 The algorithm should be written in sequence.

 It looks like normal English.

Qualities of a Good Algorithm:

(i) Time:

To execute a program, the computer system takes some amount of time. The lesser is the
time required, the better is the algorithm.

(ii) Memory:

To execute a program, computer system takes some amount of memory storage. The lesser
is the memory required, the better is the algorithm

(iii) Accuracy:

Multiple algorithms may provide suitable or correct solutions to a given problem, some of
these may provide more accurate, such algorithms may be suitable.

(iv) Sequence:

The procedure of an algorithm must form in a sequence.

(v) Functionality:

The designed algorithm must solve a single isolated problem and algorithms are designed
to handle a range of input data.

Representation of Algorithms:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

 The algorithms can be represented in several ways. Generally, one of the following method
is used.

(i) Flow chart


(ii) Pseudocode
(iii) Program

(i) Flow chart:

The flow chart is a pictorial representation of an algorithm, the sequential steps in an


algorithm can be represented as a flow chart using the standard symbols.

(ii) Pseudocode:

Pseudocode is also a formal design tool and It consist of short, readable instructions with
the rules of structured programming.

(iii) Decision Table:

It is used for nested selection to help clarify the conditions to be tested and how these
conditions should be nested to do proper actions.

(iv) Program:

The algorithms can be represented as a program using any high level language that
becomes a program.

BUILDING BLOCKS OF ALGORITHM


Algorithm can be constructed from just three basic building blocks. These three building blocks
are
 Sequence
 Selection
 Iteration(Repetition)
 Functions
(i) Sequence
This describes a sequence of actions that a program carries out one after another,
unconditionally. Execute a list of statements in order.

Consider an example
Algorithm for Addition of two numbers:
Step 1: Start the program
Step 2: Get two numbers as input and store it in to a and b
Step 3: Add the number a & b and store it into c
Step 4: Print c
Step 5: Stop.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

(ii)Selection
Selection is the program that allows a program to choose between different actions. Choose
at most one action from several alternative conditions.

Example
Algorithm to find biggest among 2 numbers:
Step1: Start
Step 2: Get two numbers as input and store it in to A and B
Step 3: If a is greater than b then
Step 4: Print A is big
Step 5: else
Step 6: Print B is big
Step 7: Stop

(iii)Repetition
Repetition(loop) may be defined as a smaller program the can be executed several times in a main
program. Repeat a block of statements while a condition is true.

Example

Algorithm to calculate factorial no:


Step1: Start the program
Step 2: Read the number num.
Step 3: Initialize i is equal to 1 and fact is equal to 1
Step 4: Repeat step 5 and 6 until i is equal to num
Step 5: fact=fact * i
Step 6: i=i+1
Step 7: Print f

(iv)Function:
Function is a small block of statements in a program. Function executes only when the function is
called.

1.1.2 PSEUDOCODE
Pseudocode is a formal design tool. It consists of short, readable instruction set with the
rules of structured programming for logically explaining an algorithm.
“pseudo” means false, “code” means the set of statements (or) instructions written in a
programming language. Pseudocode is also called ‘Program Design Language’ (PDL)

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Rules for writing Pseudocode:


(i) Write one statement per line.
(ii) Capitalize the keywords
(iii) Indent to show hierarchy
(iv)End Multiline structure
(iv) Keep statements programming language independent
(v) It is written using structured English.

Example: Pseudocode to calculate student total and average


START
READ name, class, m1, m2, m3
Total = m1 + m2 + m3
Average = TOTAL /3
WRITE name, class, total, average
END
Pseudocode is made up of the following logic structure,

 Sequential logic
 Selection logic
 Iteration logic

1)Sequence Logic
 It is used to perform instructions in a sequence, that is one after another
 Thus, for sequence logic., pseudocode instructions are written in an order in which they
are to be performed.
 The logic flow of pseudocode is from top to bottom.

Example: Pseudocode to add two numbers:


START
READ a,b
COMPUTE c by adding a &b
PRINT c

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

STOP

2) Selection Logic
It is used for making decisions and for selecting the proper path out of two or more alternative
paths in program logic.

 It is also known as decision logic.


 Selection logic is depicted as either an IF..THEN or an IF…THEN..ELSE Structure.

Example: Pseudocode to find biggest among two numbers:


START
READ a and b
IF a>b THEN
PRINT “A is big”
ELSE
PRINT “B is big”
ENDIF
STOP

3) Repetition Logic
 It is used to produce loops when one or more instructions may be executed several times
depending on some conditions.
 It uses structures called DO_WHILE, FOR and REPEAT__UNTIL
Example: Pseudocode to print first 10 natural numbers
START
INITIALIZE a->0
WHILE a<10
PRINT a
ENDWHILE
STOP

1.1.3 FLOW CHART

 A Flow chart is a pictorial representation of an algorithm.

 A flowchart uses different shaped symbols to denote the different appropriate instruction
and these instructions can be written within the boxes using clear statements.

 Then these boxes are connected by lines having arrows to indicate the flow of operations.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Flow chart symbols:


 A flowchart is drawn using different kinds of symbols. A symbol used in a flowchart is for
a specific purpose.
 The flow chart symbols are available in word processors.

Description Symbols

i) Flow lines: These are the left to right or top to bottom lines
connecting symbols. These lines show the flow of control
through the program

ii) Terminal: The oval shaped symbol always begins and ends
the flowchart. The start symbol will have only one flow line
and stop will have and entering flow line. start

stop

iii)Input/Output: The parallelogram is used for Input


(Read)and output (write).

iv) Process: The rectangle symbol is used for calculation and


initialization of memory locations

v) Decision: The diamond shaped symbol is used to indicate at


a point at which a decision has to be made and a branch to one Yes
of two or more alternative point is possible
No

vi) Connectors: A connector symbol is represented by a circle


and a letter or digit is placed in the circle to specify the link. C
Whenever a complex flowchart is drawn more than one page,
connector symbol is used C

vii)Predefined Process: This symbol used for create


functions.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Rules for Drawing flowchart:


1. The standard symbols should only be used.

2. A flowchart must have a start and end.

3. The usual direction of the flow of procedure is from top to bottom; or left to right.

4. Only one flow line should come to a process symbol and only one flow line should out
from a process symbol.

5. Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer. Should leave the decision symbol.

True False
e

6. Only one flow line is used in the terminal symbol.

Start Stop

7. The flow lines should not cross each other


8. Be consistent in using names and variables in the flowchart
9. Keep the flowchart as simple as possible.
10. The words in flowchart symbols should be common statements and easy to understand.
11. If a new page is needed for flowchart, then use connectors for better representation.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Advantages of Flowchart:
(i) To understand logic clearly:
Before coding the program, the programmer must be known about the logic of the program.

(ii) Better communication:


The flowcharts are better from communication, because “a picture is worth of thousand
words”. It is very easy for the programmer to explain the logic of the program through the
flowchart

(iii) Effective Analysis:


The flowcharts are very well suited to analyse the problem and can be broken down into
parts.

(iv) Effective synthesis:


A team of designers or programmers are associated with the design of complex system.
Each designer or programmer is responsible for designing a part of the entire system.

(v) Effective coding:


After designing the flowchart, it is very easy to write programs for the programmers,
because flowchart is the road map for the programmers.

(vi) Proper Program documentation:


The documentation involves collecting, organizing and storing a complete record of
program.

(vii) Systematic Debugging:


After taking full care in program design there may be chances for some errors. Such errors
can easily be found out in the flowcharts, and these can be eliminated easily.
(viii) Efficient program Maintenance:
The maintenance of operating system becomes easy with the help of flowchart.

Limitations of using flowcharts:


(i) Complex Logic:
Sometimes, the program logic is complicated. In such case, flowchart becomes complex and
difficult to use.
(ii) Alterations and Modifications:
If any alternations required, the flowchart may require re-drawing completely.
(iii) Cost:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

For large application the time and cost of flowchart drawing will be more.
(iv) Not known:
Task start and finish dates, the duration of tasks, resources needed, physical locations of
tasks are not known.

Flowchart is made up of the following logic structure,


 Sequential logic
 Selection logic
 Iteration logic

Sequential logic Selection Logic

Start

Read

if
Process True A>B False

A is big B is big
Output

Stop

Iteration logic
(a) Top Tested loop:
o If the condition is true, the control follows the flow line that goes into the loop.
o If it is false, control follows the flow line to the first statement after the loop.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Start

count = 0

False
while
count < 10

True

count=count+1
Stop

Display
count

(b) Bottom Tested Loop:


o The body of the loop will be executed, once before control even gets to the loop
test.
o If the condition is false, control follows the flow line back to the loop.
o If the test is true, control follows the branch from the decision box that exists the
loop structure.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Start

count = 0

Add 1 to count

Display count

while
count <
True
False

Stop

SAMPLE PROBLEMS
1) Write an algorithm, Flowchart, Pseudocode to find the area and circumference of the circle.
Algorithm:
Step 1: Start
Step 2: Input the radius of the circle
Step 3: Find the area and circumference
area  3.14 * r*r
circumference  2*3.14*r
Step 4: Print the area and circumference
Step 5: Stop
Flow chart:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Start

read r

area = 3.14*r*r

print area, circumference

Stop

Pseudocode:
READ the radius r
Find the area and circumference
Area = 3.14*r*r
circumference = 2*3.14*r
WRITE area and circumference.

2) Roots of the Quadratic Equation


Algorithm:
Step 1: start
Step 2: Enter the value of a, b, c
Step 3 : Find the value of ‘d’ using the formula d = b*b-4*a*c
Step 4: If d is greater than or equal to zero then find the two roots are
root 1 (-b + sqrt (d))/ (2*a)
root 2 (-b- sqrt (d))/(2*a)
Step 5: Print the two roots, roots1, root2
Step 6: If d is not greater than or equal to zero,
then print the roots are imaginary
Step 7: Stop

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

start

read a, b, c

d = b*b-4*a*c

False
If d > = 0

True

root 1 = [-b+sqrt(d)]/(2*a)
root 2 = [-b-sqrt(d)]/(2*a)

print root1, root2

stop

Pseudocode:
READ the values of a, b, c
Find Discriminant
d b*b - 4*a*c
IF d>=0 THEN
Calculate root1 = (-b + sqrt(d))/(2*a)
Root2 = (-b + sqrt (d))/(2*a)
ELSE
Roots are imaginary
ENDIF
WRITE root1, root2
3) Program for Simple calculator

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Algorithm:
Step 1: Start
Step 2: Enter the values of a, b
Step 3: Find the sum
sum = a+ b, sub=a-b, pro=a*b, quo=a/b
Step 4 : Print the sum, sub, pro, quo
Step 5:
Stop

Pseudocode:
READ a,b
Find the sum difference, product, quotient
sum = a + b
sub=a-b
pro=a*b
quo=a/b
WRITE sum, sub, pro, quo
Flowchart

Start

read a,b

sum = a+b, sub=a-b, pro=a*b, quo=a/b

print sum, sub, mul, quo

Stop

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

4) To find the given year is leap year or not


Algorithm:
Step 1: Start
Step 2: Read the year
Step 3: If (year mod 4) = 0 THEN PRINT “leap year”
ELSE print “Not leap year”
Step 4: Stop
Pseudocode:
READ the year
IF (year % 4 = = 0) THEN
WRITE the year is leap year
ELSE
WRITE the year is not a leap year
ENDIF
Flow chart

Start

Read year

False
If
(year % 4 = =
0)

Print not leap


True year

Print leap year

Stop

5) To find the Greatest of three numbers

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Algorithm:
Step1: start Pseudocode:
Step 2: READ a, b, c READ a, b, c
Step 3: IF (a >b) and (a>c) THEN IF ((a>b) &&(a>c)) THEN
Step 3.1: Print ‘a’ is big WRITE ‘a is big’
ELSE ELSE IF (b>c) THEN
Step 4: IF (b>c) THEN WRITE ‘b is big’
Step 4.1: Print ‘b’ is big ELSE
ELSE WRITE ‘c is big’
Step 4.2: Print ‘c; is big ENDIF
Step 5: Stop
Flowchart

Start

Read a,b,c

If False
(a>b) and
(a>c)
If
True (b>c)

True False

print a is big print b is big print c is big

Stop

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

6) To print the Reverse of a number


Algorithm:
Step 1: Start
Step 2: Enter the value of n
Step 3: Assign r = 0, sum = 0
Step 4: IF n >0 ELSE Goto step 6
Step 4.1: r n mod 10.
Step 4.2: sumsum *10+r
Step 4.3: nn div 10
Step 5: Goto step 4
Step 6: Print sum
Step 7: Stop

Flow chart

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Start

Read n

r =0
Sum = 0

False
While
(n>0)

True

r = n%10
Sum = sum*10+r
N = n/10

Print sum

Stop

Pseudocode
Set sum = 0, r=0
READ value of n
WHILE (n>0)
r =n% 10
sum = sum *10 + r
n = n/10
ENDWHILE
WRITE Sum

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

7) To find the sum & avg of n numbers


Algorithm
Step 1: Start
Step 2: Enter the value of n
Step 3: Assign , sum0
Step 4: If n > 0, ELSE Go to step 6
Step 4.1: sum  sum + r Flow chart
Step 5: Goto step 4
Start
Step 6: Print sum
Step 7: avg=sum/n
Read n
Step 8: print avg
Step 9: Stop
Pseudocode sum = 0

Set Sum = 0,
READ the value of n
WHILE (n <= 0) While
False

READ the value of num (n<=0)

sum = sum +num


True
n = n-1
Read num
ENDWHILE
WRITE sum
Avg=avg/n sum = sum+num
n=n-1
WRITE avg

Print sum

avg=sum/n

Print avg

Stop

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

10) To swap the variable using another variable


Flow chart

Start

Read a, b

temp = a
a=b
b = temp

Print a, b

Stop

Algorithm
Step1: Start
Step 2: Read the value of a,b
Step 3: To swap using temp
Step 3.1: temp a
Step 3.2: a  b
Step 3.3: b  temp
Step 4: Print value a and b
Step5: Stop
Pseudocode
READ a, b
Swap a and b using temp
temp = a
a=b
b = temp
WRITE a and b

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

11) To generate the Fibonacci series:


Algorithm
Step 1: Start
Step 2 : Assign f10, f2  1, f0
Step 3: Print f1, f2
Step 4: f f1+f2
Step 5: READ n
Step 6: IF (f < n), ELSE Goto Step 8
Step 6.1 : ff1 + f2
Step 6.2: f1  f2
Step 6.3: f2f
Step7: Goto step 6
Step 8: Stop

Pseudocode
Set f1 =0, f2 = 1, f = 0
WRITE f1, f2
f = f1 + f2
READ n
WHILE (f < n)
f = f1 + f2
f1 = f2
f2 = f
WRITE f
ENDWHILE

Flowchart :

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Start

f1 =0
f2 = 1, f= 0

Print f1, f2

Read n

False
While
( f < n)

True

f = f1 + f2
f1 = f2
f2 = f

Print f

Stop

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

12) Find the area of triangle:


Algorithm
Step 1: Start
Step 2: Read value of a, b, c
Step 3: Calculate the three sides
s  (a + b + c)/2
Step 4: Find area Flow chart

area  sqrt (s*(s-a)*(s-b)*(s-c)) Start


Step 5: print area

Step 6: Stop Read a, b

Pseudocode
s= (a+b+c)/2
READ a, b, c

CALCULATE s
area = sqrt (s*(s-a) * (s-b)*(s-c))
s = a+b+c/2

area = sqrt (s*(s-a) * (s-b) * (s-c)) Print area


WRITE area
Stop

13) To convert the celcius into Fahrenheit

Algorithm Flow chart


Step1: Start
Start
Step 2: Read the celcius

Step 3: Calculate the fahrenheit Read celcius

fahrenheit  (1-8 *celcius) + 32

Step 4: Print fahrenheit fahrenheit=(1.8*celcius) + 32

Step5: Stop
Print fahrenheit

Pseudocode
Stop

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

READ celcius
Find fahrenheit
fahrenheit = (1.8 * celcius ) + 32
WRITE Fahrenheit

14) To find the sum of all odd integers between 1 and n


Algorithm
Step 1: Start Flow chart
Step 2: Read the value of n
Start
Step 3: Assign Sum 0 and i 1
Step 4: IF i<=n ELSE Goto step 6 Read n
Step 4.1: sum sum + i
Step 4.2: ii+2 Sum = 0, i = 1
Step 5: Goto step 4
Step 6: Print sum False

Step 7: Stop While


i<=n
Pseudocode True
Set sum = 0, i = 1
Sum = sum + i
READ n
WHILE (i < = n)
Sum = sum + i
sum = sum + i
i = i+ 2
Print sum
ENDWHILE
WRITE SUM
Stop

x3 x5 x7 xn
15) To solve the series S  x     .......
3! 5! 7! n!
Algorithm Pseudocode
Step 1: Start Set s= 0, term = x, I =1
Step 2: Read the value of x, n READ x, n
Step3: assign s 0, term x, i1. WHILE (I < = n)

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Step 4: ss+term s=s+term


Step 5: term = term*x*x (-1)/ (i+1)(i+2) term = (term *x*x(-1)/(i+1)*(i+2)
Step 6: ii+2 i=i+2
Step 7: Repeat step 4 to 6 WHILE (i<=n) ENDWHILE
Step 8: Stop WRITE result.
Flow chart
Start

Read x, n

sum = 0
term = x
i=1

While
i<=n

sum = sum + i

Print s

Stop

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

16. To convert a binary number to decimal number


Algorithm Pseudocode
Step 1: Start set q = n, s=0, k=0
Step 2: Read binary value n READ n
Step 3: Initialise q = n, s= 0, k=0 WHILE (q>0)
Step 4: Chack (q>0) r=q%10
Step 5: Calculate = r=q%10 s=s+r * pow(2, k)
s=s+r*pow (2, k) q=q/10
q = q/10 k = k+1
k = k+1 ENDWHILE
Step 6: Print S WRITE s
Step 7: Stop
Flow chart:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Start

Read x, n

q=n
s =0
k =0

While
q>0

r = q%10
s=s+r*pow(2,k)
q=q/10
k=k+1

Print s

Stop

17) To find the factorial of the given number


Algorithm Pseudocode
Step 1: Start Set fact = 1, i = 1
Step 2: Read the value n READ the value n
Step 3: Set initial values fact= i=1 IF (i<=n) THEN
Step 4: IF i<=n ELSE Goto Step 6 fact = fact *i
Step 4.1 : fact  fact *i i =i + 1
Step 4.2 : i  i + 1 ENDIF
Step 5: Goto Step 4 WRITE fact
Step 6: print fact
Step 7: Stop

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Flow chart:

Start

Read n

fact=1, i=1

If
i<=n

fact=fact*i Print

i=i+1
Stop

18) To find whether the number is prime or not.


Algorithm Pseudocode
Step1: Start Set i = 2
Step 2: Assign i2 READ n
Step 3: READ n WHILE (i < = n-1)
Step 4: REPEAT steps 4.1, 4.2 IF n mod i = = 0 THEN
UNTIL i < = n – 1 WRITE not prime
Step 4.1: If (nmod I = 0) THEN EXIT
Print Not Prime ENDIF
Step 4.2: i  i +1 i=i+1
Step 5: IF (i=n) Then END WHILE
Step 6: Print prime IF (i = = n) THEN
WRITE prime
ROHINI COLLEGE OFENDIF
ENGINEERING AND TECHNOLOGY
24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Flow chart:

Start

i=2

read n

Fals
if
i<=n-1

Tru

If False
n % i == 0
True

Print not
prime

i=i+1
A

False
if
i==n

Tru
Print prime

A
Stop

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

C PROGRAMMING

C is a general-purpose programming language created by Dennis Ritchie at the Bell


Laboratories in 1972. It is a very popular language. It is a fundamental language in the field of
computer science. C language combines the power of a low-level language and a high-level
language. The low-level languages are used for system programming, while the high-level
languages are used for application programming. It is because such languages are flexible and easy
to use. Hence, C language is a widely used computer language.

It supports various operators, constructors, data structures, and loop constructs. The
features of C programming make it possible to use the language for system programming,
development of interpreters, compilers, operating systems, graphics, general utilities, etc. C is also
used to write other applications, such as databases, compilers, word
processors, and spreadsheets.

1.2 STRUCTURE OF C PROGRAM


The structure of a language gives us a basic idea of the order of the sections in a program.
We get to know when and where to use a particular statement, variable, function, curly braces,
parentheses, etc. It also increases our interest in that programming language.

Thus, the structure helps us analyse the format to write a program for the least errors. It
gives better clarity and the concept of a program.

Sections of a C program

The sections of a C program are listed below:

1. Documentation section
2. Preprocessor section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

1.Documentation section

It includes the statement specified at the beginning of a program, such as a program's name,
date, description, and title. Comment lines are used. It is represented as:

//name of a program
OR
/* Overview of the code */
Both methods work as the document section in a program. It provides an overview of the
program. Anything written as comments will be considered a part of the documentation section
and will not interfere with the specified code.
2.Preprocessor section

The preprocessor section contains all the header files used in a program. It informs the
system to link the header files to the system libraries. It is given by:

#include<stdio.h>
#include<conio.h>

The #include statement includes the specific file as a part of a function at the time of the
compilation. Thus, the contents of the included file are compiled along with the function being
compiled.

The #include<stdio.h> consists of the contents of the standard input output files, which
contains the definition of stdin, stdout, and stderr. Whenever the definitions stdin, stdout, and stderr
are used in a function, the statement #include<stdio.h> need to be used.

There are various header files available for different purposes. For example, # include
<math.h>. It is used for mathematic functions in a program.

3.Define section

The define section comprises of different constants declared using the define keyword. It is given
by:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

#define a = 2

4. Global declaration

The global section comprises of all the global declarations in the program. It is given by:

float num = 2.54;

int a = 5;

char ch ='z';

5. Main function

main() is the first function to be executed by the computer. It is necessary for a code to
include the main(). It is like any other function available in the C library. Parenthesis () are used
for passing parameters (if any) to a function.

The main function is declared as: main()

We can also use int or void with the main (). The void main() specifies that the program will
not return any value. The int main() specifies that the program can return integer type data.

int main()
OR
void main()
Main function is further categorized into local declarations, statements, and expressions.

6.Local declarations

The variable that is declared inside a given function or block refers to as local declarations.

main()
{
int i = 2;
i++;
}

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

7.Statements

The statements refer to if, else, while, do, for, etc. used in a program within the main
function.

Expressions: An expression is a type of formula where operands are linked with each other by the
use of operators. It is given by:

a - b;

a +b;

8.User defined functions

The user defined functions specified the functions specified as per the requirements of the
user. For example, color(), sum(), division(), etc.

The program (basic or advance) follows the same sections as listed above.

Return statement is generally the last section of a code. But, it is not necessary to include. It is
used when we want to return a value. The return function returns a value when the return type
other than the void is specified with the function.

Return type ends the execution of the function. It further returns control to the specified
calling function. It is given by

return;

Or

return expression;

For example,

return 0;

Example 1: To find the sum of two numbers given by the user

/* Sum of two numbers */


#include<stdio.h>
int main()
{

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

int a, b, sum;
printf("Enter two numbers to be added ");
scanf("%d %d", &a, &b);
// calculating sum
sum = a + b;
printf("%d + %d = %d", a, b, sum);
return 0; // return the integer value in the sum
}

Output

The detailed explanation of each part of a code is as follows:

/* Sum of the two It is the comment section. Any statement described in it is not considered as
numbers */ a code. It is a part of the description section in a code.
The comment line is optional. It can be in a separate line or part of an
executable line.

#include<stdio.h> It is the standard input-output header file. It is a command of the preprocessor


section.

int main() main() is the first function to be executed in every program. We have used
int with the main() in order to return an integer value.

{… The curly braces mark the beginning and end of a function. It is mandatory
} in all the functions.

printf() The printf() prints text on the screen. It is a function for displaying constant
or variables data. Here, 'Enter two numbers to be added' is the parameter
passed to it.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

scanf() It reads data from the standard input stream and writes the result into the
specified arguments.

sum = a + b The addition of the specified two numbers will be passed to the sum
parameter in the output.

return 0 A program can also run without a return 0 function. It simply states that a
program is free from error and can be successfully exited.

Example 2: Below C program to find the sum of 2 numbers using function


// Documentation
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
/ Subprogram
int sum(int y)
{
return y + X;
}
Output
Sum: 75

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Explanation of the above Program


Below is the explanation of the above program. With a description explaining the program’s
meaning and use.

Sections Description

/**
*file:sum.c
* author: you It is the comment section and is part of the description section of the
* description: program code.
to find sum.
*/

Header file which is used for standard input-output. This is the


#include<stdio.h> preprocessor section.

This is the definition section. It allows the use of constant X in the


#define X 20 code.

This is the Global declaration section includes the function


int sum(int y) declaration that can be used anywhere in the program.

int main() main() is the first function that is executed in the C program.

These curly braces mark the beginning and end of the main
{…} function.

printf(“Sum: %d”,
printf() function is used to print the sum on the screen.
sum(y));

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Sections Description

We have used int as the return type so we have to return 0 which


states that the given program is free from the error and it can be
return 0; exited successfully.

int sum(int y)
{ This is the subprogram section. It includes the user-defined
return y + X; functions that are called in the main() function.
}

1.3 C TOKENS
A token in C can be defined as the smallest individual element of the C programming
language that is meaningful to the compiler. It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are
used to perform. The types of C tokens are as follows:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

1. Keywords
The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program.
You cannot redefine keywords. C language supports 32 keywords which are given
below:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

2. Identifiers
Identifiers are used as the general terminology for the naming of variables, functions, and
arrays. These are user-defined names consisting of an arbitrarily long sequence of letters and
digits with either a letter or the underscore (_) as a first character.
Identifier names must differ in spelling and case from any keywords. You cannot use
keywords as identifiers;
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
 They must begin with a letter or underscore (_).
 They must consist of only letters, digits, or underscore. No other special character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are significant.
For example,
Roll_no, num1, _age, contact_number1
 main: method name.
 a: variable name.
3. Constants
The constants refer to the variables with fixed values. They are like normal variables but
with the difference that their values cannot be modified in the program once they are
defined. Constants may belong to any of the data types.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Examples of Constants in C
const int c_var = 20;
const float pi=3.14

4. Strings
Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in double
quotes. Whereas, a character is enclosed in single quotes in C and C++.
Examples of String
char str1[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char str2[20] = “c Programming”;
char str3[] = “C Concepts”;

5. Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot
be used for some other purpose. Some of these are listed below:
 Brackets[]: Opening and closing brackets are used as array element references. These
indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and function
parameters.
 Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
 Comma (, ): It is used to separate more than one statement like for separating parameters in
function calls.
 Colon(:): It is an operator that essentially invokes something called an initialization list.
 Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity.
That’s why each individual statement must be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
 Assignment operator(=): It is used to assign values and for logical operation validation.
 Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

 Period (.): Used to access members of a structure or union.


 Tilde(~): Bitwise One’s Complement Operator.

6. Operators
Operators are symbols that trigger an action when applied to C variables and other objects.
The data items on which operators act are called operands. Depending on the number of
operands that an operator can act upon, operators can be classified as follows:
 Unary Operators: Those operators that require only a single operand to act upon are
known as unary operators. For Example increment and decrement operators
 Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
 Ternary Operator: The operator that requires three operands to act upon is called the ternary
operator. Conditional Operator(?) is also called the ternary operator.

1.4 KEYWORDS
Keywords are those predefined words that have special meaning in the compiler and they
cannot be used for any other purpose. As per the C99 standard, C language has 32 keywords.
Keywords cannot be used as identifiers.
• The following table has the list of all keywords (reserved words) available in the C
language:

auto double int struct


break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

default goto sizeof volatile


const float short unsigned
All the keywords in C have lowercase alphabets, although the keywords that have been
newly added in C, do have uppercase alphabets in them.
C is a case-sensitive language. Hence, int is a keyword but INT, or Int are not recognized as a
keyword.
The compiler checks the source code for the correctness of the syntax of all the keywords and
then translates it into the machine code.

These keywords can be broadly classified in following types −


 Primary Data types
 User defined types
 Storage types
 Conditionals
 Loops and loop controls
 Others
Primary Types C Keywords
These keywords are used for variable declaration. C is a statically type language, the
variable to be used must be declared. Variables in C are declared with the following keywords:
int Declares an integer variable
long Declares a long integer variable
short Declares a short integer variable
signed Declares a signed variable
double Declares a double-precision variable
char Declares a character variable
float Declares a floating-point variable
unsigned Declares an unsigned variable
void Specifies a void return type

User-defined Types C Keywords


C language allows you to define new data types as per requirement. The user defined
type has one or more elements of primary type.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

The following keywords are provided for user defined data types −
struct Declares a structure type
typedef Creates a new data type
union Declares a union type
enum Declares an enumeration type

Storage Types C Keywords


The following set of keywords are called storage specifiers. They indicate the location
where in the memory the variables stored. Default storage type of a variable is auto, although
you can ask the compiler to form a variable with specific storage properties.
auto Specifies automatic storage class
extern Declares a variable or function
static Specifies static storage class
register Specifies register storage class

Conditionals C Keywords
The following set of keywords help you to put conditional logic in the program. The
conditional logic expressed with if and else keywords provides two alternative actions for a
condition. For multi-way branching, use switch – case construct. In C, the jump operation in an
assembler is implemented by the goto keyword.
goto Jumps to a labeled statement
if Starts an if statement
else Executes when the if condition is false
case Labels a statement within a switch
switch Starts a switch statement
default Specifies default statement in switch

Loops and Loop Control C Keywords


Repetition or iteration is an essential aspect of the algorithm. C provides different
alternatives for forming a loop, and keywords for controlling the behaviour of the loop. Each of
the keywords let you form a loop of different characteristics and usage.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

For Starts a for-loop


do Starts a do-while loop
while starts a while loop
continue skips an iteration of a loop
break Terminates a loop or switch statement

Other C Keywords
The following miscellaneous keywords are also extremely important:
const Specifies a constant value
Sizeof Determines the size of a data type
Volatile compiler that the value of the variable may change at any time

1.5 DATA TYPES IN C


 Each variable in C has an associated data type.
 It specifies the type of data that the variable can store like integer, character,
floating, double, etc.
 Each data type requires different amounts of memory and has some specific
operations which can be performed over it.
The data types in C can be classified as follows:

Types Description

Primitive Data Primitive data types are the most basic data types that are used for
Types representing simple values such as integers, float, characters, etc.

User Defined
The user-defined data types are defined by the user himself.
Data Types

The data types that are derived from the primitive or built-in datatypes
Derived Types
are referred to as Derived Data Types.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

The data type is a collection of data with values having fixed values, meaning as well as
its characteristics.

Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the memory
requirement and format specifiers on the 32-bit GCC compiler.
Data Type
Size (bytes) Range Format Specifier
short int
2 -32,768 to 32,767 %hd

unsigned short
2 0 to 65,535
int %hu

unsigned int 4 0 to 4,294,967,295 %u

-2,147,483,648 to
int 4 %d
2,147,483,647

-2,147,483,648 to
long int 4 %ld
2,147,483,647

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long 0 to
8 %llu
long int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 %f
1.2E-38 to 3.4E+38

double 8 %lf
1.7E-308 to 1.7E+308

Primitive data types in C:


1.Integer Data Type
The integer datatype in C is used to store the integer numbers (any number including positive,
negative and zero without decimal part). Octal values, hexadecimal values, and decimal values
can be stored in int data type in C.
 Range: -2,147,483,648 to 2,147,483,647
 Size: 4 bytes
 Format Specifier: %d
Syntax
int var_name;
C program to print Integer data types.
#include <stdio.h>
int main()
{
// Integer value with positive data.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

int a = 9;
// integer value with negative data.
int b = -9;
// U or u is Used for Unsigned int in C.
int c = 89U;
// L or l is used for long int in C.
long int d = 99998L;
printf("Integer value with positive data: %d\n", a);
printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n",c);
printf("Integer value with an long int data: %ld", d);
return 0;
}
Output
Integer value with positive data: 9

Integer value with negative data: -9

Integer value with an unsigned int data: 89

Integer value with a long int data: 99998

The integer data type can also be used as


1. unsigned int: Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768 to
32,767.
3. long int: Larger version of the int datatype so can store values greater than int.
4. unsigned short int: Similar in relationship with short int as unsigned int with int.

2.Character Data Type


Character data type allows its variable to store only a single character. The size of the
character is 1 byte. It is the most basic data type in C. It stores a single character and requires a
single byte of memory in almost all compilers.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

 Range: (-128 to 127) or (0 to 255)


 Size: 1 byte
 Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of character type:

char var_name;

// C program to print Integer data types.


#include <stdio.h>
int main()
{
char c = 'a';
printf("Value of c: %c\n", c);
c++;
printf("Value of a after increment is: %c\n", c);
return 0;
}
Output
Value of c: a

Value of c after increment is: b

3.Float Data Type


In C programming float data type is used to store floating-point values. Float in C is used to
store decimal and exponential values. It is used to store decimal numbers (numbers with floating
point values) with single precision.
 Range: 1.2E-38 to 3.4E+38
 Size: 4 bytes
 Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:

float var_name;

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

// C Program to demonstrate use of Floating types


#include <stdio.h>
int main()
{
float a = 9.0f;
float b = 2.5f;
// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);

return 0;
}
Output
9.000000

2.500000

0.000200

4. Double Data Type


A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers with
decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding 64
bits of decimal numbers or floating points.
Since double has more precision as compared to that float then it is much more obvious that
it occupies twice the memory occupied by the floating-point type. It can easily accommodate
about 16 to 17 digits after or before a decimal point.
 Range: 1.7E-308 to 1.7E+308
 Size: 8 bytes
 Format Specifier: %lf

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Syntax of Double
The variable can be declared as double precision floating point using the double keyword:

double var_name;

// C Program to demonstrate use of double data type


#include <stdio.h>
int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;
printf("%lf\n", a);
printf("%lf\n", b);
printf("%lf", c);
return 0;
}

5.Void Data Type


The void data type in C is used to specify that no value is present. It does not provide a
result value to its caller.
It has no values and no operations. It is used to represent nothing. Void is used in
multiple ways as function return type, function arguments as void, and pointers to void.

6.Size of Data Types in C


The size of the data types in C is dependent on the size of the architecture, so we cannot
define the universal size of the data types. For that, the C language provides the sizeof() operator
to check the size of the data types.

Syntax:
// function return type void
void exit(int check);
// Function without any parameter can accept void.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

int print(void);
// memory allocation function which returns a pointer to void.
void *malloc (size_t size);

// C Program to print size of different data type in C


#include <stdio.h>
int main()
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);
printf("The size of int data type : %d\n", size_of_int);
printf("The size of char data type : %d\n",size_of_char);
printf("The size of float data type : %d\n",size_of_float);
printf("The size of double data type : %d",size_of_double);
return 0;
}
Output
The size of int data type : 4

The size of char data type : 1

The size of float data type : 4

The size of double data type : 8

1.6 VARIABLE IN C
A variable is an Identifier used for naming entity in Programming. Variable C is a
memory location with some name that helps store some form of data and retrieves it when
required. They can be viewed as the names given to the memory location so that we can refer to
it without having to memorize the memory address.
The size of the variable depends upon the data type it stores.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the variable.
datatype variablename = value ; // defining single variable
or
datatype variable_name1, variable_name2 ; // defining multiple variable
Here,
 data_type: Type of data that a variable can store.
 variable_name: Name of the variable given by the user.
 value: value assigned to the variable by the user.
Example
int var; // integer variable
char a; // character variable
float fff; // float variables

There are 2 aspects of defining a variable:


1. Variable Declaration
2. Variable Initialization
1) Variable Declaration
Variable declaration in C tells the compiler about the existence of the variable with the
given name and data type.
When the variable is declared, an entry in symbol table is created and memory will be
allocated at the time of initialization of the variable.
Example
int var;
char var2;
2) Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value
to the variable when creating the variable.
Example

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

int var = 10; // variable declaration and definition (i.e. Vairable Initialization)

EXAMPLE
// C program to demonstrate the declaration, initialization
#include <stdio.h>
int main()
{
// declaration
int defined_var;
// assignment
defined_var = 12;
// initialization
int ini_var = 25;
printf("Value of defined_var after assignment: %d\n", defined_var);
printf("Value of ini_var: %d", ini_var);
return 0;
}

Output
Value of defined_var after assignment: 12

Value of ini_var: 25

Rules for Naming Variables In C


1. A variable name must only contain alphabets, digits, and underscore.
2. A variable name must start with an alphabet or an underscore only. It cannot start with a digit.
3. No white space is allowed within the variable name.
4. A variable name must not be any reserved word or keyword.
Example: valid variable names _arjun, arjun_hari, arjun123, arjun_1, room_105
Invalid variable names: arjun hari, 1arjun, 105room

C VARIABLE TYPES
The C variables can be classified into the following types:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

1. Local Variables
2. Global Variables
3. Static Variables
4. Automatic Variables
5. Extern Variables
6. Register Variables

1) Local Variables in C
A Local variable in C is a variable that is declared inside a function or a block of code. Its
scope is limited to the block or function in which it is declared.
Example of Local Variable in C
// C program to declare and print local variable inside a function.
#include <stdio.h>
void function()
{
int x = 10; // local variable
printf("%d", x);
}

int main()
{
function();
}
Output
10

In the above code, x can be used only in the scope of function (). Using it in the main function
will give an error.

2. Global Variables in C
A Global variable in C is a variable that is declared outside the function or a block of
code. Its scope is the whole program i.e. we can access the global variable anywhere in the C
program after it is declared.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Example of Global Variable in C


// C program to demonstrate use of global variable
#include <stdio.h>
int x = 20; // global variable
void function1()
{
printf("Function 1: %d\n", x);
}
void function2()
{
printf("Function 2: %d\n", x);
}
int main()
{
function1();
function2();
return 0;
}
Output
Function 1: 20

Function 2: 20

3. Static Variables in C
A static variable in C is a variable that is defined using the static keyword. It can be
defined only once in a C program and its scope depends upon the region where it is declared
(can be global or local).
The default value of static variables is zero.
Syntax of Static Variable in C
static data_type variable_name = initial_value;

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

As its lifetime is till the end of the program, it can retain its value for multiple function
calls as shown in the example.
/ C program to demonstrate use of static variable
#include <stdio.h>
void function()
{
int x = 20; // local variable
static int y = 30; // static variable
x = x + 10;
y = y + 10;
printf("\tLocal: %d\n\t Static: %d\n", x, y);
}
int main()
{
printf("First Call\n");
function();
printf("Second Call\n");
function();
printf("Third Call\n");
function();
return 0;
}
Output
First Call

Local: 30

Static: 40

Second Call

Local: 30

Static: 50

Third Call

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Local: 30

Static: 60

4. Automatic Variable in C
All the local variables are automatic variables by default. They are also known as auto
variables.
Their scope is local and their lifetime is till the end of the block. If we need, we can use
the auto keyword to define the auto variables.
The default value of the auto variables is a garbage value.

Syntax of Auto Variable in C


auto data_type variable_name;
or
data_type variable_name; (in local scope)
Example of auto Variable in C
// C program to demonstrate use of automatic variable
#include <stdio.h>
void function()
{
int x = 10; // local variable (also automatic)
auto int y = 20; // automatic variable
printf("Auto Variable: %d", y);
}
int main()
{
function();
return 0;
}
Output
Auto Variable: 20

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

In the above example, both x and y are automatic variables. The only difference is that variable
y is explicitly declared with the auto keyword.

5) External Variables in C
External variables in C can be shared between multiple C files. We can declare an external
variable using the extern keyword.
Their scope is global and they exist between multiple C files.
Syntax of Extern Variables in C
extern data_type variable_name;

Example of Extern Variable in C


----------myfile.h------------
extern int x=10; //external variable (also global)

----------program1.c----------
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", x);
}

6) Register Variables in C
Register variables in C are those variables that are stored in the CPU register instead of the
conventional storage place like RAM. Their scope is local and exists till the end of
the block or a function.
 These variables are declared using the register keyword.
 The default value of register variables is a garbage value.
Syntax of Register Variables in C
register data_type variable_name = initial_value;

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Example of Register Variables in C


//C program to demonstrate the definition of register variable
#include <stdio.h>
int main()
{
register int var = 22;
printf("Value of Register Variable: %d\n", var);
return 0;
}

Output
Value of Register Variable: 22

1.7 CONSTANTS IN C
The constants in C are the read-only variables whose values cannot be modified once
they are declared in the C program.
 The type of constant can be an integer constant, a floating pointer constant, a
string constant, or a character constant.
 In C language, the const keyword is used to define the constants.
 As the name suggests, a constant in C is a variable that cannot be modified once
it is declared in the program.
 We cannot make any change in the value of the constant variables after they are
defined.
How to Define Constant in C?
We define a constant in C language using the const keyword. Also known as a const type
qualifier, the const keyword is placed at the start of the variable declaration to declare that
variable as a constant.
Syntax to Define Constant
const data_type var_name = value;

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Example of Constants in C
// C program to illustrate consta
#include <stdio.h>
int main()
{
// defining integer constant using const keyword
const int int_const = 25;
// defining character constant using const keyword
const char char_const = 'A';

// defining float constant using const keyword


const float float_const = 15.66;
printf("Printing value of Integer Constant: %d\n", int_const);
printf("Printing value of Character Constant: %c\n",char_const);
printf("Printing value of Float Constant: %f", float_const);
return 0;
}

Output
Printing value of Integer Constant: 25

Printing value of Character Constant: A

Printing value of Float Constant: 15.660000

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the list
of the types of constants
 Integer Constant
 Character Constant
 Floating Point Constant
 Double Precision Floating Point Constant
 Array Constant
 Structure Constant

PROPERTIES OF CONSTANT IN C
The important properties of constant variables in C defined using the const keyword are as
follows:
1. Initialization with Declaration
We can only initialize the constant variable in C at the time of its declaration.
Otherwise, it will store the garbage value.
2. Immutability
The constant variables in c are immutable after its definition, i.e., they can be initialized
only once in the whole program. After that, we cannot modify the value stored inside that
variable.

// C Program to demonstrate the behaviour of constant


// variable
#include <stdio.h>
int main()
{
// declaring a constant variable

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

const int var;


// initializing constant variable var after declaration
var = 20;
printf("Value of var: %d", var);
return 0;
}

Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^

1.8 QUALIFIERS IN C PROGRAMMING

Type qualifiers were introduced by ANSI C, It is used to control optimization done by the
compiler on any data object.

There are two type of qualifiers in C:

1. const

2. volatile

const and volatile type qualifiers can be applied to any type of data objects. When using a
type qualifier with an array identifier, each element of the array is qualified by the compiler, not the
array type itself.

A qualifier can be applied on structure/union objects and an individual structure/union


member can also be qualified. When a structure object is qualified, each member of the structure is
qualified using same qualifier and when a qualifier is applied on any particular structure member
then only that member is qualified.

1. The ‘const’ qualifier:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

This qualifier instructs compiler to mark any data object as read only i.e. no one can change
the value of the data object during program execution.

Objects qualified by the const keyword cannot be modified. This means that an object
declared as const cannot serve as the operand in any operation that changes its value.
Some const qualified objects and their behavior are given below:

Constant integer:

const int Var = 10;

The value of Var can’t be modified.

Pointer to a constant integer:

const int *Ptr;

The value in the location pointed by Ptr can’t be modified i.e. *Ptr is non-modifiable but Ptr is
modifiable;

Constant pointer:

int * const Cptr;

A pointer which will always point to the same location. Cptr is non-modifiable but *Cptr is
modifiable;

A constant pointer to a constant integer:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

const int *const Ccp;

Neither the pointer nor the integer can be modified. Ccp and *Ccp, both are not modifiable.

EXAMPLE:

#include<stdio.h>
const int glob=10; /* reside inside read only data segment */
int main()
{
const int localc=10; /* goes onto stack and localc is marked as read only */
int *localp1=&amp;localc; /* WARNING: local const accessed through a non const qualified
object */
int *localp2=&amp;glob; /* WARNING: global const accessed through a non const qualified
object */
*localp1=0; /* Allowed */
*localp2=0; /* Illegal: since address localp2 reside in.ro section and any alteration in .ro
section results a segmentation fault */
return 0;
}

2. The ‘volatile’ qualifier:

The volatile qualifier alters the default behavior of the variable and does not attempt to
optimize the storage referenced by it.

volatile means the storage is likely to change at any time and that is something outside the
control of the user program.

This means that if you reference the variable, the program should always check the
physical address (i.e. a mapped input fifo), and not use it in a cached way.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

This qualifier forces the compiler to allocate memory for the volatile object, and to always access
the object from memory.

Some volatile qualified objects and their behavior are given below:

Volatile data object:


To declare a volatile data object, include the keyword volatile before or after the data type in the
variable definition. For instance both of these declarations will declare vint to be a volatile
integer:

volatile int vint;


int volatile vint;

Pointer to a volatile data object:


Both of these declarations declare ptr to be a pointer to a volatile integer:

volatile int * ptr;


int volatile * ptr;

Volatile pointer to a non-volatile data object:


Following declaration declares vptr to be a volatile pointer to non-volatile integer:

int * volatile vptr;

Volatile pointer to a volatile data object:


Following declaration declares vptrv to be a volatile pointer to volatile integer:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

int volatile * volatile vptrv;

If you apply volatile to a struct or union, the entire contents of the struct/union are volatile.
If you don’t want this behavior, you can apply the volatile qualifier to the individual members of
the struct/union.

Use of volatile variable:


A volatile variable is used, where the value of variable changes unexpectedly.
You can see usage of volatile variables in

• Memory-mapped peripheral registers.


• Global variables modified by an interrupt service routine.
• Global variables within a multi-threaded application.

Example code 1:

void TestFunc()
{
unsigned int * ptr = (unsigned int *) 0x65917430;
/* Wait for register to become non-zero. */
while (0 == *ptr);
printf("Register updated\n");
}

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

1.9 TYPEDEF

The typedef is a keyword that is used to provide existing data types with a new name. The
C typedef keyword is used to redefine the name of already existing data types. When names of
datatypes become difficult to use in programs, typedef is used with user-defined datatypes, which
behave similarly to defining an alias for commands.

Syntax
typedef existing_name alias_name;
After this declaration, we can use the alias_name as if it were the real existing_name in out C
program.
Example:
typedef long long ll;
Below is the C program to illustrate how to use typedef.
// C program to implement typedef
#include <stdio.h>
// defining an alias using typedef
typedef long long Longl;
// Driver code
int main()
{
// using typedef name to declare variable
Long1 var = 20;
printf("%ld", var);
return 0;
}

Output
20

Use of typedef in C
 Following are some common uses of the typedef in C programming:

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CS201 PROGRAMMING FOR PROBLEM SOLVING USING C – UNIT 1

 The typedef keyword gives a meaningful name to the existing data type which helps other
users to understand the program more easily.
 It can be used with structures to increase code readability and we don’t have to type struct
repeatedly.
 The typedef keyword can also be used with pointers to declare multiple pointers in a single
statement.
 It can be used with arrays to declare any number of variables.

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

You might also like