0% found this document useful (0 votes)
32 views137 pages

Unit 1-PSC

Uploaded by

Rajvikash R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views137 pages

Unit 1-PSC

Uploaded by

Rajvikash R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 137

U 1 9 CS1 0 1 – P RO B L E M S O LV I N G U S I N G C

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.

Primary Memory/Main Memory:


Primary memory is computer memory that is accessed directly by the
CPU
Secondary Memory
 Secondary memory is computer memory that is non-volatile and
persistent in nature and is not directly accessed by a computer/processor.
 It allows a user to store data that may be instantly and easily
retrieved, transported and used by applications and services.
Problem Solving-Introduction
Definition: Problem solving is the process of identifying a problem,
developing
possible solution paths, and taking the appropriate course of action..

 No universal approach

 Explore all possible ways

 Arrive at one solution.

 A problem is subdivided into number of problems.

 Solution of sub-problems are combined to get a solution.

7
Example-Problem solving

 Stuck in traffic – alternatives to go to office on time

 Why is the baby crying? – feeding, diaper change, sleep, discomfort

 Recipe preparation for dinner

 Preparing for a science project

 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

2. Developing an Algorithm /Design


• An algorithm is a sequence of simple and easily understandable steps to
the solution.
• Flowchart is a diagrammatic representation of the algorithm.
e.g very well-written recipe for a dish with steps in making it.
• More than one algorithm is possible for a problem. we have to select
the most suitable solution

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.

 An algorithm is defined as “a step by step procedure for solving any


problem”.

 It is an English –like representation of logic which is used to solve the


problem.

 The algorithm is independent of any programming language.

 To accomplish a particular task, different algorithms can be written.


They differ by their time and space.

 The algorithm can be implemented in many different languages by using


different methods and programs.

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

• When an instruction is executed the execution control moves to


the next immediate step

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

Example 3: Algorithm to convert Fahrenheit to


Centigrade
Step 1: Start
Step 2: Read Fahrenheit F
Step 3: Calculate Centigrade C=(F-32)*(5/9)
Step 4: Print C
Step 5: Stop

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

 It tells about the logic of the problem solution, without any


implementational details

 It clearly reveals the flow of control during execution of the program

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:

1. Makes logic clear through visualization.


2. Effective analysis
3.Useful in coding – to develop error free coding and making the coding
process faster.
4. Proper testing and debugging- detection of errors
5. Appropriate documentation- can know details like what is the use of
program? And How to use it?

Drawbacks:

1.Complex and costly (Larger problems)

