0% found this document useful (0 votes)
31 views199 pages

PPS Unit-1

The document outlines the evolution of programming languages and problem-solving through programming, detailing key milestones from early machine language to modern multiparadigm languages. It emphasizes the importance of algorithms, pseudocode, and programming basics, including data types, control structures, and debugging. Additionally, it highlights the significance of problem analysis, algorithm development, and optimization in effective programming.

Uploaded by

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

PPS Unit-1

The document outlines the evolution of programming languages and problem-solving through programming, detailing key milestones from early machine language to modern multiparadigm languages. It emphasizes the importance of algorithms, pseudocode, and programming basics, including data types, control structures, and debugging. Additionally, it highlights the significance of problem analysis, algorithm development, and optimization in effective programming.

Uploaded by

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

21CSS101J

PROGRAMMING FOR PROBLEM


SOLVING

Dr. R. Femi
Assistant Professor
Department of Electrical and Electronics Engineering
SRM Institute of Science and Technology,
Kattankulathur
Unit-1
Evolution of Programming & Languages - Problem solving
through programming - Writing algorithms & Pseudo code -
Single line and multiline comments - Introduction to C:
Structure of the C program - Input and output statements.

Variables and identifiers, Constants, Keywords - Values,


Names, Scope, Binding, Storage Classes - Numeric Data
types: integer, floating point Non-Numeric Data types: char
and string - L value and R value in expression,

Increment and decrement operator - Comma, Arrow and


Assignment operator, Bitwise and Size-of operator -
Arithmetic, Relational and logical Operators - Condition
Operators, Operator Precedence - Expressions
with pre / post increment operator
Evaluation of Programming & Languages
1883: The Journey starts from here…!!
• In the early days, Charles Babbage had made the device, but he was confused
about how to give instructions to the machine, and then Ada Lovelace wrote the
instructions for the analytical engine.
• The device was made by Charles Babbage and the code was written by Ada
Lovelace for computing Bernoulli’s number.
• First time in history that the capability of computer devices was judged.

1949: Assembly Language


• It is a type of low-level language.
• It mainly consists of instructions (kind of symbols) that only machines could
understand.
• In today’s time also assembly language is used in real-time programs such as
simulation flight navigation systems and medical equipment eg – Fly-by-wire
(FBW) systems.
• It is also used to create computer viruses.

1952: Autocode
• Developed by Alick Glennie.
• The first compiled computer programming language.
• COBOL and FORTRAN are the languages referred to as Autocode.
Evaluation of Programming & Languages
1957: FORTRAN
• Developers are John Backus and IBM.
• It was designed for numeric computation and scientific computing.
• Software for NASA probes voyager-1 (space probe) and voyager-2 (space probe)
was originally written in FORTRAN 5.
1958: ALGOL
• ALGOL stands for ALGOrithmic Language.
• The initial phase of the most popular programming languages of C, C++, and
JAVA.
• It was also the first language implementing the nested function and has a simple
syntax than FORTRAN.
• The first programming language to have a code block like “begin” that indicates
that your program has started and “end” means you have ended your code.
1959: COBOL
• It stands for COmmon Business-Oriented Language.
• In 1997, 80% of the world’s business ran on Cobol.
• The US internal revenue service scrambled its path to COBOL-based IMF
(individual master file) in order to pay the tens of millions of payments mandated
by the coronavirus aid, relief, and economic security.
Evaluation of Programming & Languages
1964: BASIC
• It stands for beginners All-purpose symbolic instruction code.
• In 1991 Microsoft released Visual Basic, an updated version of Basic
• The first microcomputer version of Basic was co-written by Bill Gates,
Paul Allen, and Monte Davidoff for their newly-formed company,
Microsoft.

1972: C
• It is a general-purpose, procedural programming language and the most
popular programming language till now.
• All the code that was previously written in assembly language gets
replaced by the C language like operating system, kernel, and many
other applications.
• It can be used in implementing an operating system, embedded system,
and also on the website using the Common Gateway Interface (CGI).
• C is the mother of almost all higher-level programming languages like
C#, D, Go, Java, JavaScript, Limbo, LPC, Perl, PHP, Python, and Unix’s
C shell.
Evaluation of Programming & Languages
The evolution of programming and programming languages is a fascinating
journey of how humans have developed increasingly sophisticated ways to
communicate with computers. Here's an overview of the key milestones:

1. Early Era: Machine Language (1940s)


• Machine Language (1st Generation): The earliest form of programming,
consisting of binary code (0s and 1s) directly understood by computers.
• Example: 10110000 01100001
• Highly error-prone and difficult for humans to understand.
• Programs were hardcoded into machines, requiring knowledge of the
specific hardware.

2. Assembly Language (1950s)


• Assembly Language (2nd Generation): Introduced mnemonic codes as
symbolic representations for machine instructions.
• Example: MOV AX, 61h (easier than binary).
• Required an assembler to convert these instructions into machine code.
• Made programming slightly more human-readable but still low-level.
Evaluation of Programming & Languages
3. High-Level Languages (1950s-1960s)
• Third-Generation Languages (3GLs): Allowed programmers to write in a syntax
resembling natural language, making programming accessible.
• FORTRAN (1957): First high-level language for scientific and engineering
computations.
• COBOL (1959): Designed for business applications.
• LISP (1958): Pioneered functional programming, used in AI research.
• Key Features:
• Platform independence: Could run on multiple types of hardware using a
compiler.
• Abstraction from hardware details.

