0% found this document useful (0 votes)
12 views185 pages

21CSS101J - Unit1 - Updated 2

The document provides an overview of programming languages, their evolution, and the problem-solving process using programming. It outlines the history of programming, categorizes programming languages, and details the steps for effective problem-solving and algorithm design. Additionally, it discusses the importance of comments in C programming and the structure of a C program.
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)
12 views185 pages

21CSS101J - Unit1 - Updated 2

The document provides an overview of programming languages, their evolution, and the problem-solving process using programming. It outlines the history of programming, categorizes programming languages, and details the steps for effective problem-solving and algorithm design. Additionally, it discusses the importance of comments in C programming and the structure of a C program.
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/ 185

SRM INSTITUTE OF SCIENCE AND TECHNOLOGY

Kattankulathur
SCHOOLF OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit : I
Session title: Evolution and Problem Solving
Session Outcome:
By the end of this session, learners will be able to:
i)Exhibit knowledge regarding evolution of programming languages
ii) Highlight the steps involved to solve a problem with the help of computer

Prepared by: Dr. K. Vijaya, Associate Professor/CTECH.


12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 1
Programming​

• Programming has its origin in the 19th century, when the first “programmable” looms
and player piano scrolls were developed.​

• This followed the punch cards encoded data in 20th century that used to direct the
mechanical processing. In the 1930s and early 1940s lambda calculus remained the
influential in language design.​

• In 1940’s the modern computers have been introduced and programming languages
were developed.​

• The first high-level programming language to be designed for a computer was


Plankalkül, developed for the German Z3 by Konrad Zuse between 1943 and 1945.​
12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 2
Ref: https://www.slideshare.net/jxyz/a-brief-history-of-programming-42780183​
History of Programming​
• 1882-1843: First Computer Program – Ada Lovelace​
• 1890: Census Data on Punched cards – Herman Hollerith​
• 1943-1945: First High Level Programming Language: Konrad Zuse​
• 1949: Short Code (Electronic Computer) – John Mauchly​
• 1952: Manchester Mark 1 (Compiled) – Alick Glennie​
• 1957: FORTRAN (Numeric and Scientific) – John Backus​
• 1959: COBOL (Business computing – US Defence) – Short Range Committee​
• 1964: BASIC (Simplicity – Games) – John George Kenny and Thomas Eugene Kurtz
• 1970: ​PASCAL – Niklaus Wirth​
• 1970: C – Dennis Ritchie
• 1980: ADA – Jean Ichbiah​
• 1983: C++ – Bjarne Stroustrap​
• 1983: Objective C – Brad Cox and Tom Love​
• 1991: Python – Guido Van Rossum​
• 1993: Ruby – Yukihiro Matsumoto​
• 1994: Java – James Gosling​
• 1995: PHP – Rasmus Lerdorf​
• 1996: Javascript – Brenden Eich​​
12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 3
Ref: https://www.slideshare.net/hyunshar/history-of-programming?next_slideshow=1​
Programming Languages - Category​
• Machine Language: Instructions written in Binary Language​
i.e. with 0’s and 1’s only.​

• Assembly Language: Instructions written using pneumonic


codes which would be converted to 0’s and 1’s using
assemblers.​

• High Level Language: Instructions written using English like


statements, which would be converted to 0’s and 1’s using
compilers or interpreters.​

12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 4


Image Source: http://www.dfanning.com/programming-coding-faq/​
Generations of Languages​
First Generation Language (1GL): Machine Language​
Second Generation Language (2GL):Assembly Language​
Third Generation Languages (3GL): High Level
Languages – Flow-Matic, COBOL, FORTRAN, BASIC,
PASCAL, LISP, ALGOL, Java and many more.​
Fourth Generation Languages (4GL): Program generating
languages​– Perl, Ruby, Python and Matlab.​
Fifth Generation Languages (5GL): Graphical Interface to
Create Language -- Mercury, Prolog and OPS5.​

12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 5


Image Source: https://windowsground.com/generations-of- programming-language-and-examples/​
12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 6
Problem Solving​
• Process of transforming the
description of the problem into a
solution. ​
• Knowledge of the problem domain​

• Use appropriate problem solving


strategies, tools and techniques ​

12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 7


Image Source: https://www.facebook.com/programmingandproblemsolving/​
Steps to Solve Problem Using
Programming​
• Understand the problem correctly​
• Read more than once​

• Explain to someone else​

• Ask related question​

• Analyze, divide and Assess​


• Analyse and process information about the problem​

• Break it, if necessary​

• Try to solve manually and note the steps​

• Fine tune the steps by using sample inputs​


12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 8
Steps to Solve Problem Using
Programming​Contd…
• Optimize the step​
• Consider the steps written for specific samples and generalize it​

• Try to eliminate steps that are repeated​

• Write Pseudo code​


• Based on the steps derived ensure that you write pseudo code and check for correctness of Logic​

• Write Program​
• Choose a programming and convert the pseudocode into a program​

• Optimize code and Test​


• Use programming language construct to optimize the code and test with sample inputs​
12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 9
Quiz
1. How many generations of programming languages do we have
a) Three b) Four c) Five d)Six
2. Computers can understand ___________ Language
b) Assembly b) Machine c) Binary d) High Level
3. What is the first step in solving problem using computer
c) Analyse b) Understand c) Design d) Code
4. First person who wrote a program
d) Konrad Zuse​b) Ada Lovelace c) Dennis Ritchie d) Herman Hollerith

12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 10


Additional Resources
• https://www.youtube.com/watch?v=mhpslN-OD_o​

• https://www.youtube.com/watch?v=YZV8Zv_YW7I​

• https://www.youtube.com/watch?v=M4d3FXu9-3I​

• https://www.youtube.com/watch?v=iHNLEWa7Hew

12/8/24 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 11


SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
Kattankulathur
SCHOOL OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit : I
Session title: Algorithms and Pseudocode
Session Outcome:
By the end of this session, learners will be able to:
Think and evolve with a logic to construct an algorithm and pseudocode that can be converted into a program.

