Introduction Unit-1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 104

INTRODUCTION TO

C PROGRAMMING
(21CS107)
COURSE DESCRIPTION AND OBJECTIVE

This course is aimed to impart knowledge on basic concepts of C


programming language and problem solving through programming.
It covers basic structure of C program, data types, operators,
decision making statements, loops, functions and static data
structures. At the end of this course students will be able to design,
implement, test and debug modular C programs.
COURSE OUTCOMES
Upon completion of the course, the student will be able to achieve the following outcomes

No. Outcome
CO 1 Understanding of how to write simple, but complete, C programs
Identification of suitable data type for operands and design of expressions
CO 2
having right precedence.
Application of decision making and iterative features of C Programming
CO 3
language effectively.
CO 4 Selection of problem specific data structures and suitable accessing methods.
Design and development of non- recursive and recursive functions and their
CO 5
usage to build large modular programs.
Development of C programs that are understandable, debuggable,
CO 6
maintainable and more likely to work correctly in the first attempt.
Input Processing and Output
Input, processing and output
To design a solution, three major requirements are
there:

• Receive Input
• Process the data
• Produce output
Input, processing and output
• Input: Study the problem and identify the pieces of data.
• Process: Determine the calculations and/or other processes that must be
performed.
• Output: It will produce the results of the program’s calculations and/or other
processes.
The next step is writing the algorithm/pseudocode, or drawing it as a flowchart
Problem 1: Check the attendance percentage

Considering the above example, let’s break down the


task into steps:
Input – Roll No
Tasks to be preformed – Search for my Roll No
Output expected – Attendance Percentage
Problem 1: Check the attendance percentage
Instruction to a Friend:
1. Go to the University Notice Board.
2. Search for my Roll No on the board.
3. Check the percentage against my Roll no.
Problem 1: Check the attendance percentage
Instructions to the Computer:
1. Go to the University Notice Board.
2. Read the Roll No.
3. If this is my Roll no, see percentage and come back.
4. Read the next Roll no.
5. Repeat the above two steps until you find my Roll no.
Problem 2: Suppose Your Little Sister Asks
You How To Boil Water?
Let’s look at the 3 requirements for designing a solution for
this task:
• Input – Kettle, Water
• Tasks to be preformed (Process) – Fill up the kettle, boiling
water
• Output expected – Boiled water
Problem 2: Suppose Your Little Sister
Asks You How To Boil Water?
Instructions to a Friend:
1. Fill the kettle with water.
2. Place it on the stove and turn on the burner.
3. Turn off the burner when the water starts boiling.
Problem 2: Suppose Your Little Sister Asks You
How To Boil Water?

Instructions to the Computer:

1. Place the kettle under the tap. 6. Place the kettle on the burner
2. Turn on the tap. 7. Turn - on the burner.
3. Check if 90% of the kettle is filled. 8. Check if the water is 100 C
4. If not, repeat the above step. 9. If not, repeat the above step.
5. Turn off the tap. 10. Turn off the burner.
Problem 3: Check whether a person is
eligible to cast a vote or not
• Input: Person Age
• Process: Identify whether the person is Eligible to cast
a vote or not
• Output: Eligible or not
Problem 3: Check whether a person is eligible
to cast a Vote or not

1. Read Age
2. Check if age is greater than 18 then go to step
3 otherwise go to step 4
3. Display " Person is eligible to cast a vote"
4. Display "person is not eligible to cast a vote "
Problem 4: Convert Temperature
From Celsius To Fahrenheit

• Input: Temperature in Celsius


• Process: Convert temperature from Celsius to
Fahrenheit
• Output: Temperature in Fahrenheit
Problem 4: Convert Temperature
From Celsius To Fahrenheit

1. Read temperature in Celsius ‘c’


2. Convert the temperature from Celsius to
Fahrenheit
3. Display Fahrenheit temperature.
I want to know my Blood group
• Input: Blood samples
• Process: Clinical process (Blood sample is
mixed with antibodies against type A and
B blood)
• Output: Blood group
Procedure for Blood test to know the blood group

1. Go to the clinic for giving blood samples


2. At the time of sample collection lay your arm.
3. A card is put around your arm at the top which helps to
locate the nerve easily.
4. Then he/she will collect the blood sample
5. Process the collected sample
6. Identify the blood group
I want to prepare a Pizza