4. Structured Programming (1960s-1970s)


• Emphasis on structured control flow (e.g., loops, conditionals) and modular design.
• Languages: C (1972), Pascal (1970).
• Encouraged better programming practices and readability.
• Introduction of concepts like functions and procedures.
Evaluation of Programming & Languages
5. Object-Oriented Programming (1980s-1990s)
• Object-Oriented Paradigm: Focused on objects that
encapsulate data and methods.
• Languages: C++ (1983), Java (1995), Smalltalk.
• Key Concepts: Encapsulation, inheritance, polymorphism.
• Revolutionized software development by making code
reusable, maintainable, and scalable.

6. Scripting and Internet Era (1990s-2000s)


• Rise of scripting languages and web development.
• JavaScript (1995): For dynamic web pages.
• Python (1991): Emphasized simplicity and versatility.
• PHP (1995): Popular for server-side scripting.
• Ruby (1995): Focused on developer happiness with readable
syntax.
Evaluation of Programming & Languages
7. Modern Era: Multiparadigm and Specialized Languages
• Multiparadigm Languages: Support multiple programming styles (functional,
procedural, object-oriented).
• Examples: Python, Scala, Kotlin.
• Domain-Specific Languages (DSLs):
• Designed for specific purposes (e.g., SQL for databases, MATLAB for engineering
simulations).
• Concurrency and Parallelism:
• Languages like Go (2009) and Rust (2010) designed for safe and efficient
concurrent programming.

8. Current Trends and Future Directions


• AI and Machine Learning: Languages like Python dominate due to frameworks
like TensorFlow and PyTorch.
• Low-Code/No-Code Platforms: Simplify app development for non-
programmers.
• Quantum Computing: Emerging languages like Q# and Cirq for quantum
algorithms.
• Decentralized Systems: Focus on blockchain programming (e.g., Solidity for
Ethereum).
Evolution of Programming Languages
Programming Language is considered as the set of commands and
instructions that we give to the machines to perform a particular task. For
example, if you give some set of instructions to add two numbers then the
machine will do it for you and tell you the correct answer accordingly.
But a good programming language----
1. Portability
2. Maintainability
3. Efficient
4. Reliable
5. Machine Independence
6. Cost Effectiveness
7. Flexible
Problem solving through programming
Problem Solving through Programming" is an essential skill in computer science and
engineering. It focuses on applying logical thinking and programming techniques to solve
real-world problems.
Core Concepts:

1. Problem Analysis:
1. Understand the problem requirements.
2. Identify inputs, outputs, and constraints.
3. Break the problem into smaller, manageable parts.

2. Algorithm Development:
1. Develop a step-by-step solution (algorithm).
2. Use flowcharts or pseudocode for visualization.
3. Ensure efficiency and correctness.

3. Programming Basics:
1. Familiarize yourself with programming languages (e.g., Python, C++, Java).
2. Understand variables, data types, and operators.
3. Learn control structures like loops (for, while) and conditionals (if-else).
4. Data Structures:
1. Use arrays, lists, stacks, queues, and dictionaries for efficient data handling.
2. Solve problems using advanced structures like trees, graphs, and heaps.
Problem solving through programming
5. Functions and Modularity:
• Write reusable code using functions.
• Understand the scope and lifecycle of variables.
• Practice modular programming for clean, maintainable
code.
6. Debugging and Testing:
• Debug programs to identify and fix errors.
• Write test cases for various scenarios.
• Use debugging tools and logging.
7. Optimization:
• Analyze the time and space complexity of solutions.
• Optimize algorithms for better performance.
Problem Solving through programming
What is problem solving?
Problem solving is the act of defining a problem; determining the cause of the
problem; identifying, prioritizing, and selecting alternatives for a solution; and
implementing a solution.
Problem Solving through programming
Stages of Problem solving
1. Understand the problem
2. Define the problem
3. Define boundaries
4. Plan solution
5. Check solution
Writing algorithms & Pseudo code
What is an Algorithm?
An algorithm is a set of instructions or step-by-step
procedures for solving problems or performing tasks.
These sets of instructions are unambiguous and very
well-defined.

What is Pseudocode?
It is a high-level description of an algorithm that uses
natural language and simple programming constructs to
convey the logic of an algorithm. Pseudocodes are like a
special language software developers use to plan an
algorithm before writing the code.
Algorithms
• Example: Find the maximum value in a given list of numbers.
• Solutions: Here is a set of instructions (or algorithm) that you can
follow to find the maximum value in the list.

1. Start with the first number and assign it as the maximum value.
2. Now, move to the second number; if the second number > the first
number, then set the maximum value to the second number; there is
no change.