Prepared by: Dr. G Bhargavi, Assistant Professor/CTECH.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 12


Writing Algorithms and pseudocode

An algorithm is a set of steps designed to solve a problem or accomplish a task. Algorithms


are usually written in pseudocode, or a combination of your speaking language and one or
more programming languages, in advance of writing a program.
Step-1: Obtain detailed information on the problem.
Step-2: Analyze the Problem
Step-3: Think of a problem solving approach.
Step-4: Review the problem solving approach and try to think of a better alternative.
Step-5: Develop a basic structure of the algorithm.
Step-6: Optimize, improve, and refine.
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 13
Importance of algorithms

• Algorithms are crucial for data processing and decision-making in computer science.

• They help in optimizing tasks like searching and sorting efficiently.

• A well-designed algorithm can significantly reduce computation time and resource usage.

• Understanding algorithms is fundamental for any programmer or developer.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 14


Characteristics of a good algorithm

1: Input and output must be specified.


2: All important steps must be mentioned.
3: Instructions must be perfectly ordered.
4: Short and effective descriptions
5: The algorithm must contain a finite number of steps.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 15


Examples of Algorithm

1. Addition of two numbers


Step-1: Start
Step-2: Declare variables num1, num2, and sum
Step-3: Read values of num1 and num2
Step-4: Add the values of num1 and num2 and assign the result
Step-5: Display the sum
Step-6: End

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 16


Examples of Algorithm
2. Comparison of 3 numbers to find the largest number
1: Start
2: Declare variables num1, num2, and num3
3: Read values of num1 and num2 and num3
4: Compare num1, num2 and num3
5: If num1>num2 and num1>num3
Display num1 is the largest number
Else
If num2>num1 and num2>num3
Display num2 is the largest number
Else
Display num3 is the largest number
6: End
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 17
How does pseudocode work?
● Pseudocode is a plain language description of the steps in an algorithm.

● It uses the structures of programming languages but is not meant for execution.

● Pseudocode helps in planning the algorithm before coding it in a specific language.

● It focuses on the logic and flow rather than on syntax details

Benefits of Pseudocode
● Pseudocode enhances readability and understanding of algorithms for non-programmers.

● It allows algorithm design without worrying about language-specific syntax.

● It serves as an effective communication tool among developers and stakeholders.

● Using pseudocode simplifies debugging and optimization of algorithms.


07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 18
Writing pseudocode
1. Always capitalize the initial word (often one of the main six constructs).
2. Make only one statement per line.
3. Indent to show hierarchy, improve readability, and show nested constructs.
4. Always end multi-line sections using any of the END keywords (ENDIF, ENDWHILE,
etc.).
5. Keep your statements programming language independent.
6. Use the naming domain of the problem, not that of the implementation.For instance:
“Append the last name to the first name” instead of “name = first+ last.”
7. Keep it simple, concise,and readable.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 19


Main Constructs of Pseudocode
Sequence: Sequentially completed linear tasks are represented by it.
WHILE: It is a loop that starts with a condition.
REPEAT-UNTIL: A loop containing a condition present at the bottom called REPEAT-
UNTIL.
FOR: an additional looping method.
IF-THEN-ELSE: A conditional statement that alters the algorithm’s flow is known as IF-
THEN-ELSE.
CASE: It is the IF-THEN-ELSE generalization form.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 20


SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
Kattankulathur
SCHOOL OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit : I
Session title: Comments and structure of C program
Session Outcome:
By the end of this session, learners will be able to:
Know how to use the comments and how to write the structure of c program effectively

Prepared by: Dr. SARANYA V S, Assistant Professor/CTECH.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 21


Why and when to use comments in C ?

• The comments in C are human-readable explanations or notes in the source code of a C program.
• A comment makes the program easier to read and understand. These are the statements that are not
executed by the compiler or an interpreter.
• It is considered to be a good practice to document our code using comments.

• A person reading a large code will be bemused if comments are not provided about details of the
program.

• C Comments are a way to make a code more readable by providing more descriptions.

• C Comments can include a description of an algorithm to make code understandable.

• C Comments can be used to prevent the execution of some parts of the code.
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 22
Types of comments in C

In C there are two types of comments in C language:​

• Single-line comment​
• Multi-line comment

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 23


Single-line Comment in C
A single-line comment in C starts with ( // ) double forward slash. It extends till the end of the line and we don’t need to
specify its end.
// C program to illustrate
// use of single-line comment

Syntax of Single Line C Comment


#include <stdio.h>
// This is single comment
int main(void)
{
Example : C Program to illustrate single-line comment // This is a single-line comment
printf("Welcome to GeeksforGeeks");
return 0;
}
// C program to illustrate
Output:
// use of single-line comment Welcome to GeeksforGeeks

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 24


2. Multi-line Comment in C
• The Multi-line comment in C starts with a forward slash and asterisk ( /* ) and ends with an asterisk and
forward slash ( */ ).
• Any text between /* and */ is treated as a comment and is ignored by the compiler.
• It can apply comments to multiple lines in the program.
Syntax of Multi-Line C Comment

/*Comment starts
continues
continues
.
.
.
Comment ends*/

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 25


C Program to illustrate the multi-line comment

/* C program to illustrate
use of
multi-line comment */
#include <stdio.h>
int main(void)
{
/*
This is a
multi-line comment
*/

/*
This comment contains some code which
will not be executed.
printf("Code enclosed in Comment");
*/
printf("Welcome to GeeksforGeeks");
return 0;
}
Output: Welcome to GeeksforGeeks

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 26


Introduction to C: Structure of the C program
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at
Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to
write the UNIX operating system.

Sections of the C Program


Documentation
In a C program, single-line comments can be written using two forward slashes i.e., //, and we can
create multi-line comments using /* */. Here, we've used multi-line comments.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 27


Preprocessor Section
• All header files are included in this section.
• A header file is a file that consists of C declarations that can be used between different files. It
helps us in using others' code in our files. A copy of these header files is inserted into your
code before compilation.
#include <stdio.h>

Definition
A preprocessor directive in C is any statement that begins with the "#" symbol. The #define is a
preprocessor compiler directive used to create constants. In simple terms, #define basically allows
the macro definition, which allows the use of constants in our code.
#define BORN 2000

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 28


Global Declaration
• This section includes all global variables, function declarations, and static variables. The
variables declared in this section can be used anywhere in the program. They're accessible to
all the functions of the program. Hence, they are called global variables.
int age(int current);
Sub programs
• This includes the user-defined functions called in the main() function. User-defined functions
are generally written after the main() function irrespective of their order.
• When the user-defined function is called from the main() function, the control of the program
shifts to the called function, and when it encounters a return statement, it returns to the main()
function. In this case, we've defined the age() function, which takes one parameter, i.e., the
current year.
int age(int current) {
return current - BORN;
• }

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 29


Structure of C Program with Example
Below is the simple structure of c program with example code to calculate our age.

Code:
/** //Documentation
* file: age.c
* author: you
* description: program to find our age.
*/
#include <stdio.h> //Link
#define BORN 2000 //Definition
int age(int current); //Global Declaration
int main(void) //Main() Function
{
int current = 2021;
printf("Age: %d", age(current));
return 0;
}
int age(int current) { //Subprograms
return current - BORN;
}
30
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
Kattankulathur
SCHOOLF OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit :I
Session title: Input and output statements, Variables and
Identifiers, Constants, Keywords - Values, Names, Scope, Binding
Session Outcome:
By the end of this session, learners will be able to:
i)Write programs using various forms of Input and output statements, Variables and identifiers,
Constants, Keywords - Values, Names, Scope, Binding .
ii)Demonstrate the differences and appropriate use cases for each type of input / output