2.Difficult to modify (redrawing entire

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.

2. Steps must be understandable, and when the steps are followed,


they must produce a solution to the specified problem.

3. Capitalize keywords such as READ, PRINT, and so on.

4. Each set of instructions is written from top to bottom, with


only one entry and one exit.

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.

Pseudocode for the sum of two numbers will be:


INPUT num1
INPUT
num2
COMPUTE Result = num1 + num2
PRINT Result

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.

 C is a popular general purpose programming language


 The source code of Unix Operating System is coded in C
 C runs under number of operating system including
MS-DOS
 C programs are efficient, fast and highly portable, that is
programs written in one computer can be run on another
with little or no modification.
 C is a structured language
 Large programs are divided into small programs called
Functions
 It is easy for debugging, testing, and maintenance if a
language is structured one

46
History of C

37
C COMPILATION PROCESS
 C is a compiled language.

 There are four steps in creating a C Program

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.

(2)Execution part in which program logic and other process is done.


Two curly brackets “{…}” are used to group all statements together Or shows how
much the main() function has its scope.

6. Subprogram Section/ User defined function section

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.

 From the main or controlling procedure, a procedure call is used to


invoke the required procedure.

 Some of languages that fall in the category are C, COBOL, and


FORTRAN.

Example : Simple Bank Account App:

1. Creating an account for an individual (account)


2. Getting an account to deposit or withdraw
funds (getAccount, deposit, withdraw)
3. Transferring funds between two different accounts (transfer)
47
2. Modular Programming
 The programs coded with procedural paradigms usually fit
into a
single code file and are meant for relatively smaller programs.
 However, if the program gets large, then modular way
of programming is recommended.
 In case of modular programming, large programs are broken down into
a number of smaller programs units known as modules.
 Each module is designed to perform a specific function.
 A program, therefore divided into several smaller parts that interact
and build the whole program.

48
HLL &MLL
comparison
High Level Language Low Level Language

It is a user-friendly language as this It is a machine-friendly language


language is written in simple English Written with 0’s and 1’s
words
More time to execute. Faster
Needs assembler/interpreter to Needs Compiler to convert the
convert the assembly code into high-level language instructions
machine code into machine code
Debugging and maintenance are not Easier
easier

49
Lifecycle of a C Program
COMPILATION

 The process of converting of the source code into a machine


code is called compiling.
 The program that is used to convert source code into the machine
code is called compiler.
 It translates the source code into the object code.
 Object code is the intermediate form of the program.
 The file has an extension .obj
 Before creating object code compiler scans the source code for error.
 All the errors must be removed from the source code before
creating
the object code of the program.

51
LINKING

 A C Program may contain predefined routines and functions.


 These functions are contained in separate files.
These files are part of the C Compiler and are called library files or
runtime routines.
 In this step necessary libraries are linked to the object code. After
linking libraries, the executable file of the program is created.
If the source code uses a library function that does not exist, the linker
generates an error.
 If there are errors, the linker does not create the executable file.
 The executable file is created with the .exe extension.
 This is directly run on the computer system.
52
53
EXECUTION

 In this step program actually run on the computer system.

For example, in Windows OS, when the name of an executable file is


double clicked, the system loads the file into the computer memory and
executes it.

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

Robust libraries and functions in C help even a beginner coder to code


with ease.
Middle-Level Language
As it is a middle-level language so it has the combined form of both
capabilities of assembly language and features of the high-level
language.
Features of C Program
 Portability
It is a diversified language with a rich set of built-in operators which
are used in writing complex or simplified C programs.
 Easy to Extend
Programs written in C language can be extended by adding some more
features and operations to the main program.
C- Tokens
 They are the smallest individual element in a C program.
 “We cannot create a sentence without using words; similarly,
 We cannot create a program in C without using tokens in C”..
 They are the building block or the basic component for creating a program in C
language

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.

There are two ways of declaring constant:


 Using const keyword
 Using #define pre-processor

Constant Example

Integer constant 10, 11, 34, etc.


Floating-point constant 45.6, 67.8, 11.2, etc.
Octal constant 011, 088, 022, etc.
Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.
Character constant 'a', 'b', 'c', etc.
String constant "java", "c++", ".net", etc.
64
Keywords
 Keywords are reserved words whose meaning has already explained to
the
compiler.
 Keywords are also called as reserved words.
 They must be written in lower case.
 There are 32 keywords available in C.

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.

Upper and lowercase letters are distinct because C is case-sensitive

Variable Declaration
 Variable declaration refers to the part where a variable is
first declared or
introduced before its first use.

Syntax

type variable_list

Eg. Int a,b,c;

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.

Eg. Int a=10;


Int b=20;
Float salary=2000.0;
Double d=3000.0;
Rules for defining
variables
1.A variable can
have alphabets,
digits, and
underscore.
2.A variable name can start with the alphabet, and underscore only. It can’t start
with a digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword, e.g. int, goto , etc.

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

 C language supports both signed and unsigned literals.

 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.

 The following table depicts their size and range of values.

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.

 Example char test = ‘h’;

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.

Example: enum plug{on = 1, off = 0};

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()
{

printf("Maximum bits in a byte %d\n", CHAR_BIT);

printf("Minimum value for signed char %d\n", SCHAR_MIN);


printf("Maximum value for signed char %d\n", SCHAR_MAX);
printf("Maximum value for unsigned char %d\n", UCHAR_MAX);

return(0);
}

80
#include <stdio.h>
#include <limits.h>

int main()
{

printf("Minimum value of short int %d\n", SHRT_MIN);


printf("Maximum value of short int %d\n", SHRT_MAX);
printf("Maximum value of unsigned short int %d\n", USHRT_MAX);

printf("Minimum value of int %d\n", INT_MIN);


printf("Maximum value of int %d\n", INT_MAX);
printf("Maximum value of unsigned int %ld\n", UINT_MAX);

printf("Minimum value of long int %ld\n", LONG_MIN);


printf("Maximum value of long int %ld\n", LONG_MAX);
81
return(0);
#include <stdio.h>
#include <float.h>
int main ()
{
printf("The maximum value of float = %.10e\n", FLT_MAX);
printf("The minimum value of float = %.10e\n", FLT_MIN);
return 0;
}

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.

 Now, we describe the strings in different ways:

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.

char a[7] = {‘e',‘s',‘h',‘w',‘a',‘r‘,'\0'}; // String is represented in the form


of characters.

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.

7. Tilde (~): It is used as a destructor to free memory.


8. Period (.): It is used to access a member of a structure or a union.

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:

scanf (“format string”, &arg1, &arg2, …..););

 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);

•Float:Input: scanf("%f", &floatVariable); Output: printf("%f", floatVariable);



•Character:Input: scanf("%c", &charVariable); Output: printf("%c", charVariable);

93
94
Example

95
Rules for writing Printf statement

1. Place appropriate heading in the output.


2. The variables must be separated by commas, and need not be
preceded with ‘&’ sign.
3. The control string and the variables must match in their order.
4. The control string must be in quotations and there we can also use
any other text to print with data.
5. Provide blank space in between the numbers for better readability.
6. Print special messages wherever required in output.

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

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


printf("Enter character: "); c = getchar();
printf("Character entered: "); putchar(c);
return(0);}

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