i.e., if the current number is greater than the maximum value, then set the
maximum value to the current number.
3. Move on to the next number in the list, and repeat step 2 until you
have reached the end of the list.
4. The maximum value is the value that was stored in the maximum
variable.
Algorithms
Writing Algorithms
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.
Writing Algorithms
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 finite
number of steps
Writing Algorithms
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
Writing Algorithms
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
Creating Algorithms Contd…
Example : Print 1 to 20
 Step 1: Start

 Step 2: Initialize X as 0,

 Step 3: Increment X by 1,

 Step 4: Print X,

 Step 5: If X is less than 20 then go back to step 2.

 Step 6: Stop
Creating Algorithms

Example
Convert Temperature from Fahrenheit (℉)to Celsius (℃)
 Step 1: Start

 Step 2: Read temperature in Fahrenheit

 Step 3: Calculate temperature with formula C=5/9*(F-32)

 Step 4: Print C

 Step 5: Stop
Creating Algorithms
Example
Algorithm to Add Two Numbers Entered by User
 Step 1: Start

 Step2: Declare variables num1, num2 and sum.

 Step 3: Read values num1 and num2.


 Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2

 Step 5: Display sum

 Step 6: Stop
Creating Algorithms
 Write an Algorithm to:

1) Find the Largest among three different numbers

2) Find the roots of a Quadratic Equation

3) Find the Factorial of a Number

4) Check whether a number entered is Prime or not

5) Find the Fibonacci Series


Pseudo code
• In simple terms, it is considered a way or medium to
communicate algorithms to other people (or non-
programmers) and to document algorithms for future
reference.
• let’s consider the same example above to find the maximum
value from the list.
• So, the corresponding pseudo
– Start
– Initialize a variable called “max” to the first element of the list
– Loop through each element of the list
– If the current element is greater than “max”, set “max” equal to the
current element
– Continue looping until all elements have been checked
– Output the value of “max”
– Stop
Pseudo code
procedure find_max(list)
max = list[0] #initialize a variable
for i = 1 to len(list) #loop through each
element
if list[i] > max
max = list[i] #if the current value is greater
than max, set max = current value
return max
A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does
not use any programming language in its representation instead it uses the simple English
language text as it is intended for human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation(code) in a
high-level language.
21CSS101J

PROGRAMMING FOR PROBLEM


SOLVING

Dr. R. Femi
Assistant Professor
Department of Electrical and Electronics Engineering
SRM Institute of Science and Technology,
Kattankulathur
Unit-1
Evolution of Programming & Languages - Problem solving
through programming - Writing algorithms & Pseudo code -
Single line and multiline comments - Introduction to C:
Structure of the C program - Input and output statements.

Variables and identifiers, Constants, Keywords - Values,


Names, Scope, Binding, Storage Classes - Numeric Data
types: integer, floating point Non-Numeric Data types: char
and string - L value and R value in expression,

Increment and decrement operator - Comma, Arrow and


Assignment operator, Bitwise and Size-of operator -
Arithmetic, Relational and logical Operators - Condition
Operators, Operator Precedence - Expressions
with pre / post increment operator
Pseudo code
• In simple terms, it is considered a way or medium to
communicate algorithms to other people (or non-
programmers) and to document algorithms for future
reference.
• let’s consider the same example above to find the maximum
value from the list.
Algorithm
– Start
– Initialize a variable called “max” to the first element of the list
– Loop through each element of the list
– If the current element is greater than “max”, set “max” equal to the
current element
– Continue looping until all elements have been checked
– Output the value of “max”
– Stop
Pseudo code
procedure find_max(list)
max = list[0] #initialize a variable
for i = 1 to len(list) #loop through each
element
if list[i] > max
max = list[i] #if the current value is greater
than max, set max = current value
return max
A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does
not use any programming language in its representation instead it uses the simple English
language text as it is intended for human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation(code) in a
high-level language.
How to Write Pseudocode
Example:
Finding the largest number in a list
Algorithm
• Start
• Input the list of numbers (e.g., [3, 1, 4, 1, 5]).
• Set largest to the first number in the list.
• For each number in the list:
– If the number is greater than largest, set largest to the
number.
• After the loop ends, largest contains the largest number.
• Output the value of largest.
• End
Finding the largest number in a list
Pseudocode
pseudocode for adding two numbers

START
DISPLAY "Enter the first number:"
READ number1
DISPLAY "Enter the second number:"
READ number2
result ← number1 + number2
DISPLAY "The sum is:", result
END
pseudocode to convert a temperature
from degrees Celsius to Fahrenheit:

START
DISPLAY "Enter the temperature in degrees
Celsius:"
READ celsius
fahrenheit ← (celsius × 9/5) + 32
DISPLAY "The temperature in Fahrenheit is:",
fahrenheit
END
pseudocode to check if a number is
even or odd:

START
DISPLAY "Enter a number:"
READ number
IF (number MOD 2 = 0) THEN
DISPLAY "The number is even."
ELSE
DISPLAY "The number is odd."
ENDIF
END
pseudocode for detecting Abnormal
Heart Rate

START
DISPLAY "Enter the heart rate (in beats per minute):"
READ heart_rate
IF heart_rate < 60 THEN
DISPLAY "Heart rate is below normal (bradycardia)."
ELSE IF heart_rate > 100 THEN
DISPLAY "Heart rate is above normal (tachycardia)."
ELSE
DISPLAY "Heart rate is normal."
ENDIF
END
pseudocode for calculating Body Mass
Index (BMI)
START
DISPLAY "Enter weight (in kilograms):"
READ weight
DISPLAY "Enter height (in meters):"
READ height
bmi ← weight / (height × height)