• Input: Ingredients (Flour, cheese, toppings, sauce,


woven, etc.…..)
• Process: Baking process
• Output: A crispy hot pizza
Procedure for pizza Making
1. Take the dough and roll it into a circle
2. Puff out the edge of the dough so the crust is thicker at the edge
3. Pre-heat oven to 250-260 degrees Centigrade
4. Put on the pizza sauce, cheese, and toppings
5. Put the pizza on the pizza stone in the oven
6. Bake for 30 minutes / until pizza is crispy and golden brown.
ALGORITHM
&
PSEUDO CODE
Algorithm
• An algorithm is a set of instructions for solving a problem or
accomplishing a task.
For designing any solution, the following has to be known:
• Input
• Tasks to be preformed
• Output expected
Characteristics of Algorithm
Well Defined
Input

Clear and
Well Defined
Unambiguous
Output

Characteristics

Language Finiteness
Independent

Feasible
CHARACTERISTICS OF ALGORITHM

• Input: An algorithm may or may not require input


• Output: Each algorithm is expected to produce at least one result
• Finiteness: If the instructions of an algorithm are executed, the algorithm should terminate
after finite number of steps.

• Feasible: The algorithm must be simple, generic and practical, such that it can be executed
upon will the available resources. It must not contain some future technology, or anything.

• Language Independent: An algorithm should have step-by-step directions, which should be


independent of any programming code.

• Clear & Unambiguous: Algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one meaning.
Types of Algorithms

We have three type of Algorithms:

1. Sequence
2. Selection
3. Repetition
Types of Algorithms
Sequence: Begin

Statements are executed in a specified


First Task
order. No statement is skipped and no
statement is executed more than once.
Second Task

Third Task

Done
Selection:
Based upon the condition statements will execute.
Statement is executed when the condition is true and ignored
when it is false e.g if, if else, switch structures.

true
Condition

false
Statement(s)

rest of Code
Repetition:
• In this structure the statements are
executed more than one time. It is also
known as iteration or loop Initialization

• Ex: while loop, for loop do-while loops etc.


false
Condition

true
Loop Body

Update
Design a solution for performing addition on two numbers

• Input: Two numbers


• Process: Add two numbers and store the result
• Output: Display the sum of two numbers
Design a solution for performing addition on two numbers

Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result
to sum. ( sum←num1+num2 )
Step 5: Display sum
Step 6: Stop
I want to Cook Rice in electric rice cooker

• Input: Rice, water and Electric rice cooker


• Process: Cook the rice
• Output: Cooked rice
I want to Cook Rice in electric rice cooker
Step 1: Start
Step 2: Take 1 cup of rice in to the vessel.
Step 3: Add 2 cups of water to the rice.
Step 4: Place the vessel into an electric rice-cooker.
Step 5: Close the lid of the cooker and switch it on.
Step 6: Wait until the indicator light of the rice-cooker
turns off
Step 7: Stop
What is the process for making a call to your
friend

• Input: Phone, Friend phone number


• Process: Make a call
• Output: Friend is on the call
What is the process for making a call to your
friend
Step 1 : Start
Step 2 : Pick up the phone.
Step 3 : Search for friend’s phone number in the contact list
Step 4 : Select the number and dial it by clicking on the dial
button.
Step 5 : Wait for the network to connect.
Step 6 : If connection is successful, you will hear the dialer
tone,
Step 7 : End
What is the process for generating Electricity bill?

• Input: Number of units, Slab rate


• Process: Calculate the bill
• Output: Generate the Electricity bill
What is the process for generating Electricity bill?

Step 1: Start
Step 2: Read number of units consumed
Step 3: Calculate bill amount based on slab rate
(b= u * slab rate)
Step 4: Generate the bill.
Step 5: Stop.
Your grand father is seeking help in withdraw
cash from ATM

• Input: ATM card, PIN number


• Process: Process the card request
• Output: Withdraw the cash and collect the bill,
and card
Your grand father is seeking help in withdraw
cash from ATM
Step 1: Start
Step 2: Go to the ATM
Step 3: Insert your card into the machine
Step 4: Select Language
Step 5: Enter PIN number
Step 6: Choose “Withdraw” and enter required Amount
Step 7: Take the cash, slip and card.
Step 8: Stop.
Your little brother is asking you, how to prepare a
cup of tea

• Input: Kettle, Tea Leaves, Milk, Water and sugar