Operator Meaning of Operator

+ Addition or unary plus

- Subtraction or unary minus

* Multiplication

/ Division (returns the quotient)

% Remainder after division (modulo division)

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

 The output of relational expression is either true (I) or false (0)

 Relational operators mainly used for comparison of operands

Example

 a>b if a is greater than b, then a>b returns 1 else returns 0

 The 2 operands may constants, variables or expressions

 There are 6 relational operators

109
Relational Operators

Operator Meaning of Operator Example

> Greater than 5 >3 returns true (1)

< Less than 5<3 returns false(0)


>= Greater than or equal to 5>=3 returns true (1)
Less than or equal 5<=3 returns false(0)

== Equal to 5==3 returns false(0)


!= Not equal to 5!=3 returns true(1)

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)

|| Or operator. It performs a logical disjunction on two


expressions. (if either or both expressions evaluate to True,
the result is True)

! Not operator. It performs logical negation on an expression.


112
Example

113
5.Bitwise Operators

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

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.

 Sizeof operator is usually used to determine the lengths of arrays


and structures when their sizes are not known to programmer

& - Returns the address of a memory location.


123
Special operators

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.

 The operators at the higher level of precedence are evaluated first.

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 #.

Rules for writing preprocessor directive


o It should begin with # symbol.
o Semicolon is not needed.
o Only one directive can appear on a line.

Types of preprocessor directive


o Macro substitution directive
o File inclusion directive
o Compiler control directive
o Other directives 13
3
Macro substitution directive

1.Macro substitution without argument


.
o General format:
#define macro_name replacement_string

o Example:
#define PI 3.14
#define TRUE 1

Macro substitution with argument

o General format:
#define macro_name (parameter list) replacement_string

13
4
Macro substitution directive

13
5
File Inclusion directive

 This directive is used to include the content of a file into source


code of the program.

 # include “file name” (or) #include <file name>

 Where, #include- preprocessor directive

File name- name of the file to be included into source code


 Example:
 #include<stdio.h>
 #include ”example.c”
 #include<math.h>

13
6
Compiler control directive
 This directives are also called “conditional compilation”.

 A portion of source code may be compiled conditionally using


the
conditional compilation directive.

 The directives used in the conditional compilation are #ifdef, #endif, #if,
#else, #ifndef.

13
7

You might also like