.
statements

Prepared By: Mrs.PREETHI V, Assistant Professor/ NWC.


07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 31
Input and Output statement

• 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.
 Scanf()
 Printf()

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 3


2
Scanf()
• The scanf() method, in C, reads the value from the console as
per the type specified and store it in the given address.
Syntax

Scanf (“%x”, &variableofxtype);

• where %X is the format specifier in C. It is a way to tell the


compiler what type of data is in a variable and & is the address
operator in C, which tells the compiler to change the real value
of variableOfXType, stored at this address in the memory.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 3


3
Printf()

• The printf() method, in C, prints the value passed as


the parameter to it, on the console screen.

Syntax
printf(“%x”, variableOfxType);

where %X is the format specifier in C. It is a way to tell


the compiler what type of data is in a variable
and variableOfXType is the variable to be printed.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 3


4
Format Specifiers

• The basic type in C includes types like int, float, char,


etc. In order to input or output the specific type,
the X in the above syntax is changed with the specific
format specifier of that type. The Syntax for input and
output for these are:
• Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 3


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

Character:

Input: scanf("%c", &charVariable);


Output: printf("%c", charVariable);

Code for reference:


https://tinyurl.com/y3zvn9zt
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
Format specifier
• The advanced type in C includes type like String. In
order to input or output the string type, the X in the
above syntax is changed with the %s format specifier.
The Syntax for input and output for String is:

syntax
Input: scanf("%s", stringVariable);
Output: printf("%s", stringVariable);

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


Format specifier

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II


Format Specifier Description
%c For character type.
%d For signed integer type.
%e or %E For scientific notation of floats.
%f For float type.
%g or %G For float type with the current precision.
%i signed integer
%ld or %li Long
%lf Double
%Lf Long double
%lu Unsigned int or unsigned long
%lli or %lld Long long
%llu Unsigned long long
%o Octal representation
%p Pointer
%s String
%u Unsigned int
%x or %X Hexadecimal representation
%n Prints nothing
%% Prints % character
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II
VARIABLES

 A variable in C language is the name associated with


some memory location to store data of different types.
 There are many types of variables in C depending on
the scope, storage class, lifetime, type of data they
store, etc.
 A variable is the basic building block of a C program
that can be used in expressions as a substitute in place
of the value it stores.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 4


0
Definition

 A variable in C is a memory location with some name


that helps store some form of data and retrieves it
when required. We can store different types of data in
the variable and reuse the same variable for storing
some other data any number of times.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 4


1
Syntax
 The syntax to declare a variable in C specifies the name and the type of the
variable.

Syntax
data_type variable_name = value; // defining single variable or
data_type 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
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 4
2
Variables
There are 3 aspects of defining a variable:
1.Variable Declaration
2.Variable Definition
3.Variable Initialization

C 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.
https://www.programiz.com/c-programming/online-compiler/
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 4
3
Variables

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 4


4
Variables
C Variable Definition
In the definition of a C variable, the compiler allocates some memory and
some value to it. A defined variable will contain some random garbage
value till it is not initialized.
Example
int var; char var2;

C Variable Initialization
Initialization of a variable is the process where the user assigns some
meaningful value to the variable when creating the variable.
Example
int var = 10;
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 4
5
Rules for Naming Variables in C
You can assign any name to the variable as long as
it follows the following rules:
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.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 4


6
C Variable Types
The C variables can be classified into the following types:
1.Local Variables
2.Global Variables
3.Static Variables
4.Automatic Variables
5.Extern Variables
6.Register Variables

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 4


7
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.
Link - https://shorturl.at/vXHrY

In the above code, x can be used only in the scope of


function(). Using it in the main function will give an error.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 4


8
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.
Link - https://shorturl.at/G2UZu

In the above code, both functions can use the global


variable as global variables are accessible by all the
functions.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 4


9
Global Variables in C
 Local Variable: The variable whose scope lies inside
a function or a block in which they are declared.
 Global Variable: The variable that exists outside of
all functions. It is the variable that is visible from all
other scopes.
 We can access global variable if there is a local
variable with same name in C
through Extern and Scope resolution
operator respectively.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 5


0
Global Variables in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 5


1
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
static data_type variable_name = initial_value;

As its lifetime is till the end of the program, it can retain its value for multiple
function calls
https://www.programiz.com/c-programming/online-compiler/
In the above example, we can see that the local variable will always print the same
value whenever the function will be called whereas the static variable will print the
incremented value in each function call.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 5