• Process: Add all the ingredients one after
another and prepare tea
• Output: Tea
Your little brother is asking you, how to prepare a
cup of tea
Step 1: Fill the kettle with water.
Step 2: Add tea leaves and sugar to the kettle.
Step 3: Plug the kettle into the power point and switch it on.
Step 4: If the water in the kettle is boiled, then go to step 5.
Step 5: Switch off the kettle.
Step 6: Pour some milk into the kettle.
Step 7: Tea is ready
Pseudocode
• Pseudocode (which means fake code, because its not really
programming code) specifies the steps required to
accomplish the task.
• Pseudocode is a type of structured English that is used to
specify an algorithm.
• Pseudocode cannot be compiled nor executed, and there
are no real formatting or syntax rules.
Find factorial for the given number
Algorithm Pseudocode
START procedure to find factorial(number)
Step 1: Read integer ‘a’ FOR value = 1 to number
Step 2: Assign value to the factorial = factorial * value
variable Value = value-1
END FOR
Step 3: Multiply each digit from
‘a’ to 1 and store the result in f DISPLAY factorial
Step 4: Display ‘f’
end procedure
STOP
FLOWCHART
Flowchart
• Flowchart is agraphical representation to solve a problem in
step by step manner.
• Flowchart is used to indicate flow of information.
• Instead of descriptive steps (Algorithm), it uses pictorial
representation for every step.
Limitations:

 Flow charts are difficult to modify (redrawing)


 Translation of flow chart into computer program is always not easy.
Advantages:

 Communication: Flowcharts are better way of communicating the logic


of a program.
 Effective analysis: With the help of flowchart, problem can be
analysed in more effective way therefore reducing cost and wastage
of time.
Flowchart Symbols
Terminal

• The beginning or ending of a program


• It is single directional i.e. only one flow line(either incoming line or
outgoing line) can be connected with terminal symbol.
Input/Output

• The parallelogram is used to represent input and output


operation.
• It is having two flow lines, i.e., incoming and outgoing lines.
Process

• The rectangle symbol is used to represent mathematical


calculations / process.
• It is having two flow lines, i.e., incoming and outgoing lines.
Flowline

• The arrow symbol is used to establish a logical flow between


symbols.
Decision

• The rhombus symbol is used to check the condition i.e., decision.


• It is having single flow line for input and two flow lines for output.
Connector

• The circle is used to connect two portions of flowcharts in different


pages.
• It is having single flow line (either incoming line or outgoing line)
Example flowchart

Parallelograms
Ovals Input symbols
Terminal
Symbols
Processing
Symbol
Parallelograms
Output symbols
Types of Flowcharts

Sequential
flowchart
Selection
flowchart
Iterative
flowchart
Sequence Structure

• A set of statements that execute in the order that they appear


is called a sequence structure.
Displaying Output
• The most fundamental thing that we can do in a program is to
display a message on the computer screen.
• As we know that, all high-level languages provide a way to display
the output.
• Here we use the word Display to write pseudocode statements for
displaying output on the screen.
• Here is an example: Display “Welcome to the Course"
How can we ‘Display a Simple message’

Pseudocode1:
Display “Welcome to the Course”
Draw a flowchart to display a message

Start

Display ”Welcome to the


Course”

Stop
Suppose your instructor tells you to write a pseudocode
program that displays your Name and address on the
computer screen.

• Input: Name, Address

• Task: Display

• Output: Name, Address


Suppose your instructor tells you to write a pseudocode
program that displays your Name and address on the
computer screen.

Pseudocode:
Display “Ravi”
Display “Guntur”
Draw a flowchart to display Name and address

Start

Display Ravi

Display Guntur

Stop
Input, Output and Variables

Computer programs typically perform the following


three-step process:
1. Receive Input.
2. Process the input.
3. Output is produced.
Let us discuss with an example:
Your father wants to pay salary to his workers. He need to
calculate the ‘Total Pay’ every time.
Task: Pay calculator
Input: No. of hours worked (n) and Hourly pay rate (h).
Process: ???
Total Pay (p) = n * h
Output: Total Pay (p).
PSEUDOCODE:
1. Display “No. of hours worked:”
2. Input n
3. Display “Hourly pay rate:”
4. Input h
5. Calculate Total Pay
1. Total Pay (p) = n * h
6. Display “Total Pay ”
7. Output p
Flow chart for Pay Calculator
Start

Read No. of hours


worked: n

Read Hourly pay


rate: h

Total Pay (p) = n * h

Display Total Pay P

Stop
Your little sister wants to add two numbers

• Input: Two numbers

• Task: Perform calculation on those two numbers

• Output: Sum of the two numbers