IF bmi < 18.5 THEN


DISPLAY "BMI:", bmi, " - Underweight"
ELSE IF bmi >= 18.5 AND bmi < 24.9 THEN
DISPLAY "BMI:", bmi, " - Normal weight"
ELSE IF bmi >= 25 AND bmi < 29.9 THEN
DISPLAY "BMI:", bmi, " - Overweight"
ELSE
DISPLAY "BMI:", bmi, " - Obesity"
ENDIF
END
Single line and multiline comments
• 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.
When and Why to use Comments in C programming?
• A person reading a large code will be confused 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.
Single line and multiline comments
Types of comments in C
In C there are two types of comments in C
language:

• Single-line comment
• Multi-line comment
Single line comments
Multiline comments
Single line and Multi line comments

In general, there are two types of comments in programming languages.


1. Single line comments
Single line comments is accomplished by double-slash (//). Everthing that is
followed by double-slash till the end of line is ignored by the compiler.
2. Multi line comments
Multi-line comments starts by using forward slash followed by asterisk (/*)
and ends by using asterisk followed by forward slash (*/). Everthing
between (/*) and (*/) are ignored by compiler whether it is one or more than
one line.
Single line and Multi line comments

Example:
/* This program takes age input from the user It stores it in the age variable
And, print the value using printf() */
#include <stdio.h>
int main() {
//declare integer variable
int age;
printf("Enter the age: ");
scanf("%d", &age);
printf("Age = %d", age);
return 0;
}
Basic Structure of C
Program
The sections of a C program are listed below:

❖ Documentation section

❖ Preprocessor section

❖ Definition section

❖ Global declaration

❖ Main function

❖ User defined functions


Basic Structure of C
Program
Documentation Section:
It includes statements such as a program's name, date, description, and title
that are specified at the start of the program.
Example:
//name of the program
(or)
/*
Specify the title and date
*/
It provides overview of the program. The Documentation section consists of a
set of comment lines.
Basic Structure of C
Program
Preprocessor Section:
All of the header files used in a program are found in the preprocessor section.
It informs the system that the header files should be linked to the system
libraries. It is provided by:
#include<stdio.h> // Defines core input and output functions
#include<string.h> // Defines string handling functions
#include<math.h> // Defines common mathematical functions
This section provides instruction to the compiler to link the header files or
functions from the system library.
Basic Structure of C Program
Definition Section:
The definition section defines all symbolic constants such by using the
#define directive.
#define a=5
Global Declaration Section:
There are some variables that are used in more than one function, such variables
are called global variables.
In C there are two types of variable declaration,
Local variable declaration: Variables that are declared inside the main function.
Global variable declaration: Variables that are declared outside the main
function.
float num = 2.54;
int a = 5;
char ch ='z';
Basic Structure of C
Program
Main Function Section:
Every C-program should have one main() function. main() is the first
function to be executed by the computer. It is necessary for a code to include
the main().
The main function is declared as:
main()
We can also use int or main with the main (). The void main() specifies that
the program will not return any value. The int main() specifies that the
program can return integer type data.
int main()
(or)
void main()
Basic Structure of C
Program
Main Function Section:
Main function is further categorized into local declarations,
statements, and expressions.
Local Declarations
The variable that is declared inside a given function or block refers to as local
declarations. main()
{
int i = 2; //local
variable
i++;
}
Basic Structure of C
Program
Main Function Section:
Statements:
The statements refers to if, else, while, do, for, etc. used in a program within
the main function.
Expressions:
An expression is a type of formula where operands are linked with each other
by the use of operators. It is given by:
a - b;
a +b;
Basic Structure of C
Program
User Defined Function:
It includes number of functions implemented in the program. For example,
color(), sum(), division(), etc.
Return statement is generally the last section of a code. But, it is not
necessary to include. It is used when we want to return a value. The return
function returns a value when the return type other than the void is specified
with the function.
return;
(or)
return expression;
For example
return 0;
/* Sum of two numbers */
Basic Structure of C
#include<stdio.h>
Program
Example: int main()
{
int a, b, sum;
printf("Enter two numbers to be
added ");
scanf("%d %d", &a, &b);
// calculating sum
sum = a + b;
printf("%d + %d = %d", a, b,
sum);
return 0; // return the integer
value in the sum
Executing a C Program
Input and Output Functions
 Ability to Communicate with Users during execution
 Input Operation
 Feeding data into program
 Data Transfer from Input device to Memory
 Output Operation
 Getting result from Program
 Data Transfer from Memory to Output device
 Header File : #include<stdio.h>
Input and Output Functions Contd…
 Input / Output Function Types
a) Formatted Input / Output Statements
b) Unformatted Input / Output Statements
Input and Output Functions Contd…
a) Formatted Input / Output Statements
 Reads and writes all types of data values
 Arranges data in particular format
 Requires Format Specifier to identify Data type
 Basic Format Specifiers
 %d – Integer
 %f – Float
 %c – Character
 %s - String