2
Static Variables in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 5


3
Automatic Variables 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
auto data_type variable_name; or
data_type variable_name;

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 5


4
Automatic Variables in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 5


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
extern data_type variable_name;

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 5


6
External Variables in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 5


7
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
register data_type variable_name = initial_value;
NOTE: We cannot get the address of the register variable using addressof (&)
operator because they are stored in the CPU register. The compiler will throw an
error if we try to get the address of register variable.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 5


8
Register Variables in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 5


9
Constant Variables in C
 Till now we have only seen the variables whose values can be
modified any number of times. But C language also provides us a
way to make the value of a variable immutable. We can do that by
defining the variable as constant.
 A constant variable in C is a read-only variable whose value cannot
be modified once it is defined. We can declare a constant variable
using the const keyword.
 Syntax
const data_type variable_name = value;

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 6


0
Constant Variables in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 6


1
Constant Variables in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 6


2
Constant Variables in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 6


3
Keywords and Identifiers in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 6


4
Keywords in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 6


5
Keywords in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 6


6
Keywords in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 6


7
Keywords in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 6


8
Keywords in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 6


9
Keywords – Scope in C
 The scope is the variable region in which it can be used.
Beyond that area, you cannot use a variable.
 The local and global are two scopes for C variables.
 The local scope is limited to the code or function in which the
variable is declared.
 The scope of the global variable is the entire program. They
are not defined inside any function and can be used in any
function.


07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 7
0
Local Scope in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 7


1
Global Scope in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 7


2
Keywords – Binding in C
 Binding provides a linkage between a function call and its definition.
 Static – if binding occurs before runtime and remains unchanged
throughout the program execution.
 Dynamic – if binding occurs during runtime or can change in the
course of program execution.
Static Binding Dynamic Binding

It happens at the compile time. It happens at the run time.

It is also called early binding. It is also called late binding.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 7


3
• include <stdio.h>

int main() {
int num1 = 10;
int num2 = 5;
Guess printf("The sum of %d and %d is:
%d", num1, num2, num1 +
the num2);
return 0;
output… }

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 74


}

• #include <stdio.h>
• int main() {
float radius = 3.5;
float area = 3.14159 * radius *
Guess radius;
printf("The area of the circle with
the radius %.2f is: %.2f", radius, area);
output… }
return 0;

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 75


}

• void main()
• { int number ;// number is a variable name
float amount;
• number= 100;
• amount = 30.75 + 75.35;
Guess • printf(“%d\n”, number); // this function
contain 2 argument the %d tells the compiler
the that the value of second argument number
output… should be printed as a decimal integer
• printf(“%5.2f\n”, amount); // %5.2f tells the
compiler that the output must be floating
point, with five place in all and two places to
the right of the decimal point.
07-08-2024
• }
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 76
}

#include<stdio.h>
void main()
{ int a,b;
• float c;
• printf(" Enter the value of a \n");

Guess • scanf("%d",&a);
• printf(" Enter the value of b \n");
the • scanf("%d",&b);

output… • c=a*b;
• printf("The sum of two numbers are: %5.3f ",c);
/*printf("Hello world \n");
• printf("my first program");
• return (0);*/ }
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 77
}

• #include<stdio.h>
• void main()
• {
• char a;
Guess • printf("Enter the a:\n");
the • scanf("%c",&a);
output… • printf("You have entered: %c", a); }

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 78


}

• #include<stdio.h>
• void main()
• {
• char a[100];
• printf("Enter a:\n");
Guess • scanf("%s",&a);
the • printf("You name is: %s\n", a); //will read only
the text before space
output… • }
• O/P
• Enter a: Welcome to Python
07-08-2024
• You name is: Welcome
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 79
#include <stdio.h> // driver code
int main()
{
float a = 12.67;
printf("Using %%f: %f\n", a);
printf("Using %%e: %e\n", a);
Guess printf("Using %%E, %E", a);
return 0;
the }
Using %f: 12.670000
output… Using %e: 1.267000e+01
Using %E, 1.267000E+01

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 80


Coding Assignments

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 81


Reference
• https://www.upgrad.com/tutorials/software-engineering/
c-tutorial/input-and-output-functions-in-c/
• https://jncollegeonline.co.in/attendence/classnotes/files
/1626589806.pdf

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 82


SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
Kattankulathur
SCHOOLF OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit : I
Session title: Storage Classes
Session Outcome:
By the end of this session, learners will be able to:
i) To understand the different storage classes in C and their impact on variable scope, visibility, and lifetime.
ii) To demonstrates the use of auto, register, static, and extern storage classes through practical examples.

Prepared By: Dr. Arikumar K S, Assistant Professor/ DSBS.

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 83


Storage Classes
storage class tells us:
• Where the variable would be stored.
• What will be the initial value of the variable, if initial value
is not specifically assigned.(i.e. the default initial value).
• What is the scope of the variable; i.e. in which functions the
value of the variable would be available.
• What is the life of the variable; i.e. how long would the
variable exist.
05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 84
Types
• Automatic storage class
• Register storage class
• Static storage class
• External storage class

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 85


Automatic Storage Class
• Storage − Memory.
• Default initial value − An unpredictable value, which is
often called a garbage value.
• Scope − Local to the block in which the variable is
defined.
• Life − Till the control remains within the block in which
the variable is defined.

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 86


