Unit 1-PSC
Unit 1-PSC
I- S E M
1
UNIT I – INTRODUCTION TO C AND CONTROL
STATEMENTS
Basic Computer Organization
Problem Solving Techniques
Algorithm, Flowchart, Pseudocode
Introduction to C programming
Lifecycle of a C program
Features of C
Keywords, Variables, Scope - Declaring, assigning and
printing variables
Coding Standard
Data Types: integer, float and character types
Constants–Operators – Bitwise Manipulations
Expression Evaluation – Preprocessor
2
Basic Computer Organization
The main component of basic organization of a computer system is Central
Processing Unit, Memory Unit(MU) and Input-Output Unit.
Central Processing Unit: CPU is a brain of computer. It controls the
computer system. It converts data to information.
Arithmetic and Logic unit: This is a part of CPU. It consists of two units.
One is arithmetic unit and another one is logic unit.
Input and Output unit: This unit controls input and output devices. Input
devices are keyboard, mouse etc and output devices are printer, monitor,
plotter, etc.
3
Functionalities of a Computer
Step 1 − Takes data as input.
Step 2 − Stores the data/instructions in its memory and uses them as required.
Step 3 − Processes the data and converts it into useful information.
Step 4 − Generates the output.
Basic Computer Organization-CPU and I/O
Unit
Central Processing Unit
CPU is considered as the brain of the computer CPU performs all types of
data processing operations.
It stores data, intermediate results, and instructions (program).It controls the
operation of all parts of the computer.
Input Devices
Keyboard, Mouse, Joy Stick, Light pen, Track Bal, Scanner, Graphic Tablet,
Microphone, Magnetic Ink Card Reader(MICR) etc.
Output Devices
Monitors ,Graphic Plotter ,Printer.
Basic Computer Organization-Memory Unit
Memory
It is used to store data and instruction.
No universal approach
7
Example-Problem solving
It’s raining and you need to go to the store – Umbrella, Car, Bus or friend.
8
Steps or Phases of problem solving
9
Steps or Phases of problem solving
1. Analyzing the problem
• Clear understanding of the problem
• Read and analyze the problem statement carefully
• What are the inputs that our program should accept and the outputs that it
should produce
3. Coding/Implementation
• Converting the algorithm into the format which can be understood by
• the computer to generate the desired solution
• Different high level programming languages can be used for
• writing a program
10
Steps or Phases of problem solving
4.Testing and Debugging
The program should meet the requirements of the user.
It must respond within the expected time of the user.
It should generate correct output for all possible inputs.
Testing methods like unit or component testing, integration
testing, system testing, and acceptance testing can be employed.
The errors or defects found in the testing phases are debugged or
rectified and the program is again tested
11
Algorithm
Algorithm is an ordered sequence of finite, well defined, unambiguous
instructions for completing a task.
12
Algorithm-Selection Statement
Example 1 Algorithm to check whether the given number is odd
or
even
Step1: Start.
Input Number, i.e Num1.
Step2: If Num1 % 2==0. If yes go to Step 4.Else go to Step
6. Print number is even.
Step3: Go to Step 7.
Print number is odd.
Step4: End.
13
Step5:
Algorithm Example- Lemon Juice
Step 1: First, we will cut the lemon into half.
Step 2: Squeeze the lemon as much you can and take out its juice in a
container.
Step 3: Add two tablespoon sugar in it.
Step 4: Stir the container until the sugar gets dissolved.
Step 5: When sugar gets dissolved, add some water and ice in
it.
Step 6:
Store the juice in a fridge for 5 to
Step 7:
minutes. Now, it's ready to drink.
14
Algorithm-Sequence
Instructions are executed in the order as they are written
•In short, sequence is a series of steps that are followed one after
the other
15
Algorithm-Example
Example 1: Algorithm to find sum of two
numbers
Step 1: Start
Step 2: Read two numbers Num1 and Num2
Step 3: Calculate sum, i.e. Total=Num1+Num2
Step 4: Display Total
Step 5: Stop
Example 2: Algorithm to calculate the area of
circle
Step 1: Start
Step 2: Read input ‘r’ as radius of circle
Step 3: Calculate area, i.e.
Step 4: Area=3.14*r*r Display Area
Step 5: Stop 11
Algorithm-Example
17
Algorithm-Selection Statement
Example 2: Algorithm to find greatest among three
numbers
Step 1: Start.
Step 2: Read the three numbers A, B, C.
Step 3: Compare A and B. If A is greater, store A in MAX, else
store B in MAX.
Step 4: Compare MAX and C. If MAX is greater, output “MAX is
greatest” else output “C is greatest.
Step 5: Stop.
18
Algorithm-Repetition or
Iteration
Example: Algorithm to print all natural numbers upto
‘n’
Step 1: Start
Step 2: Get ‘n’
Step 3: value.
Step 4: Initialize i=1
Step 5: If (i<=n) go to step 5 else go to step 7
Step 6: Print i value and increment i value by
Step 7: 1 Go to step 4
Stop
19
Algorithm-Selection Statement
20
Algorithm-Characteristics
1. Precision — the steps are precisely stated or defined.
2. Uniqueness — results of each step are uniquely defined and only
depend on the input and the result of the preceding steps.
3. Finiteness — the algorithm always stops after a finite number of
steps.
4. Input — the algorithm receives some input.
5. Output — the algorithm produces some output.
Algorithm Representation
There are two common methods of representing an algorithm —
1.Flowchart and 2.Pseudocode
21
Algorithm-Qualities
1. Accuracy
Algorithm should provide accurate result than
others.
2. Memory
It should require minimum computer memory.
3. Time
Lesser the time taken better the quality.
4. Sequence
Procedure of an algorithm must be sequential form.
5. Result
It should lead to correct result each time.
22
Flowchart
1. A flowchart is a visual representation of an algorithm.
2. A flowchart is a diagram made up of boxes, diamonds and other
shapes, connected by arrows.
3. Each shape represents a step of the solution process and the arrow
represents the order or link among the steps.
23
Flowchart-Guide Lines
The flowchart should be clear, neat, and easy to follow.
The usual direction of the flow of a procedure or system is from left to right
or top to bottom.
Only one flow line should emerge from a process symbol.
24
Flowchart & Algorithm -
Example
Write an algorithm to find the square of a number.
Before developing the algorithm, let us first identify the input, process and
output:
Input: Number whose square is required
Process: Multiply the number by itself to get its square
Output: Square of the number
Algorithm:
Step 1: Input a number and store it to num
Step 2: Compute num * num and store it in square
Step 3: Print square
25
Flowchart - Example
26
Flowchart – Advantages &
Drawbacks
Advantages:
Drawbacks:
logic)
27
Pseudocode
A pseudo code (pronounced Soo-doh-kohd) is another way of representing an
algorithm.
It is considered as a non-formal language that helps programmers to write
algorithm. Written in the English language.
It is a detailed description of instructions that a computer must follow in a
particular order.
It is intended for human reading and cannot be executed directly by
the computer.
No specific standard for writing a pseudo code exists.
The word “pseudo” means “not real,” so “pseudocode” means “not real code”.
28
Rules for writing
pseudocode
1. Statements should be written in simple English and
should be programming language independent.
29
Pseudocode- Advantages &
Drawbacks
Advantages:
1. Since it is language independent, it can be used by
most
programmers.
2. It is easier to develop a program from a pseudocode than with
a flowchart.
3. Often, it is easy to translate pseudocode into a
programming language
4. Unlike flowcharts, pseudocode is compact and does not tend to
run
over many pages.
5. It's simple structure and readability makes it easier to modify.
Drawbacks:
6. It does not provide visual representation of the program's logic.
7. There are no accepted standards for writing pseudocodes.
8. Pseudocode cannot be compiled nor executed, and there are no
30
real formatting or syntax rules.
Pseudocode- Sequence control structure
Write an algorithm to display the sum of two numbers entered by
user, using both pseudocode and flowchart.
31
Pseudocode-Selection control structure
32
Pseudocode- Iterative control structure
33
Pseudocode- Iterative control structure
34
Pseudocode- Iterative control structure
35
Introduction to C
C is a middle-level structured oriented programming language used in
general purpose programming, developed by Dennis Ritchie at AT&T Bell
labs, USA between 1969 and 1973.
46
History of C
37
C COMPILATION PROCESS
C is a compiled language.
1. Editing
2. Compiling
3. Linking
4. Executing
1.Editing
The programming process starts with creating a source file that
consists
of the statements of the program written in C Language.
Editor is specially designed for writing the source code of C
programs. The source code is saved on the disk with an
extension .c
38
Structure of C program
39
Structure of C program
1. Documentation Section
- This is a comment block, which is ignored by the compiler. Comment can used
anywhere in program to add info about program or code block, which will be
helpful for developers to easily understand the existing code in the future.
e.g. /* */, //
2. Link Section
-This Section is the core part of the program in which compiler links
the inbuilt function from the system library.
e.g. # include < >
3. Definition Section
-In this part, we define a symbolic constant.
e.g. define PI = 3.14
4. Global Declaration
-When programmer wants to use some variables that are used in more than
one function. The global declaration section is used to define those variables that
are used globally within the entire program and is used in more than one function.
40
Structure of C program
5. Main( )
The main() is the main function where program execution begins. Every C
program must contain only one main function. This section contains two parts.
All the statements of these two parts needs to be terminated with semi-colon
(1) Declaration parts in which all variables and user defined functions are
declared.
The sub-program section deals with all user defined functions that are called from
the main(). These user defined functions are declared and defined usually after the
main() function.
41
42
43
44
45
Structured Programming
The programs generated using unstructured approach are meant for
simple and small problems.
If the problems gets lengthy, this approach becomes too complex and
obscure.
Using structured programming, a program is broken down into small
independent tasks that are small enough to be understood easily.
These tasks are developed independently, and each task can carry out
the specified task on its own, without help of any other task.
Structured Programming can be performed in two ways:
1. Procedural programming and
2. Modular programming
46
1. Procedural Programming
Procedural Programming divides the program into procedures,
which are also known as routines or functions,
These procedures are combined into one single location with the
help of return statements.
48
HLL &MLL
comparison
High Level Language Low Level Language
49
Lifecycle of a C Program
COMPILATION
51
LINKING
54
Object file and Executable file – A
comparison
55
Features of C Program
High level language
General-Purpose Language
Portable
Libraries with rich Functions (Built in functions) and
operators
Structured programming language / Modularity
Pointers – work with memories
Dynamic memory allocation
Compilation and execution is faster
Portability
Easy to Extend
Embedded systems – low power and memory requirement
Features of C Program
Procedural Language
Fast and Efficient
Modularity
Statically Type
General-Purpose Language
Rich set of built-in Operators
Libraries with rich Functions
Middle-Level Language
Portability
Easy to Extend
Features of C Program
Procedural Language
• In a procedural language, step by step predefined instructions are
carried out.
• C program may contain more than one function to perform a particular
task.
Fast and Efficient
• C programming language as the been middle-level language provides
programmers access to direct manipulation with the computer
hardware.
• It’s fast because statically typed languages are faster than dynamically
typed languages.
Features of C Program
Procedural Language
• In a procedural language, step by step predefined instructions are
carried out.
• C program may contain more than one function to perform a particular
task.
Fast and Efficient
• C programming language as the been middle-level language provides
programmers access to direct manipulation with the computer
hardware.
• It’s fast because statically typed languages are faster than dynamically
typed languages.
Features of C Program
Modularity
• The concept of storing C programming language code in the form of
libraries for future use is known as modularity.
• C language has its own library to solve common problems by using
header files.
Statically Type
C programming language is a statically typed where the type of
variable is checked at the time of compilation but not at run time.
General Purpose Language
C programming is used in various application as follows
Operating systems: Windows, Linux, iOS, Android, OXS
Databases: Oracle, MySQL, MS SQL Server etc.
Features of C Program
Rich set of built-in Operators
It is a diversified language with a rich set of built-in operators which
are used in writing complex or simplified C programs.
Libraries with rich Functions
63
Constants
A constant is a value assigned to the variable which will remain the same
throughout the program, i.e., the constant value cannot be changed.
Constant Example
65
Variable
sA variable in simple terms is a storage place which has some memory allocated
to it. A variable used to store some form of data.
Different types of variables require different amounts of memory, and have some
specific set of operations which can be applied on them.
Variable Declaration
Variable declaration refers to the part where a variable is
first declared or
introduced before its first use.
Syntax
type variable_list
Char c, float
salary, double d; 66
Variable Definition
Variable definition is the part where the variable is assigned a memory location
and a value. Most of the times, variable declaration and definition are done
together.
Constants 67
If you want to define a variable whose value cannot be changed, you can use the
Memory
Allocation
68
Datatypes
Each variable in C has an associated data type. Each data type requires
different amounts of memory
The memory size of the basic data types may change according to 32 or 64-
bit operating system.
69
Datatypes - Classification
70
Basic or Fundamental
datatypes
The five fundamental data types available in C are
integer, character, floating point numbers, double precision floating
point numbers and void.
71
1. Integer
Datatype
72
2. Float (Or) Real
Datatype
Floating point data type can hold real numbers such as: 2.34, -9.382,
and
5.0 etc.
A floating point variable is declared by using either float or
double
keyword.
73
3. Character
Datatype
Keyword char is used for declaring character type
variables.
74
4. Void Datatype
Void actually refers to an object that does not have a value of any
type.
Void data type is used in function definition it means that
function will not return any value.
75
76
User-defined Datatype
77
1. Enumeration Datatypes
Enumerated Datatypes are used to declare Integral constants in C programming
language so that the integral constant names are easy to remember and
maintain. The keyword enum is used to declare enumerated datatypes.
78
#include <stdio.h>
int main()
{
printf("int is %d bytes \n", sizeof(short int));
printf("long int is %d bytes \n", sizeof(long int));
printf("float is %d bytes \n", sizeof(float));
printf("double is %d bytes \n", sizeof(double));
printf("long double is %d bytes \n", sizeof(long double));
printf("char is %d bytes \n", sizeof(char));
return 0;
} 79
#include <stdio.h>
#include <limits.h>
int main()
{
return(0);
}
80
#include <stdio.h>
#include <limits.h>
int main()
{
Output:
The maximum value of float = 3.4028234664e+38
The minimum value of float = 1.1754943508e-38
82
2.Identifiers
Identifiers in C are used for naming variables, functions, arrays, structures,
etc. Identifiers in C are the user-defined words.
It can be composed of uppercase letters, lowercase letters, underscore, or
digits, but the starting letter should be either an underscore or an alphabet.
Rules:
1. The first character of an identifier should be either an alphabet or an
underscore, and then it can be followed by any of the character, digit, or
underscore.
2. It should not begin with any numerical digit.
3. In identifiers, both uppercase and lowercase letters are distinct. Therefore,
we can say that identifiers are case sensitive.
4. Commas or blank spaces cannot be specified within an identifier.
5. Keywords cannot be represented as an identifier.
6. The length of the identifiers should not be more than 31 characters.
7. Identifiers should be written in such a way that it is meaningful, short, and
easy to read.
83
2.Identifiers-Example
84
3. Strings in C
Strings in C are always represented as an array of characters having null
character '\0' at the end of the string.
This null character denotes the end of the string.
Strings in C are enclosed within double quotes, while characters are enclosed
within single quotes.
The size of a string is a number of characters that the string contains.
char a[7] = “eshwar"; // The compiler allocates the 7 bytes to the 'a' array.
char a[] = “eshwar"; // The compiler allocates the memory at the run time.
85
4. Character
Constants
86
4.Character
Constants
87
5.Special characters
1. Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
2. Simple brackets ( ): It is used in function declaration and function calling.
For example, printf() is a pre-defined function.
3. Curly braces { }: It is used in the opening and closing of the code. It is used
in the opening and closing of the loops.
4. Comma (,): It is used for separating for more than one statement and for
example, separating function parameters in a function call, separating the
variable when printing the value of more than one variable using a single
printf statement.
5. Hash/pre-processor (#): It is used for pre-processor directive. It basically
denotes that we are using the header file.
6. Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.
88
Input and Output statements in C
89
Input and Output statements in C
C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input
and output.
The scanf() function is used for input. It reads the input data from the
console/Keyboard
Syntax:
Note that the ampersand (&) before the variables in the scanf( ) function is a
must.
& is an ‘Address of’ operator.
It gives the location number used by the variable in memory.
When we say &a, we are telling scanf( ) at which memory location should
it store the value supplied by the user from the keyboard.
90
Format string or
specifier
91
Example
Note that a blank, a tab or a new line must separate the values supplied to
scanf( ).
Note that a blank is created using a spacebar, tab using the Tab key and new
line using the Enter key 91
Rules for writing Scanf statement
1. The control string must be preceded with (%) sign and must be
within quotations, i.e., the address of variable should be passed.
2. If there is an number of input data items, items must be separated by commas
and must be preceded with (&) sign except for string input.
3. The control string and the variables going to input should match with each
other.
4. It must have termination with semicolon.
5. The scanf() reads the data values until the blank space in numeric input or
maximum number of character have been read or an error is detected.
92
Example
•Integer:Input: scanf("%d", &intVariable); Output: printf("%d", intVariable);
93
94
Example
95
Rules for writing Printf statement
97
Scanf and Printf – Comparison
Scanf Printf
Used to accept data Used to display data
Control string and & operator is used Control string only used.
It end with semicolon It end with semicolon
Number of input specified with format
Number of input specified with format
String and enclosed within double
string and separated by commas.
quotes.
The Input variables are specified
The output variables are specified by
using Address operator (&) is
their name and separated by commas.
separated by commas.
98
Escape sequence in C
An escape sequence is a series of characters that represents a special character.
It begins with a backslash character (\), which indicates that the character(s) that
follow the backslash character should be treated in a special way.
C uses escape sequences within a format string to print certain special characters
Escape
sequence Description Example Output
\n New line printf("Hello \n World"); Hello
World
\t Horizontal tab printf("Hello \t World"); Hello World
\' Single quote printf("Hello \'World\' "); Hello 'World'
\" Double quote printf("Hello \"World\" "); Hello "World"
\\ Backslash printf("Hello \\World"); Hello \World
99
Unformatted I/O
100
Unformatted I/O
101
Unformatted I/O
#include <stdio.h>
int main ()
{
char c;
printf("Enter character: ");
c = getchar();
printf("Character entered: ");
putchar(c);
return(0);
}
Output:
Enter a character :
A
Character entered:
102
A
Operators in C
Operator is a Symbol that tells or instructs the Compiler to perform certain
Mathematical or Logical manipulations (Calculations).
Operators are used in a program to work on data and variables.
Operators are generally classified into different types. They are described
one below another as follows.
Classification of Operators
1. Arithmetic operators
2. Increment/decrement operators
3. Assignment operators
4. Relational operators
5. Logical operators
6. Conditional operator
7. Bitwise operators
8. Special operators
103
1.Arithmetic Operators
These operators are used to perform basic arithmetic operations
There are 5 arithmetic operators
* Multiplication
104
Arithmetic Operators
105
Sample Program
106
2.Increment and Decrement Operator
107
Example
108
3.Relational Operators
Relational operators are used to find the relationship between two
operands
Example
109
Relational Operators
110
Example
111
4.Logical Operators
These operators are used to perform logical operations like negation,
conjunction and disjunction.
The output of logical expression is either true(I) or false(0)
All non-zero values(ie. 1, -1,2, -2) will be treated as true
While zero value (i.e. 0) will be treated as false
Operator Meaning
&& And operator. It performs logical conjunction of two
expressions. (if both expressions evaluate to True, result is
True. If either expression evaluates to False, the result is
False)
113
5.Bitwise Operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
114
115
Binary Right Shift Operator (>>). The left operands value is moved right by
the number of bits specified by the right operand.
Binary Left Shift Operator (<<). The left operands value is moved left by the
number of bits specified by the right operand.
116
117
6.Conditional Operator
The conditional operator is also called ternary operator, it
takes
three operands.
Conditional operators are used for decision making in C
118
Example
119
7.Assignment Operators
Assignment operators applied to assign the result of an expression to a
variable. C has a collection of shorthand assignment operators.
The most common assignment operator is =
This operator assigns the value in right side to the left side
120
Example
121
Assignment Operators
122
Special Operators in C
C supports some special operators of interest such as
(1) sizeof:
It is a compile time operator and when used with an operand it
returns the number of bytes the operand occupies.
124
Types of Operators
125
Types of Operators
126
Operator precedence in C
Operator precedence determines which operator is evaluated first
when an expression has more than one operators.
For example:
Solve : 10+20*30
10 + 20 * 30 is calculated as
10 + (20 * 30) and not as (10 + 20) * 30
127
128
Operators
Associativity
Operators Associativity is used when two operators of same precedence
appear in an expression. Associativity can be either Left to Right
or Right to Left.
For example: ‘*’ and ‘/’ have same precedence and their associativity
is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) *
10”.
129
Operators precedence and
Associativity
130
Operators precedence and
Associativity
131
Expression Evaluation
An expression is evaluated based on the precedence and associativity of the
operators in that expression.
Example
10 + 4 * 3 / 2
•In the above expression, there are three operators +, * and /.Among these three
operators, both multiplication and division have the same higher precedence and
addition has lower precedence.
•As multiplication and division have the same precedence they are evaluated
based on the associativity. The associativity of multiplication and division is left
to right. So, multiplication is performed first, then division and finally addition.
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
132
Pre-processor
“Preprocessor” is a process that reads the source code and performs
some operation before it is passed on to the computer.
Preprocessor directives are placed in the source program before
main
function.
All the preprocessor directives begin with the symbol #.
o Example:
#define PI 3.14
#define TRUE 1
o General format:
#define macro_name (parameter list) replacement_string
13
4
Macro substitution directive
13
5
File Inclusion directive
13
6
Compiler control directive
This directives are also called “conditional compilation”.
The directives used in the conditional compilation are #ifdef, #endif, #if,
#else, #ifndef.
13
7