Input and Output Functions Contd…
i. The scanf ( ) Function
 Reads all types of input data
 Assignment of value to variable during Runtime
 Syntax

scanf(“Control String/Format Specifier”, &arg1, &arg2,… &argn)

 Control String / Format Specifier


 arg1, arg2.,,, arg n – Arguments (Variables)
 & - Address
Input and Output Functions Contd…

/* Giving Direct Input in /*Getting Input using scanf ( )


Program */ function */

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
int a; int a;
a=10; scanf(“%d”, &a);
} }
Input and Output Functions Contd…

/* Getting Multiple Input using /* Getting Multiple Different Inputs


scanf ( ) function */ using scanf ( ) function */
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
int a, b, c; int a, b;
scanf(“%d%d%d”,&a,&b,&c); float c;
} scanf(“%d%d%f”,&a,&b,&c);

}
Input and Output Functions Contd…
/* Getting Multiple Input using scanf ( ) function */
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b;
float c;
scanf(“%d %d”, &a, &b);
scanf(“%f ”, &c);
}
Input and Output Functions Contd…
ii. The printf ( ) Function
 To print Instructions / Output onto the Screen
 Requires Format Specifiers & Variable names to print
data

 Syntax

printf(“Control String/Format Specifier”,arg1,arg2,… argn)

 Control String / Format Specifier


 arg1, arg2.,,, arg n – Arguments (Variables)
Input and Output Functions Contd…
/* Example 1 – Using printf ( ) & scanf ( ) function */
#include<stdio.h>
#include<conio.h>
void main( )
{
int a;
printf(“Enter the Value of a”);
scanf(“%d”, &a);
printf(“Value of a is %d”, a);
getch( );
}
Input and Output Functions Contd…
/* Example 2 – Using printf ( ) & scanf ( ) function */
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b, c;
printf(“Enter the Value of a, b & c”);
scanf(“%d %d %d”, &a, &b, &c);
printf(“Value of a, b & c is %d%d%d”, a, b, c);
getch ( );
}
/* Example 3 – Using printf ( ) & scanf ( ) function */
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b;
float c;
printf(“Enter the Value of a & b”);
scanf(“%d %d”, &a, &b);
printf(“Enter the Value of a & b”);
scanf(“%f ”, &c);
printf(“Value of a, b is %d%d”, a, b);
printf(“Value of c is %f ”, c);
getch ( );
}
Input and Output Functions Contd…
/* Example 4 – Using printf ( ) & scanf ( ) function */
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b;
float c;
printf(“Enter the Value of a, b & c”);
scanf(“%d %d%f”, &a, &b, &c);
printf(“Value of a, b & c is %d%d%f”, a, b, c);
getch ( );
}
Input and Output Functions Contd…
 Try it Out Yourself ! Write a C program to:
1) Add two numbers
2) To Multiply two floating point numbers
3) To compute Quotient and Remainder

4) To Swap two numbers


Input and Output Functions Contd…
b) Unformatted Input / Output Statements
 Works only with Character Data type
 No need of Format Specifier
 Unformatted Input Statements
i. getch ( ) – Reads alphanumeric characters from
Keyboard
ii. getchar ( ) – Reads one character at a time till enter key
is pressed
.

Input and Output Functions Contd…


iii. gets ( ) – Accepts any string from Keyboard until Enter Key
is pressed

 Unformatted Output Statements


i. putch ( ) – Writes alphanumeric characters to Monitor
(Output Device)
ii. putchar ( ) – Prints one character at a time
iii. puts ( ) – Prints a String to Monitor (Output Device)
21CSS101J

PROGRAMMING FOR PROBLEM


SOLVING

Dr. R. Femi
Assistant Professor
Department of Electrical and Electronics Engineering
SRM Institute of Science and Technology,
Kattankulathur
Unit-1
Evolution of Programming & Languages - Problem solving
through programming - Writing algorithms & Pseudo code -
Single line and multiline comments - Introduction to C:
Structure of the C program - Input and output statements.

Variables and identifiers, Constants, Keywords - Values,


Names, Scope, Binding, Storage Classes - Numeric Data
types: integer, floating point Non-Numeric Data types: char
and string - L value and R value in expression,

Increment and decrement operator - Comma, Arrow and


Assignment operator, Bitwise and Size-of operator -
Arithmetic, Relational and logical Operators - Condition
Operators, Operator Precedence - Expressions
with pre / post increment operator
C Programming Fundamentals
C Programming Fundamentals Contd…
C Programming Fundamentals Contd…
 C Token - Smallest
individual unit of a C
program

 C program broken into


many C tokens
 Building Blocks of C
program
Keywords
 Keywords – Conveys special meaning to Compiler
 Cannot be used as variable names
Variables
Example of Variable
Identifiers
Rules for Naming Identifiers in C
Creating an Identifier for a Variable
Creating an Identifier for a Function
Constants
Example of Constants
Constants
 Definition :Value does not change during execution
 Can be a Number (or) a Letter
 Types
 Integer Constants
 Real Constants
 Character Constant
 Single Character Constants
 String Constants
Constants Contd…
Keywords
Values
Names
Scope