Example
main( )
{
auto int i = 1 ;
{{{
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}}
The output of the above program is:
111
05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 87
Register Storage Class
• Storage - CPU registers.
• Default initial value - Garbage value.
• Scope - Local to the block in which the variable is
defined.
• Life - Till the control remains within the block in which
the variable is defined.

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 88


Example
main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 89


Static Storage Class
• Storage − Memory.
• Default initial value − Zero.
• Scope − Local to the block in which the variable is
defined.
• Life − Value of the variable persists between different
function calls.

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 90


Example
main( ) main()
{ {
increment( ) ; increment( ) ;
increment( ) ; increment( ) ;
increment( ) ; increment( ) ;
} }
increment( ) increment( )
{ {
auto int i = 1 ; static int i = 1 ;
printf ( "%d\n", i ) ; printf ( "%d\n", i ) ;
i=i+1; i=i+1;
} }

11/05/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 91


External Storage Class
• Storage − Memory.
• Default initial value − Zero.
• Scope − Global.
• Life − As long as the program’s execution doesn’t
come to an end.

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 92


Example
int i ; increment( )
main( ) {
{ i=i+1;
printf ( "\ni = %d", i ) ; printf ( "\non incrementing i = %d", i ) ;
increment( ) ; }
increment( ) ; decrement( )
decrement( ) ; {
decrement( ) ; i=i-1;
} printf ( "\non decrementing i = %d", i ) ;
}

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 93


SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
Kattankulathur

SCHOOL OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit : I
Session title: Numeric Data types: Integer and Floating Point Non Numeric
Data Types: Char & String-L Value & R Value in Expression
Session Outcome:
By the end of this session, learners will be able to:
i)Write programs using various numerical data types

ii)Demonstrate the differences integer and floating point .


Prepared By: Mr. Jishnu. K S, Assistant Professor/ C-Tech.
Mr. Gokulakrishnan, Assistant Professor/ C-Tech.
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 94
Data Types
● In C programming, a data type specifies the kind of data a variable can hold, including
its size and range of values.
● This information is crucial for the compiler to allocate appropriate memory and perform
correct operations.

Mainly 2 Types
I. Numeric Data Types: Numeric data types are used to represent numerical values.
II. Non-Numeric Data types: Non-numeric data types are used to represent characters,
text, logical values, and other non-numerical information.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 95


I. Numeric Data Types:

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 96


07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 97
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 98
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 99
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 100
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 101
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 102
L value and R value in expression

L value and R value refer to the left and right sides of the assignment operator.
An L value refers to an expression that represents a memory location. An L value means expression
which can be placed on the left-hand side of the assignment operator. An expression which has memory
location.
An examples of L values include variables, array elements, and deferential pointers.
An R value refers to an expression that represents a value that is stored at some location.
It can appear on the right-hand side of the assignment operator.
An examples of R value include literals (e.g numbers and characters), the results of arithmetic operations,
and function return values.
L value and R value in expression

Note:
L value can be used as an R value , but an R-value cannot be used as an L value.
The unary operator ‘&’ can be used to get the address of L value.
The address of operator ‘&’ cannot be applied to R value.

int main() {
int x = 10; // 'x' is an l-value
int y = x; // 'x' is an r-value on the right side of the assignment, and 'y' is an l-value

int* ptr = &x; // '&' operator gets the address of 'x', which is an l-value
// The following lines would result in compilation errors:
// int* ptr2 = &10; // Error: Cannot take the address of an r-value
// &x = 20; // Error: 'x' is an l-value, but the left side of the assignment operator expects an l-value
return 0;
}
Reference
• https://data-flair.training/blogs/numeric-data-types-in-c/#google_
vignette
• https://www.geeksforgeeks.org/data-types-in-c/

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 105


SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
Kattankulathur
SCHOOLF OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit: I
Session Title: Increment & Decrement Operators
Session Outcome:
By the end of this session, learners will be able to:
i)Write programs using Increment and Decrement operators, and understanding the power of this operators

Prepared by: Dr. N. Nithiyanandam.


Assistant Professor/ C.Tech. Department
Dr. Gokulnath C, Assistant Professor/ CTech.
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 106
Operators in C

 In C programming, operators are symbols that perform operations on variables and values.
 They are classified into different categories based on the type of operations they perform.

Example: a+b (or) 2*10


 What input data we are passing it is called operand.

 Which symbol we are using it is called operator.

 Depends on number of operands, this operators are classified into 3 types.

1. Unary Operator (requires one operand)

2. Binary Operator (requires two operands)

3. Ternary Operator (requires three operands)

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 107


Operators in C

Operators also classified into –

1. Arithmetic Operator

2. Relational Operator

3. Logical Operator

4. Ternary or Conditional operator

5. Increment and Decrement operator

6. Bitwise Operator

7. Comma Operator

8. Sizeof Operator
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 108
Operators in C

1.Arithmetic Operator:-
 Arithmetic operators are used to perform arithmetic operations between two operands.

Operator Description Example


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (remainder) a%b

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 109


1. Arithmetic Operators in C
/* Working of arithmetic operators*/
#include < stdio.h > Output:
int main()
{
a + b = 15
int a = 10,b = 5, c; a-b=5
c = a+b; //Addition a * b = 50
printf("a + b = %d \n",c);
a/b=2
c = a-b; //Subtraction
printf("a - b = %d \n",c);
a%b=0
c = a*b; //Multiplication
printf("a * b = %d \n",c);
c = a/b; //Division
printf("a / b = %d \n",c);
c = a%b; //Modulo Division
printf("a % b = %d \n",c);
return 0;
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 110


Relational Operator

 A relational operator checks the relationship between two operands.


 If the relation is true, it returns 1; if the relation is false, it returns value 0

Operator Description Example

== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 111


Relational Operator

// Working of relational operators Output:


#include < stdio.h > 5 == 5 is 1
int main()
5 == 10 is 0
{
int a = 5, b = 5, c = 10; 5 > 5 is 0
printf("%d = = %d is %d \n", a, b, a = = b); 5 > 10 is 0
printf("%d = = %d is %d \n", a, c, a = = c);
printf("%d > %d is %d \n", a, b, a > b);
5 < 5 is 0
printf("%d > %d is %d \n", a, c, a > c); 5 < 10 is 1
printf("%d < %d is %d \n", a, b, a < b);
5 != 5 is 0
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b); 5 != 10 is 1
printf("%d != %d is %d \n", a, c, a != c); 5 >= 5 is 1
printf("%d >= %d is %d \n", a, b, a >= b);
5 >= 10 is 0
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b); 5 <= 5 is 1
printf("%d <= %d is %d \n", a, c, a <= c); 5 <= 10 is 1
return 0;
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 112