PSEUDOCODE:
1. Display “Enter two values: n1, n2”
2. Input n1, n2
3. Calculate Sum
1. Sum= n1+n2
4. Display “Sum is ”
5. Output sum
3. Draw a flowchart to add two numbers

Start

Sum=0

Input n1 and n2

Sum = n1+n2

Display Sum

Stop
Calculate the area of a Triangle

• Input: Breadth, Height

• Task: Perform calculation on those two values

• Output: Area of a Triangle


PSEUDOCODE:
1. Display “Enter Breadth: b”
2. Input b
3. Display “Enter Height: h”
4. Input h
5. Calculate Area ‘a’
1. a = (1/2) * b * h
6. Display “Area of Triangle is: ”
7. Output a
Flowchart for Area of Triangle
Start
Enter
b and h
INPUT
b and h
Area=
(1/2)*b*h.
Print
area

Stop
Calculate Simple Interest

• Input: Principal amount, Rate and Time

• Task: Calculate Interest

• Output: Simple Interest


PSEUDOCODE: 1. Display “Enter Principal Amount: p”
2. Input p
3. Display “Enter Rate: r”
4. Input r
5. Display “Enter Time: t”
6. Input t
7. Calculate Simple Interest ‘I’
1. I = (p * r * t) /100
8. Display “Simple Interest ‘I’ ”
9. Output I
Flowchart for Simple Interest

Start
Input
P,T,R
I=
(P*T*R)/100.
Print value of
I

Stop
Calculate sales price of an item after discount

• Input: Original Price

• Task: Sales Price

• Output: Price of an Item


PSEUDOCODE:
1. Display “Enter the item’s original price: op”
2. Input op
3. Calculate Sales Price (sp)
1. Set discount = op*0.2
2. Set sp =op – discount
4. Display “Sales Price: ”
5. Output sp
Flowchart for sales price:
Start

Display “Enter the


item’s original price”

Input op

Set discount =op * 0.2

Set sp = op-discount

Display sp

Stop
IDENTIFY THE DATA TYPES
Calculate the Average of three tests

• Input: Three test’s marks (t1,t2,t3)

• Task: Calculate average of three test’s

• Output: Average Marks


PSEUDOCODE:
1. Declare Integer t1,t2,t3
2. Declare Real avg
3. Display “Enter three test’s marks: t1,t2,t3”
4. Input t1,t2,t3
5. Calculate Average of three test’s (avg)
1. Set avg = (t1+t2+t3)/3
6. Display “Average marks of three test’s:”
7. Output avg
Flowchart for calculating the average marks
Start

Display “Enter the first test


score” Input test3

Input test1 Set average =


(test1+test2+test3)/3
Display “Enter the second
Display “The average
test score”
score is”, average
Input test2 Stop
Display “Enter the third
test score”
Iteration Structure

• Iteration or looping is depicted by a combination of


process and decision symbols placed in proper
order.
• Here flow lines are used to connect the symbols and
depict input and output to this structure.
Iteration Structure
Start

Process 1

Process Y Process x

False
Condition

True
Calculate the sum of first 50 numbers.

• Input: 1 to 50

• Task: Calculate the sum of first 50 numbers.

• Output: Sum
PSEUDOCODE:
1. Declare Integer sum, N
2. Set sum=0, N=0
3. N=N+1
4. Sum=Sum+N
5. If N is less than or equal to 50 then goto step 3,
otherwise goto step 6
6. Display “Sum of first 50 numbers:”
7. Output sum
Flowchart for calculating the sum of first 50 numbers.
Start

Sum=0

N=0

N=N+1

Sum=Sum+ N
No
while
N>=50?
Yes
Print Sum

Stop
Decision Structure

• Selection of a process or step is depicted by the decision


making and process symbols.
• Only one input indicated by one incoming flow line and one or more
output flowing out of this structure exists.
• The decision symbol and the process symbols are connected by flow
lines.
Decision Structure

True False
Decision

Process 1
Process x
Calculating the bonus.

• Input: salary

• Task: Calculate the Bonus.

• Output: Bonus
PSEUDOCODE:
1. Declare Integer sal
2. Declare Real bonus
3. If sal is greater than or equal to 5000 then goto
step 4, otherwise goto step 5
4. Set bonus = 0.05*sal
5. Set bonus = 250
6. Display “Bonus:”
7. Output bonus
Flowchart for calculating the bonus.
Start

Input Salary

False True
Is Salary>=5000