A block or a region where a variable is declared, defined and used and when a
block or a region ends, the variable is automatically destroyed.
#include <stdio.h>
int main()
{
int var = 34; // Scope of this variable is within main() function only.
// Therefore, called LOCAL to main() function.
printf("%d", var);
return 0;
}
Scope
Local Variables:
Variables that are declared within the function block and can be used only
within the function are called local variables.
Local Scope or Block Scope
A local scope or block is a collective program statement placed and declared
within a function or block (a specific area surrounded by curly braces). C also
has a provision for nested blocks, which means that a block or function can
occur within another block or function. So it means that variables declared
within a block can be accessed within that specific block and all other internal
blocks of that block but cannot be accessed outside the block.
Scope
Example (Local Variable):
#include <stdio.h>
int main ()
{
//local variable definition and initialization
int x,y,z;
//actual initialization
x = 20;
y = 30;
z = x + y;
printf ("value of x = %d, y = %d and z = %d\n",
x, y, z);
return 0;
}
Scope
Example (Global Variable):
#include <stdio.h>
int z; //global variable
int main ()
{
//local variable definition and initialization
int x,y;
//actual initialization
x = 20;
y = 30;
z = x + y;
printf ("value of x = %d, y = %d and z = %d\n", x, y, z);
return 0;
}
Binding
In C, binding refers to the association of a name with a particular entity, such
as a variable or a function. Binding is typically done through the use of
declarations or definitions in the code.
Example:
#include <stdio.h>
int main() {
int x = 5; // Binding the name 'x' to the value 5
printf("The value of x is: %d\n", x);
{
int x = 10; // Binding a new 'x' in a nested block
printf("The value of nested x is: %d\n", x);
}
printf("The value of x is still: %d\n", x); // Accessing the outer 'x'
return 0;
}
DATA TYPES

A data type specifies the type of data that a variable can store such as integer,
floating, character, etc.
DATA TYPES

Types Description

Basic They are arithmetic types and are further classified into:
Types (a) integer types and (b) floating-point types.

They are again arithmetic types, and they are used to


Enumerat
define variables that can only assign certain discrete
ed Types
integer values throughout the program.

The type specifier void indicates that no value is


void
available.

Derived They include (a) Pointer types, (b) Array types, (c)
Types Structure types, (d) Union types and (e) Function types.
DATA TYPES

Integer
Types
DATA TYPES

Integer Types
To get the exact size of a type or a variable on a particular platform, you can
use the sizeof operator. The expressions sizeof(type) yields the storage size
of the object or type in bytes.
DATA TYPES

Floating-Point
Types
DATA TYPES

The void
type
21CSS101J

PROGRAMMING FOR PROBLEM


SOLVING

Dr. R. Femi
Assistant Professor
Department of Electrical and Electronics Engineering
SRM Institute of Science and Technology,
Kattankulathur
Unit-1
Evolution of Programming & Languages - Problem solving
through programming - Writing algorithms & Pseudo code -
Single line and multiline comments - Introduction to C:
Structure of the C program - Input and output statements.

Variables and identifiers, Constants, Keywords - Values,


Names, Scope, Binding, Storage Classes - Numeric Data
types: integer, floating point Non-Numeric Data types: char
and string - L value and R value in expression,

Increment and decrement operator - Comma, Arrow and


Assignment operator, Bitwise and Size-of operator -
Arithmetic, Relational and logical Operators - Condition
Operators, Operator Precedence - Expressions
with pre / post increment operator
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

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
}
Operator Precedence
❖ The precedence of operators in C indicates the order in which the operators
will be evaluated in the expression.
❖ Associativity, on the other hand, defines the order in which the operators of
the same precedence will be evaluated in an expression. Also, associativity
can occur from either right to left or left to right.
❖ The precedence of operators determines which operator is executed first if
there is more than one operator in an expression.
OPERATORS

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


For example : a+b (or) 4+5
An operator is a symbol that instructs the compiler to perform specific
mathematical or logical functions.
OPERATORS
OPERATORS

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

- Subtraction

* Multiplication

/ Division

% Modulo division
OPERATORS

Arithmetic Operator
#include <stdio.h>
int main()
{ Output
int a = 10,b = 20, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
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;
}
OPERATORS

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

Relational Operators

Operato
Meaning of Operator
r
== Equal to

> Greater than

< Less than

!= Not equal to

>= Greater than or equal to

<= Less than or equal to


OPERATORS

Relational Operators

#include <stdio.h>
int main() {
int x = 5;
int y = 3;
printf("%d", x == y); // returns 0
(false) because 5 is not equal to 3
return 0;
}
OPERATORS

Relational Operators

#include <stdio.h>
int main() {
int x = 5;
int y = 5;
printf("%d", x == y); // returns 1
(true) because 5 is equal to 5
return 0;
}
OPERATORS

Relational Operators

#include <stdio.h>
int main() {
int x = 5;
int y = 3;
printf("%d", x != y); // returns 1
(true) because 5 is not equal to 3
return 0;
}
OPERATORS

Relational Operators

#include <stdio.h>
int main() {
int x = 5;
int y = 3;
printf("%d", x>y); // returns 1 (true)
because 5 is greater than 3
return 0;
}
OPERATORS

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