Logical Operator

 In C, logical operators are used to combine two or more conditions/expressions and return either true
(1) or false (0) based on the evaluation.
 The three logical operators are:
1. Logical AND (&&): Returns true if both conditions are true.
2. Logical OR ( | | ): Returns true if at least one of the conditions is true.
3. Logical NOT (!): Reverses the logical state of its operand (true becomes false, false becomes
true).
Operator Description Example
&& Logical AND a && b
`|| Logical OR ` a || b
! Logical NOT !a

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 113


Logical Operator

// Working of logical operators


Output:
#include < stdio.h >
(a>b) && (a<c) is 0
int main()
(a>b) || (a<c) is 1
{
!(a>b) is 1
int a= 10, b = 20, c= 30;
printf ("(a>b) && (a<c) is %d", (a>b) && (a<c));
printf ("(a>b) || (a<c) is %d", (a>b) || (a<c));
printf ("!(a>b) is %d", !(a>b));
return 0;
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 114


Assignment Operator:-

 The assignment operators are used to assign the value of the right expression to the
left operand.
Operator Description Example

= Assignment a=b

+= Add and assign a += 2

-= Subtract and assign a -= 2

*= Multiply and assign a *= 2

/= Divide and assign a /= 2

%= Modulus and assign a %= 2


07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 115
Assignment Operator

// Working of Increment and Decrement operators


#include < stdio.h >
Output:
int main()
{
int a = 5, c;
c=5
c = a; c = 10
printf("c = %d\n", c);
c += a; //it is equal to c=c+a
c=5
printf("c = %d\n", c); c = 25
c -= a; //it is equal to c=c-a
printf("c = %d\n", c); c=5
c *= a; //it is equal to c=c*a c=0
printf("c = %d\n", c);
c /= a; //it is equal to c=c/a
printf("c = %d\n", c);
c %= a; //it is equal to c=c%a
printf("c = %d\n", c);
return(0);
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 116


Bitwise Operator

 The bitwise operators perform bit by bit operation on the values of the two operands.

Operator Description Example

& Bitwise AND a&b

`| Bitwise OR` Bitwise OR

^ Bitwise XOR a^b

~ Bitwise NOT (1's complement) ~a

<< Left shift a << 1

>> Right shift a >> 1

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 117


Bitwise Operator

// Working of Bitwise operators


#include < stdio.h > Output:

int main() a&b=8


{ a | b = 13
a=9 //equal to 1001 a^b=5
b = 12 //equal to 1100
~a = -10
print ("a & b = ",a & b)
a << 2 = 36
print ("a | b = ",a | b)
a >> 2 = 2
print("a ^ b = ",a ^ b)
print("~a = ",~a)
print("a << 2 = ",a << 2)
print("a >> 2 = ",a >> 2)
return(0)
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 118


Conditional Operator

 The conditional operator is also known as a ternary operator.


 The conditional statements are the decision-making statements which depends upon
the output of the expression.
 It is represented by two symbols, i.e., '?' and ':'.
 Syntax: expression1? expression2: expression3;

Operator Description Example

?: Condition evaluates and returns value (a > b) ? a : b

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 119


Conditional Operator

// Working of conditional operator


#include
int main()
{ Output:

int a=5,b=10; b is Greater


a>b? printf("a is Greater") : printf("b is Greater");
return(0);
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 120


Sizeof Operator

 The sizeof is a unary operator that returns the size of data (constants, variables, array,
structure, etc).
 Syntax: sizeof(variable);

Operator Description Example


sizeof Size of an object sizeof(a)

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 121


Sizeof Operator

// Working of conditional operator


Output:
#include < stdio.h >
int main() Size of int = 4 bytes

{ Size of float = 4 bytes


int a; Size of double = 8 bytes
float b; Size of char = 1 byte
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return(0)
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 122


Increment and Decrement Operators in C

 Increment ++ increases the value by 1 whereas decrement -- decreases the value


by 1.
 These two operators are unary operators, meaning they only operate on a single
operand.
 These operators can be used in both prefix and postfix forms, and their behavior
differs slightly depending on the form used.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 123


a) Increment Operator (‘++’)

 Pre Increment (++variable): Increases the value of the variable first, then returns the updated
value.

 Post Increment (variable++): Returns the current value of the variable, then increases it by 1.

Example:

int a = 5;

printf("%d\n", ++a); // Prefix: a is incremented first, then printed (output: 6)

printf("%d\n", a++); // Postfix: a is printed first, then incremented (output: 6)

printf("%d\n", a); // Now, a is 7 (output: 7)

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 124


b) Decrement Operator (‘- -’)

 Pre Decrement (- -variable): Decreases the value of the variable first, then returns the updated
value.

 Post Decrement (variable - -): Returns the current value of the variable, then decreases it by 1.

Example:

int b = 5;

printf("%d\n", --b); // Prefix: b is decremented first, then printed (output: 4)

printf("%d\n", b--); // Postfix: b is printed first, then decremented (output: 4)

printf("%d\n", b); // Now, b is 3 (output: 3)

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 125


Increment and Decrement Operator

Output

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 126


Operators

• An operator is a symbol that operates on a value or a variable.

• For example : a+b (or) 4+5

• A symbol that instructs the compiler to perform specific


mathematical or logical functions is known as an operator

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 127


Types of Operators
1. Unary Operator
2. Arithmetic Operator
3. Relational Operator
4. Logical Operator
5. The ternary or conditional operator
6. Increment and Decrement operator
7. Bitwise Operator
8. Comma Operator
9. Sizeof Operator

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 128


OPERATORS

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 129


Arithmetic Operator
An arithmetic operator performs mathematical operations on numerical values such as
addition, subtraction, multiplication, and division (constants and variables).

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 130


Arithmetic Operator
#include <stdio.h>
int main()
{
int a = 10,b = 20, c;
c = a+b;

Guess the printf("a+b = %d \n",c);


c = a-b;
printf("a-b = %d \n",c);
output… c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 131


Relational Operators
A relational operator checks the relationship between two operands. Relational operators are
specifically used to compare two quantities or values in a program. If the relation is true, it returns 1; if
the relation is false, it returns value 0.
Operator Meaning of Operator
== Equal to
> Greater than
< Less than
!= Not equal to
>= Greater than or equal to
<= Less than or equal to

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 132


#include <stdio.h>
int main() {
int x = 5;

Guess the int y = 3;


printf("%d", x == y); // returns 0 (false) because 5

output… is not equal to 3


return 0;
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 133


Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon whether expression
results true or false. Logical operators are commonly used in decision making in C programming.

Operator Meaning of Operator

Logical AND. True only if all


&&
operands are true

Logical OR. True only if either


||
one operand is true

Logical NOT. True only if the


!
operand is 0

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 134


#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf(" %d \n", result);
result = (a == b) && (c < b);
Guess the printf(" %d \n", result);
result = (a == b) || (c < b);

output… printf(" %d \n", result);


result = (a != b) || (c < b);
printf(" %d \n", result);
result = !(a != b);
printf(" %d \n", result);
result = !(a == b);
printf(" %d \n", result);
return 0;
}
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 135
The Ternary or Conditional operator
The conditional operator is similar to the if-else statement in that it follows the same algorithm, but the
conditional operator takes less space and helps to write the if-else statements in the shortest possible
way.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 136


The ternary or conditional operator

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

Guess the int m = 10, n = 8;

(m > n) ? printf("m is greater than n that is %d >


output… %d",m, n)
: printf("n is greater than m that is %d >
%d",n, m);
return 0;
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 137


Increment and Decrement operator
C programming has two operators increment ++ and decrement -- to change the value of an operand
(constant or variable) by 1. Increment ++ increases the value by 1 whereas decrement -- decreases the
value by 1. These two operators are unary operators, meaning they only operate on a single operand.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 138


#include <stdio.h>
int main()
{
int a = 10,b=6,c=12,d=15;

Guess the printf("a=%d \n", ++a);


printf("b=%d \n", --b);

output… printf("c=%d \n", ++c);


printf("d=%d \n", --d);
return 0;
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 139


#include <stdio.h>
int main()
{
int a = 10,b=6,c=12,d=15;
printf("a=%d \n", a++);

Guess the printf("b=%d \n", b--);

output…
printf("c=%d \n", c++);
printf("d=%d \n", d--);
return 0;
}

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 140


Bitwise Operators in C
 Bitwise operators are used to manipulate one or more bits from integral operands like char, int,
short, long.
 Bitwise operators operate on individual bits of integer (int and long) values.
 If an operand is shorter than int, it is promoted to int before doing the operations.
 In the calculation, just the individual bits of a number are considered, not the complete number.
 Negative integers are stored or represented in two’s complement form. For example, -4 is 1111 1111
1111 1111 1111 1111 1111 1100.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 141


Bitwise Operators in C

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING – UNIT-I 142


Bitwise Operators in C - Bitwise AND ‘&’

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 143


Bitwise Operators in C - Bitwise OR ‘|’

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 144


Bitwise Operators in C - Bitwise XOR ‘^’

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING – UNIT-I 145


Bitwise Operators in C - Bitwise Negation ‘~’

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 146


Bitwise Operators in C
Shift operators are used to shift a number's bits left or right. Basically two types of shift
operators,
1. Left Shift Operator (<<)
2. Right Shift Operator (>>)
Left Shift Operator
It moves the first operand's bits to the left by the number of positions specified by the
second operand. Simultaneously, the empty spaces left by the shifted bits are filled with
zeroes.
Right Shift Operator
The right shift operator (>>) shifts the first operand to the right by the specified number of
bits. Excess bits that are shifted to the right are discarded.
07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 147
Operators in C
Comma operator
Comma operators are used to link related expressions together.

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 148


Operators in C

sizeof operator

• The sizeof is a unary operator that returns the size of data (constants,
variables, array, structure, etc).

07-08-2024 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 149


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

Guess the float b;


double c;

output… char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
07-08-2024 }
21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 150
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
Kattankulathur
SCHOOLF OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit : I
Session title: Operators
Session Outcome:
By the end of this session, learners will be able to:
i) To understand the types of operators and to understand how to use it while coding.
ii) It demonstrates the examples how to use operators

Prepared By: Mr. Rohit Ravi, Assistant Professor/ CTECH.


Mr.Gowtham, Assistant Professor/CTECH.
05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 151
Operators
Unary, Binary Operators
Operators can also be classified into three types on the basis of
the number of operands they work on:
Unary Operators: Operators that work on single operand.
Example:- Increment, Decrement.
Binary Operators: Operators that work on two operands.
Example:- Addition, Subtraction.

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 152


Operators

• Arithmetic Operator
• Relational Operator
• Logical Operator

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 153


Arithmetic Operators
+ add two numeric values (a + b)
- Subtract second numeric value from first (a - b)
* Multiply two numeric values (a * b)
/ Divide numerator by denominator (a / b)
% Returns the remainder after diving the left operand with the
right operand. (a % b)
++ Increase the value by 1
-- Decrease the value by 1

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 154


Arithmetic Order of Operations
1. Parenthesis
2. Exponentiation
3. Division and multiplication
4. Addition and subtraction

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 155


Arithmetic Operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 156
Arithmetic Operators
printf("a % b = %d\n", a % b);
printf("+a = %d\n", +a);
printf("-a = %d\n", -a);
printf("a++ = %d\n", a++);
printf("a++ = %d\n", a);
printf("a-- = %d\n", a--);
printf("a-- = %d\n", a);
return 0;
}
05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 157
Arithmetic Operators
Output
a + b = 30 +a = 25
a - b = 20 -a = -25
a * b = 125 a++ = 25
a/b=5 a++ = 26
a%b=0 a-- = 26
a++ = 25

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 158


Relational Operators
• Relational operators are binary – they require an operand on
both sides of the operator

• Result of a relational expression will always be Boolean

• They are evaluated from left to right with no order of


operations

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 159


Relational Operators
< less than (a < b)
> greater than (a > b)
<= less than or equal to (a <= b)
>= greater than or equal to (a >= b)
== equal to (a == b)
!= not equal to (a != b)

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 160


Relational Operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results
printf("a < b : %d\n", a < b);
printf("a > b : %d\n", a > b);

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 161


Relational Operators
printf("a <= b: %d\n", a <= b);
printf("a >= b: %d\n", a >= b);
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);
return 0;
}

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 162


Relational Operators
Output
a<b :0
a>b :1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 163


Logical Operators
Used for joining Boolean expressions

• And – Return True if and only if both expressions are True


• Or – Return True if one or the other or both
expressions are True
• Not – makes a False condition True and vice versa

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 164


Logical Order of Operations

1. Not
2. And
3. Or

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 165


Logical Operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results
printf(“A && B : %d\n", (a<b) && (a>b));
printf(“A || B : %d\n", (a<b) || (a>b));
printf("!A: %d\n", !(a<b));
return 0;
}
05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 166
Logical Operators
Output
A && B : 0
A || B : 1
!A: 1

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT II 167


SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
Kattankulathur
SCHOOLF OF COMPUTING
21CSS101J – PROGRAMMING FOR PROBLEM SOLVING

Unit : I
Session title: Operator Precedence - Expressions with pre / post increment
operator
Session Outcome:
By the end of this session, learners will be able to:
i)Write programs using the associativity property of an operator.

ii)Demonstrate the operators of the same priority are evaluated either from left to right or from right to left, depending on the level .
Prepared By: Dr.Savaridaasan.P, Assistant Professor/ NWC.
Dr.Maranco.M, , Assistant Professor/ NWC.
05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 168
Operator Precedence

• In C language, each operator has a “precedence” or priority associated with it.


• An expression is evaluated from left to right.
• The operators at the higher level of priority are evaluated first.
• The operators of the same priority are evaluated either from left to right or
from right to left, depending on the level. This is known as the associativity
property of an operator.
Example:
( 3 * 5 ) + ( 4 / 2) – ( 1 * 2)
15 + 2 - 2
15

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 169


OPERATORS

The ternary or conditional operator


The conditional operator is similar to the if-else statement in that it follows the same algorithm, but the
conditional operator takes less space and helps to write the if-else statements in the shortest possible
way.
OPERATORS

The ternary or conditional operator


Syntax:
The conditional operator is of the form
variable = Expression1 ? Expression2 : Expression3
It can be visualized into if-else statement as:
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Since the Conditional Operator ‘?:’ takes three operands to work, hence they are also called ternary
operators.
OPERATORS

The ternary or conditional operator


#include <stdio.h>
int main()
{
int m = 10, n = 8;

(m > n) ? printf("m is greater than n that is %d > %d",m, n)


: printf("n is greater than m that is %d > %d",n, m);
return 0;
}
Operator Precedence Table

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 173


Pre / Post increment operator
• Increment and decrement operators are unary operators.
• They can add or subtract ‘1’ from the operand.
• Eg: x = x +1 can be written as ++x
• result : x=2

• C languages has two types (pre and post) of each operator:


• 1. Operator placed before variable (Pre)
• 2. Operator placed after variable (Post)

• The increment/decrement operator is ++ and --.

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 174


Types of Pre / Post increment operator
• Types:

1. Pre Increment Operator


2. Post Increment Operator
3. Pre Decrement Operator
4. Post Decrement Operator

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 175


Pre Increment Operator
• A pre-increment operator is used to increment the value of a variable
before using it in an expression. In the Pre-Increment, value is first
incremented and then used inside the expression

Syntax for Pre Increment Operator :

(pre)++var_name;

Example:

https://tinyurl.com/3cub6edw

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 176


Post Increment Operator
• The post-increment operator is used to increment the original
value of the operand by 1 after assigning it to the expression.

Syntax for Post Increment Operator :

var_name -- (Post);

Example:

https://tinyurl.com/5n7dv3uh

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 177


Pre Decrement Operator
• In pre-decrement operation, the decrement operator is used as the
prefix of the variable. The decrement in value happens as soon as
the decrement operator is encountered.

Syntax for Pre Decrement Operator :

(pre)--var_name;

Example:

https://tinyurl.com/3rc6m3t3

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 178


Post Decrement Operator
• Post decrement operator is used to decrease the original value
of the operand by 1 after assigning to the expression.

Syntax for Post Decrement Operator :

var_name++ (post);

Example:

https://tinyurl.com/mr3ftrf5

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 179


#include<stdio.h>
#include<conio.h>
void main()
{
int p,q;
Guess the i=10;
p=++q;
output… printf(“p: %d”,p);
printf(“q: %d”,q);
getch();
}

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 180


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
Guess the b=10;
a=b++;
output… printf(“a: %d”,a);
printf(“b: %d”,b);
getch();
}

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 181


#include<stdio.h>
#include<conio.h>
void main()
{
int p,q;
Guess the q=10;
p=--q;
output… printf(“p: %d”,p);
printf(“q: %d”,q);
getch();
}

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 182


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
Guess the b=10;
a=b--;
output… printf(“a: %d”,a);
printf(“b: %d”,b);
getch();
}

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 183


Coding Assignments
1. First printf output is 11, 11. Second one is 10, 20 why is it 20 shouldn't it be 21?

2. How come that the C standard says that the expression


j = i++ * i++; is undefined, whereas, the expression
j = i++ && i++; is perfectly legal.

3. What would be the output of the following program?


main()
{
int i = -3, j = 2, k = 0, m;
m = ++j && ++i || ++k;
printf("\n %d %d %d %d",i,j,k,m);
}
05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 184
Reference
• https://www.simplilearn.com/tutorials/c-tutorial/c-operators

• https://www.geeksforgeeks.org/increment-and-decrement-
operators-in-c/

05/11/2025 21CSS101J PROGRAMMING FOR PROBLEM SOLVING - UNIT I 185

You might also like