Bonus=250 Bonus=0.05*Salary

Print
bonus

Stop
GENERATIONS OF PROGRAMMING LANGUAGES
There are five generation of Programming languages. They are:
First Generation Languages:
These are low-level languages like machine language.
Second Generation Languages:
These are low-level assembly languages used in kernels and hardware drives.
Third Generation Languages:
These are high-level languages like C, C++, Java, Visual Basic and JavaScript.
Fourth Generation Languages:
These are languages that consist of statements that are similar to statements in the
human language. These are used mainly in database programming and scripting.
Example of these languages include Perl, Python, Ruby, SQL, MatLab(MatrixLaboratory).
CONT..
Fifth Generation Languages:
These are the programming languages that have visual tools to develop a
program.
Examples of fifth generation language include Mercury, OPS5, and Prolog.

The first two generations are called low level languages. The next three
generations are called high level languages.
IMPORTANCE OF C
• C programming language is most popular programming language.
• C was created in 1972 by Dennis Ritchie at the Bell Labs in USA as a
part of UNIX operating system.
• C was also used to develop some parts of this operating system.
FEATURES OF C
• Programs Written in C are efficient and fast.
• C is highly portable this means that programs once written can be run on
another machines.
• Another important feature of C program is its ability to extend itself.
• A C program is basically a collection of functions that are supported by C
library. We can also create our own function and add it to C library.
• C language is the most widely used language.
STRUCTURE OF C PROGRAM
• A C program involves the following sections:
• Documentations (Documentation Section)
• Pre-processor Statements (Link Section)
• Global Declarations (Definition Section)
• The main() function
• Local Declarations
• Program Statements & Expressions
• User Defined Functions
DOCUMENTATION SECTION / COMMENTS –
• They are two types of comments:
• Single – line comment.
• Multi – line comment.

• Single – line Comment: It starts with two forward slashes (i.e


//) and is automatically terminated with the end – of the line.
The first line of our program is a single line comment.
• Multi – line Comment: It starts with /* and terminates with */. It
is used when multiple lines of text are to be commented.
PRE-PROCESSOR DIRECTIVE SECTION
The following points must be remembered while writing a pre-processor
directives:
• The pre-processor directive should always start with hash symbol (#).
• The # symbol should be the first non-white space character in a line.
• It will terminated with the new line character not with semicolon.
• Pre-processor directives are executed before the compiler compiles the
source code.
SOME IMPORTANT PRE-PROCESSOR
DIRECTIVES:
#define Substitutes a pre-processor Macro (constant)
#include Inserts a particular header file from another file.

#ifdef Returns true if the macro is defined.


#ifndef Returns true if the macro is not defined.
#if Tests if a compile time condition is true.
#else The alternative of #if.
#elif #if and #else in one statement.
#endif Ends pre-processor conditional statement.

#error Prints error message on console output device.


GLOBAL DECLARATION SECTION-
• In this section global variables and user defined functions are
declared before main().
• These functions can be accessed by the all used defined functions
including main().
• If a user defined function or a variable is not declared in this
section it will not accessed by the remaining functions.
FUNCTION SECTION –
This section is mandatory. This section have one or more functions. A
function named main() is always required. Every function consists of two
parts:
• Header of the Function.
• Body of the Function.
Header of the Function:
• The general form of the header of the function is:
• [return-type] function_name([argument_list])
• The terms enclosed within square brackets are optional.
BODY OF THE FUNCTION:
• The body of a function consists of a set of statements enclosed
with in braces{}. And these statements are of two types:
• Non – Executable Statements (Ex – Declaration Statements)
• Executable Statements (Ex – Function call statements like printf()..)
• It is possible that no statement present within the braces. In such
case the program produces no output on execution.
• If any statements present in the function non-executable statements
should present prior to the executable statements.
A SIMPLE PROGRAM THAT PRINTS HELLO
WORLD!
// Comment: First C program
#include<stdio.h>
main()
{
printf(“Hello World! \n”);

}
Output:
Hello World!
COMPILE AND EXECUTE A C PROGRAM
• Open a text editor and add the above mentioned code.
• Save the file as hello.c.
• Open command prompt and go to the directory where we have saved the file.
• Type cc file_name.c and press enter to compile our code.
• If there are no errors in our code, the command prompt will take you to the next line and
would generate a.out executable file.
• Now type ./a.out to execute our program.
• Finally we will get output.
• $cc hello.c
• $./a.out
• Hello world!

You might also like