Logical Operators

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
OPERATORS #include <stdio.h>
int main()
{
Logical Operators
int a = 5, b = 5, c = 10,
result;
result = (a == b) && (c >
b);
printf(" %d \n", result);
result = (a == b) && (c <
b);
printf(" %d \n", result);
result = (a == b) || (c < b);
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;
}
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;
}
OPERATORS

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
#include <stdio.h>
operand.
int main()
{
int a = 10,b=6,c=12,d=15;
printf("a=%d \n", ++a);
printf("b=%d \n", --b);
printf("c=%d \n", ++c);
printf("d=%d \n", --d);
return 0;
}
OPERATORS

Increment and Decrement operator

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

Increment and Decrement operator

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

Comma operator
Comma operators are used to link related expressions together.
OPERATORS
sizeof operator
The sizeof is a unary operator that returns the
size of data (constants, variables, array, structure,
etc).
#include <stdio.h>
int main()
{
int a;
float b;
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;
}
21CSS101J

PROGRAMMING FOR PROBLEM


SOLVING

Dr. R. Femi
Assistant Professor
Department of Electrical and Electronics Engineering
SRM Institute of Science and Technology,
Kattankulathur
Unit-1
Evolution of Programming & Languages - Problem solving
through programming - Writing algorithms & Pseudo code -
Single line and multiline comments - Introduction to C:
Structure of the C program - Input and output statements.

Variables and identifiers, Constants, Keywords - Values,


Names, Scope, Binding, Storage Classes - Numeric Data
types: integer, floating point Non-Numeric Data types: char
and string - L value and R value in expression,

Increment and decrement operator - Comma, Arrow and


Assignment operator, Bitwise and Size-of operator -
Arithmetic, Relational and logical Operators - Condition
Operators, Operator Precedence - Expressions
with pre / post increment operator
Storage Classes
In C, a garbage value refers to an unpredictable or undefined value stored in a
variable before it has been explicitly initialized. When a variable is declared but not
assigned a specific value, the memory location it occupies may contain data left
over from previous operations. This leftover data is considered the garbage value.
Storage classes
Automatic
variable
Example:
auto int age;
int add(void)
{
int a=13;
auto int b=48;
return a+b;
}
Storage classes
Automatic variable
#include <stdio.h>
int main( )
{
auto int j = 1;
{
auto int j= 2;
{
auto int j = 3;
printf ( " %d ", j);
}
printf ( "\t %d ",j);
}
printf( "%d\n", j);
}
Storage classes
Global variable
#include <stdio.h>
void display();
int n = 5; // global variable
int main()
{
Output:
int n=10; n = 10
printf("n = %d\n", n); n=5
display();
return 0;
}
void display()
{

printf("n = %d", n);


}
EXPRESSIONS

In C, an expression is a set of operands and operators that computes a


single value stored in a variable. The operator represents the action or
operation to be carried out. The operands are the items to which the
operation is applied.
EXPRESSIONS

An expression can be defined depending on the position and number of its


operator and operands:
Infix Expression (operator is used between the operands)
a=x+y
Postfix Expression (operator is used after the operands)
xy+
Prefix Expression (operator is used before the operands)
+xy
Unary Expression (one operator and one operand)
x++
Binary Expression (one operator and two operands)
x+y
EXPRESSIONS

Types of Expression
EXPRESSIONS

Types of Expression

Arithmetic Expression
It consists of arithmetic operators ( + , - , * , and / ) and computes values
of int, float, or double type.

Relational Expression
It usually consists of comparison operators (> , < , >= , <= , === , and !==
) and computes the answer in the bool type, i.e., true (1) or false (0).

Logical Expression
It consists of logical operators (&&, ||, and !) and combines relational
expressions to compute answers in the bool type.
EXPRESSIONS

Types of Expression

Conditional Expression
It consists of conditional statements that return true if the condition is met
and false otherwise.

Pointer Expression
It may consist of an ampersand (&) operator and returns address values.

Bitwise Expression
It consists of bitwise operators ( >>, <<, ~, &, |, and ^ ) and performs
operations at the bit level.
EXPRESSIONS

#include <stdio.h>
int main(){
int a = (6 * 2) + 7 - 9; //Arithmetic Expression
printf("The arithmetic expression returns: %d\n", a);
int b = 10;
printf("The relational expression returns: %d\n", b % 2 == 0);
//Relational Expression
int c = (7 > 9) && ( 5 <= 9); //Logical Expression
printf("The logical expression returns: %d\n", c);
int d = (34 > 7) ? 1 : 0; //Conditional Expression
printf("The conditional expression returns: %d\n", d); //Pointer
Expression
int e = 20;
int *addr = &e;
printf("The pointer expression returns: %p\n", addr); //Bitwise
Expression
int f = 10;
int shift = 10 >> 1;
printf("The bitwise expression returns: %d\n", shift);
return 0;
}`
EXPRESSIONS

The arithmetic expression returns: 10


The relational expression returns: 1
The logical expression returns: 0
The conditional expression returns: 1
The pointer expression returns:
0x7ffdb0430704
The bitwise expression returns: 5
Operator Precedence
Let us consider an example:
int x=5-17*9;
In C, the precedence of * is higher than – and =. Hence, 17*9 is evaluated first.
Then – is evaluated and result is assigned to the variable x.
Operator Precedence
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & Right to left
sizeof
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= Right to left
<<= &= ^= |=
Comma , Left to right
Operator Precedence
Parentheses:
The expressions within parentheses are evaluated first. This allows you to
control the order of evaluation.
int result = (2 + 3) * 4; // result = 20
(2+3) is evaluated first and then it is multiplied with 4.
1) 2+3=5
2) 5*4=20

Postfix operators:
Postfix operators like function calls and array subscripting have higher
precedence than most other operators.
int arr[5] = {1, 2, 3, 4, 5};
int value = arr[2] * 3; // value = 9
arr[2]=3
3*3=9
Operator Precedence
Parentheses:
The expressions within parentheses are evaluated first. This allows you to
control the order of evaluation.
int result = (2 + 3) * 4; // result = 20
(2+3) is evaluated first and then it is multiplied with 4.
1) 2+3=5
2) 5*4=20

Postfix operators:
Postfix operators like function calls and array subscripting have higher
precedence than most other operators.
int arr[5] = {1, 2, 3, 4, 5};
int value = arr[2] * 3; // value = 9
arr[2]=3
3*3=9
Operator Precedence
Unary operators:
Unary operators, such as the increment (++) and decrement (--) operators, are
applied next.
int a = 5;
int result = ++a; // a becomes 6, (Right to Left)
result = 6
Multiplicative operators:
Multiplication (*), division (/), and modulo division (%) operators have
higher precedence than additive operators.
int result = 10 + 2 * 5; // result = 20 (multiplication is done first)
Additive operators:
Addition (+) and subtraction (-) operators are applied after the multiplicative
operators.
int result = 10 - 2 + 5; // result = 13 (subtraction is done first) (Left to Right)
Operator Precedence
Relational and equality operators:
These operators compare values and have higher precedence than logical
operators.
int result = 5 < 10 && 2 == 2; // result = 1 (true)
Order of Evaluation
1. 5<10 =>1(Hence 5 is less than 10)
2. 2==2=>1
3. Finally && is evaluated (1&&1)=1
Operator Precedence
Logical operators:
Logical AND (&&) and logical OR (||) operators are applied after relational
and equality operators.
int result = 5 < 10 || 2 > 5; // result = 1 (true)
Assignment operators:
Assignment operators (=, +=, -=, *=, /=, %=) are applied after all other
operators.
int a = 5;
a += 3; // a becomes 8
a=a+3;
a=5+3=>8
Conditional operator (ternary operator):
The conditional operator (?:) is evaluated after all other operators. It is used
for conditional expressions.
int a = 5; int result = (a > 10) ? a : 10; // result = 10
Assignment Operators
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.
Bitwise Operators in C

Operator Description Example

& (AND) Returns AND of input values a&b

| (OR) Returns OR of input values a|b

^ (XOR) Returns XOR of input values a^b

~ (Complement) Returns the one’s complement ~a


Bitwise Operators in C
Bitwise AND ‘&’
int a=2; //
0010
Truth Table
int b=3; //
0011
0010

int c=a & 0011


b; ---------
0010

Output:
2
Bitwise Operators in C
Bitwise OR ‘|’
int a=2; //
0010
Truth Table
int b=3; // 0010
0011 0011
---------
int c=a | b;
0011

Output:
3
Bitwise Operators in C
Bitwise XOR ‘^’ 0010

int a=2; // 0011


Truth Table 0010 ---------
int b=3; // 00 01
0011

int c=a ^ b;
Output:
1
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.
Bitwise Operators in C (Left
Shift)
Example: Binary Format 0 0 0 0 1 0 1 0
int
a=10; These two
bits will be
discarded 0 0
c=a<<2;
128 64 32 16 8 4
20 10 1 0 1 0 0 0
These two
places filled
32+8=40 with zeros
Bitwise Operators in C Right
Shift)
Example: Binary 0 0 0 0 1 0 1 0
int Format
a=10; These
two
0 0 bits
c=a>>2; Filled will be
with remov
zero’s ed.
128 64 32 16 8 4
20 10 0 0 0 0 1 0

2
Bitwise Operators in C

Program

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

printf("%d",10<<2);
return 0;
}
Output: 40
Bitwise Operators in C

Program

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

printf("%d",10>>2);
return 0;
}
Output: 2
21CSS101J

PROGRAMMING FOR PROBLEM


SOLVING

Dr. R. Femi
Assistant Professor
Department of Electrical and Electronics Engineering
SRM Institute of Science and Technology,
Kattankulathur
Unit-1
Evolution of Programming & Languages - Problem solving
through programming - Writing algorithms & Pseudo code -
Single line and multiline comments - Introduction to C:
Structure of the C program - Input and output statements.

Variables and identifiers, Constants, Keywords - Values,


Names, Scope, Binding, Storage Classes - Numeric Data
types: integer, floating point Non-Numeric Data types: char
and string - L value and R value in expression,

Increment and decrement operator - Comma, Arrow and


Assignment operator, Bitwise and Size-of operator -
Arithmetic, Relational and logical Operators - Condition
Operators, Operator Precedence - Expressions
with pre / post increment operator
Comma
Arrow
Bitwise Complement Operator (~ tilde)

You might also like