0% found this document useful (0 votes)
37 views

Pps Unit 1

The document discusses the evolution of programming languages from assembly language to modern languages like Python and Java. It also talks about the different approaches and steps involved in problem solving through programming, including understanding the problem, analyzing it, designing a solution, implementing the code, testing and debugging. The concept of algorithms and pseudocode are also introduced.

Uploaded by

Ajmal D
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)
37 views

Pps Unit 1

The document discusses the evolution of programming languages from assembly language to modern languages like Python and Java. It also talks about the different approaches and steps involved in problem solving through programming, including understanding the problem, analyzing it, designing a solution, implementing the code, testing and debugging. The concept of algorithms and pseudocode are also introduced.

Uploaded by

Ajmal D
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/ 48

lOMoARcPSD|30801605

PPS UNIT 1

Computer Science (SRM Institute of Science and Technology)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Ajmal D ([email protected])
lOMoARcPSD|30801605

SRM INSTITUTE OF SCIENCE & TECHNOLOGY

DEPARTMENT OF COMPUTING TECHNOLOGIES

21CSS101J
PROGRAMMING FOR PROBLEM SOLVING

for
BE/BTECH I SEM

S.PRABU
Assistant Professor
C-TECH-SRM-IST-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

01

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

Topic: 1 Evolution of Programming & Languages

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: The Evolution of Programming Languages – Assembly Language


It is a type of low-level language.
A processor understands only machine language instructions, which are combination
of 1's and 0's.
However, machine language is too obscure and complex for using in software
development.
So, the low-level assembly language is designed for a specific family of processors
that represents various instructions in symbolic code and a more understandable form.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

02

1952: Autocode
Developed by Alick Glennie.
The first compiled computer programming language.
COBOL and FORTRAN are the languages referred to as Autocode.

1957: Development of Computer Language – 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 to implement 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.
COBOL was one of the first programming languages designed for use in business and
finance.
It was created as part of a US Department of Defence effort to create a portable
programming language for data processing.

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.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

03

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.

After 1980s
The object oriented programming languages are developed
C++
Java
Dot Net
Python

What are the two main types of programming?


Two types of Languages is categorised on the basis of their usage-
1. High Level Language
2. Low Level Language

High Level Language


It enables a programmer to write programs that are more or less independent of a
particular type of machine.
Such languages are considered high-level because they are closer to human languages
and further from machine languages. Eg - Python, Java, etc.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

04

Low level Language


It is a programming language that provides little or no abstraction of programming
concepts and is very close to writing actual machine instructions.
A low level language does not need a compiler or interpreter to run the program.
Eg - Assembly language.

Topic: 2 Problem Solving Through Programming

Programming languages and computational thinking to analyze, design, and


implement solutions to various challenges.
Here's a step-by-step approach to problem-solving through programming:

Understand the Problem:


Clearly define the problem you need to solve. Break it down into smaller, manageable
components.
Gather any requirements, constraints, or specifications related to the problem.

Analyze the Problem:


Examine the problem thoroughly to understand its context and the desired outcome.
Identify the input data or variables needed and the expected output.

Plan Your Approach:


Decide on the appropriate programming language for the task.
Choose the appropriate algorithms, data structures, and programming paradigms (e.g.,
procedural, object-oriented, functional) based on the problem's nature.

Design Your Solution:


Create a high-level design of your program's structure, including the main steps,
functions, and classes if applicable.
Design data structures to store and manipulate the necessary data.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

05

Break Down the Problem:


Divide the problem into smaller sub-problems or tasks that can be tackled
individually.
Identify dependencies between these sub-problems.
Implement the Solution:
Write the code according to your design, addressing each sub-problem one at a time.
Use meaningful variable and function names, and follow coding standards for
readability.

Debug and Test:


Test your code thoroughly with different input data, including edge cases and corner
cases.
Debug and fix any issues that arise during testing.

Validate Your Solution:


Verify that your program produces the expected output for various input scenarios.
Check if your program meets the requirements and constraints provided.

Topic : 3 Writing algorithms & Pseudo code

Algorithm
A step by step procedure to solve a particular problem.
It is a ordered set of rules to solve a problem.
finite set of instructions which are being carried in a specific order to perform the
specific task

Need
Algorithms are necessary for solving complex problems efficiently and effectively.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

06

Advantages of Algorithms
In an Algorithm the problem is broken down into smaller pieces or steps hence, it is
easier for the programmer to convert it into an actual program.
Due to stepwise representation, it is easy to understand.

Disadvantages of Algorithms:
Writing an algorithm takes a long time so it is time-consuming.
Branching and Looping statements are difficult to show in Algorithms(imp).

How to Design an Algorithm?


To write an algorithm, the following things are needed as a pre-requisite:
The problem that is to be solved by this algorithm i.e. clear problem definition.
The constraints of the problem must be considered while solving the problem.
The input to be taken to solve the problem.
The output is to be expected when the problem is solved.
The solution to this problem is within the given constraints.

Features of the algorithm


Algorithms must receive inputs that can be represented as values or
inputs :
data.
The algorithm should produce some output. It can be a consequence
Output :
of a problem or a solution designed to solve it.
Algorithms must be precisely defined, using unambiguous instructions
Clarity :
that a computer or other system can follow unambiguously.
The algorithm requires limited steps. It means that it should be exited
Finiteness :
after executing a certain number of commands.
The algorithm must be valid. In other words, it should be able to
Validity : produce a solution to the problem that the algorithm is designed to
solve in a reasonable amount of time.
An algorithm must be effective, meaning that it must be able to
Effectiveness : produce a solution to the problem it is designed to solve in a
reasonable amount of time.
An algorithm must be general, meaning that it can be applied to a
Generality :
wide range of problems rather than being specific to a single problem.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

07

Example
Addition of two numbers
Step 1: Start
Step 2: Declare three variables a, b, and c.
Step 3: Enter the values of a and b.
Step 4: Add the values of a and b and store the result in the c variable,
i.e., c=a+b.
Step 5: Print c
Step 6: Stop

Write a algorithm to find the simple interest


Step 1: Start
Step 2: Declare four variables p,n,r , and si.
Step 3: Enter the values of p,n and r.
Step 4: using the formula si=(p*n*r)/100, find si and store the result in
the si variable,
Step 5: Print si
Step 6: Stop

PSEUDO CODE
Methodology to represent the implementation of an algorithm.”
It is written in the form of annotations and informational text that is written in plain
English only.
Just like programming languages, it doesn't have any syntax, so it cannot be compiled
or interpreted by the compiler.
It is a methodology that allows the programmer to represent the implementation of an
algorithm.
Simply, we can say that it’s the cooked up representation of an algorithm.
Often at times, algorithms are represented with the help of pseudo codes as they can
be interpreted by programmers no matter what their programming background or
knowledge is.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

08

Write a pseudo code to find the Addition of two Numbers


BEGIN
NUMBER a, b, sum
INPUT a,b,c
sum=a+b;
OUTPUT sum
END

Write a pseudo code to find the simple interest


BEGIN
NUMBER a, b, sum
INPUT p, n, r, si
si =; (p*n*r)/100;
OUTPUT si
END

Advantages of Pseudo code


Acts as a bridge between the program and the algorithm
The main goal of a pseudo code is to explain what exactly each line of a program
should do, hence making the code construction phase easier for the programmer.

Algorithm Pseudo Code


1 Step by Step procedures No steps, it is a next stage of algorithm.
2 It is represented by natural language It is represented by notations.
Looks like a descriptions to define the Looks like a program, but not contain its
3
steps to solve a problem. syntax

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

09

Topic : 4 Comments

Comments in C language are used to provide information about lines of code. It is


widely used for documenting code. There are 2 types of comments in the C language.
Single Line Comments
Multi-Line Comments

Single Line Comments


Single line comments are represented by double slash \\.
Let's see an example of a single line comment in C.

#include<stdio.h>
int main()
{
//printing information
printf("Hello C");
return 0;
}

Multi Line Comments


Multi-Line comments are represented by slash asterisk \* ... *\.
It can occupy many lines of code, we can give more description.

/*
code
to be commented
*/

Why do you need comments?


A good programmer who writes codes understood by a human is better than a
programmer who generates codes understood only by the machine.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

10

So, it is highly recommended to insert comments to your code because it is good


programming practice.
Comments do not affect a program because the compiler ignores them.
Comments help the developer understand the logic/algorithm of the code if he revisits
it after a long time.

Topic : 5 Structure of the C program

The structure of the C program may be

Content Code
Documentation // Addtion of 2 Numbers
#include <stdio.h>
Pre-processor Section
#define c 10
Global Declaration float pi=3.144;
Main function void main ( )
{
variable Declaration int a,b,c;
Input statement Scanf(“%d%d”, &a,&b);
Execution part c=a+b;
Output statement Printf(“Addition is: %d”,c);
}

void printdemo(void)
Sub Program
{ Printf(“Demo”); }

1. Documentation
This section consists of the description of the program, the name of the program, and
the creation date and time of the program.
It is specified at the start of the program in the form of comments. Documentation can
be represented as:
// description, name of the program, programmer name, date, time etc.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

11

Pre-processor Section
All the header files of the program will be declared in the pre-processor section of the
program.
Header files help us to access other’s improved code into our code.
A copy of these multiple files is inserted into our program before the process of
compilation.

Example:
#include<stdio.h>
#include<math.h>

#define is also a preprocessor to define a particular value before the main function.
#include <stdio.h>
#define a 10
int main()
{
printf("%d",a);
return 0;
}

Main() Function
Every C program must have a main function.
The main() function of the program is written in this section.
Operations like declaration and execution are performed inside the curly braces of the
main program.

void main()
{
Statements;
}

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

12

Sub Programs
User-defined functions are called in this section of the program.
The control of the program is shifted to the called function whenever they are called
from the main or outside the main() function.
These are specified as per the requirements of the programmer.

Topic : 6 Input and output statements

Input and Output statement are used to read and write the data in C programming.
These are embedded in stdio.h (standard Input/Output header file).
Input means to provide the program with some data to be used in the program.
Output means to display data on screen or write the data to a printer or a file.
C programming language provides many built-in functions to read any given input and
to display data on screen when there is a need to output the result.
There are mainly two of Input/Output functions are used for this purpose. These are
discussed as:
Formatted I/O functions
Unformatted I/O functions

Formatted I/O functions


Formatted I/O functions are used to take various inputs from the user and display
multiple outputs to the user.
These types of I/O functions can help to display the output to the user in different
formats using the format specifiers.
These I/O supports all data types like int, float, char, and many more.

Format specifier: It is a way to tell the compiler what type of data is in a variable.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

13

Format Specifier Data Type Used to speficy


%d short short decimal integer
%d int A decimal integer
%ld long Long decimal integer
%f float Single floating point number
%lf double Double floating point number
%Lf long double long double
%c char A single character
String or collection of
%s string
character

There are mainly two formatted I/O functions discussed as follows:


scanf()
printf()

scanf() statement
The scanf() function is an input function.
It used to read the mixed type of data from keyboard.
You can read integer, float and character data by using its control codes or format
codes. The general syntax is as:

scanf(“format_specifier”,&var_name);

Example : scanf(“%d”,&a);
%d for integer, %f for float, %c for character
& : it is the address operator, tells the location of the variable.
a : is a integer variable.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

14

printf() statement
This is an output function.
It is used to display a text message and to display the mixed type (int, float, char) of
data on screen.
The general syntax is as:

printf(“format_specifier”,var_name);

Example : printf(“%d”,a);
Format specifier: It is a way to tell the compiler what type of data is in a variable.
%d for integer, %f for float, %c for character
a : is a integer variable.

Unformatted I/O functions


There are mainly six unformatted I/O functions discussed as follows:
getchar() : Reads a single character from standard input
putchar() : Displays a single character to standard outout
gets() Reads a single string entered by the user at the console.
puts() Displays a single string's value at the console.
getch() Reads a single character from any input console,
putch() Displays a single character value to any output console.

Sample Program for getchar( ) and putchar( )

#include <stdio.h>
void main()
{
char a;
printf(“Enter a single character: ”);
a=getchar();

printf(“The entered character is : ”);


putchar(a);
}

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

15

Output :
Enter a single character: e
The entered character is : e

Sample Program for getch( ) and putch( )

#include <stdio.h>
void main()
{
char a;
printf(“Enter a single character: ”);
a=getch();

printf(“The entered character is : ”);


putch(a);
}

Output :
Enter a single character: The entered character is : r
Note: It does not need to press enter key to execute the next step, it immediately show
the result.

Difference between getchar( ) and putchar( )

getchar( ) getch( )
1 Reading character from standard input Reading character from any input console
2 It use the buffer It doesn’t use buffer
the entered character returns after the the entered character returns immediately
3
enter key is pressed. without having to wait for the enter key

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

16

Sample Program for gets( ) and puts( )

#include <stdio.h>
void main()
{
char a[10];
printf("Enter a string: ");
gets(a);

printf("The entered string is : ");


puts(a);
}

Output : Enter a string: India


The entered string is : India

Topic : 7 Variables and identifiers, Constants, Keywords

VARIABLE
variables are the storage place where some form of data is stored.
Different variables require different amount of memory on which a set of operations
is applied.
Example. Integer, float, double
How to declare variable (or) syntax for variable declaration
data_type variable_name;
int a;
A variable is a name associated with some memory location.
A variable is used to hold some value that can be changed according to the
requirement.
During program execution, there will be storing of some data in different locations of
memory in computer.
These memory locations are identified by their address like 56234.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

17

We cannot remember all the addresses of variables, during program.


There is a need to give user friendly name to that memory location.
So variables are nothing but the name of the locations or addresses of memory which
is given by programmer

CONSTANT

As its name suggests constants are the values which will never change during the
execution of program.
Those variables which cannot be modified once they are defined in the program.
syntax for constant declaration
const data_type variable_name = value;
Example: const int a=10;
A constant is used to hold the fixed values which we can retrieve later but cannot
change.
They have fixed values till the program’s life.
We can only assign value to the constant in the declaration.

KEYWORDS
Keywords are predefined, reserved words used in programming that have special
meanings to the compiler.
Keywords are part of the syntax and they cannot be used as an identifier.
There are total 32 keywords in C.
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

18

IDENTIFIER

Identifiers in C language represent the names of various entities such as arrays,


functions, variables, user-defined data types, labels, etc.
An identifier is a type of string of alphanumeric characters that always begins with
either an alphabetic or underscore character.

Rules For Naming Identifiers in C


There are specific rules for naming the identifiers in C language.
We cannot use any keyword as an identifier.
Identifiers cannot start with a digit.
The first character of an identifier should always start with an alphabet or underscore.
The special characters such as '*','#','@','$' are not allowed within an identifier.
All the identifiers are case sensitive means the identifiers "hello" and "Hello" will be
treated differently.
Length of an identifier should not exceed 31 characters.
Any blank spaces or commas are not allowed within an identifier.

Topic : 8 Values, Names, Scope, Binding,

A. Name: Identifiers that allow us to refer to variables, constants, functions, types,


operations, and so on
B. Value : The actual value it can be hold.
C. Binding: An association of a name with an object
D. Scope: The lifetime of a binding of a name to an object

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

19

Topic : 9 Storage Classes

The scope of a variable in C is the block or the region in the program where a
variable is declared, defined, and used.
Outside this region, we cannot access the variable and it is treated as an undeclared
identifier.
A storage class represents the visibility and a location of a variable. It tells from what
part of code we can access a variable.
A storage class in C is used to describe the following things:
• The variable scope.
• The location where the variable will be stored.
• The initialized value of a variable.
• A lifetime of a variable.
• Who can access a variable?

Storage class Purpose


auto It is a default storage class, and local variable.
extern It is a global variable.
It is a local or global variable which is capable of returning a value even
static
when control is transferred to the function call.
register It is a variable which is stored inside a Register.

AUTO

The variables defined using auto storage class is called as local variables.
Auto stands for automatic storage class.
A variable is in auto storage class by default if it is not explicitly specified.
The scope of an auto variable is limited with the particular block only.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

20

Once the control goes out of the block, the access is destroyed.
This means only the block in which the auto variable is declared can access it.
A keyword auto is used to define an auto storage class.
By default, an auto variable contains a garbage value.

Example: auto int age;

Program example

#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);
}
Output : 3 2 1

EXTERN

Extern stands for external storage class.


Extern storage class is used when we have global functions or variables which are
shared between two or more files.
Keyword extern is used to declaring a global variable or function in another file to
provide the reference of variable or function which have been already defined in the
original file.
The variables defined using an extern keyword is called as global variables.
These variables are accessible throughout the program.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

21

Notice that the extern variable cannot be initialized it has already been defined in the
original file.

Example, extern void display();

First File: main.c


#include <stdio.h>
extern i;
main()
{
printf("value of the external integer is = %d\n", i);
return 0;
}

Second File: original.c


#include <stdio.h>
i=48;

Result:
value of the external integer is = 48
here the enternal variable ‘i’ can be shared both the files. The value can be
modified in one file to another.

STATIC

The static variables are used within function/ file as local static variables.
They can also be used as a global variable
Static local variable is a local variable that retains and stores its value between
function calls or block and remains visible only to the function or block in which it is
defined.
Static global variables are global variables visible only to the file in which it is
declared.
Example: static int count = 10;

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

22

Keep in mind that static variable has a default initial value zero and is initialized
only once in its lifetime.

Static local variable


#include<stdio.h>
int fun()
{
static int count = 0;
count++;
return count;
}

int main()
{
printf("%d ", fun());
printf("%d ", fun());
printf("%d ", fun());
return 0;
}

Output : 1 2 3
Static variables initialized once and retains the values, its never reset again.

Static global variable


#include<stdio.h>
static int count = 0;
int fun1()
{
count++;
return count;
}
int fun2()
{
count++;
return count;

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

23

}
int fun3()
{
count++;
return count;
}

int main()
{
printf("%d ", fun1());
printf("%d ", fun2());
printf("%d ", fun3());
return 0;
}
Output : 1 2 3
Here Static variable is globally declared and shared by different functions.

REGISTER

Register variables tell the compiler to store the variable in CPU register instead of
memory.
Frequently used variables are kept in registers and they have faster accessibility.
We can never get the addresses of these variables. “register” keyword is used to
declare the register variables.
#include <stdio.h>
int main()
{
register int a = 10;
auto int b = 8;
printf("The value of register variable a : %d \n",a);
printf("The value of auto variable b : %d \n",b);
printf("The sum of auto and register variable : %d\n",(a+b));
return 0;
}

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

24

Output:
The value of register variable a : 10
The value of auto variable b : 8
The sum of auto and register variable : 18

Topic : 10 Data Types

Data types are declarations for variables.


This determines the type and size of data associated with variables.
It should mention which type of data we are going to use.
We do so because we must specify the type of data that is in use, so that the compiler
knows exactly what type of data it must expect from the given program
A data type specifies the type of data that a variable can store such as integer,
floating, character, etc.

There are the following data types in C language.


Types Data Types
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum
Void Data Type void

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

25

Basic Data Types


The data type specifies the size and type of information the variable will store.
Data Type Size Description
int 2 or 4 bytes Stores whole numbers, without decimals
float 4 bytes Stores fractional numbers, containing one
or more decimals. Sufficient for storing 6-
7 decimal digits
double 8 bytes Stores fractional numbers, containing one
or more decimals. Sufficient for storing 15
decimal digits
char 1 byte Stores a single character/letter/number, or
ASCII values

Basic Format Specifiers


There are different format specifiers for each data type. Here are some of them:

Format Specifier Data Type


%d int
%lu Long integer
%f float
%lf double
%c char
%s Used for strings (text)

Derived Data Type


Beyond the fundamental data types, C also supports derived data types, including
arrays, pointers, structures, and unions.
These data types give programmers the ability to handle heterogeneous data, directly
modify memory, and build complicated data structures.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

26

Enumeration Data Type


A set of named constants or enumerators that represent a collection of connected
values can be defined in C using the enumeration data type (enum).
Enumerations give you the means to give names that make sense to a group of
integral values, which makes your code easier to read and maintain.

Void Data Type


This term refers to no values at all. We mostly use this data type when defining the
functions in a program.

Type Cast
Type casting is the process in which the compiler converts one data type in a program
to another one.
It is otherwise called as Type Conversion.

Types
• Implicit Type Conversion
• Explicit Type Conversion

Implicit Type Conversion


One data type is automatically convert into another data type.
if a programmer wants to store a int variable value into some other type like float,
then the value is automatically converted into float (adding zeros in fractional part)

#include <stdio.h>
void main()
{
int a=5;
float b;
b=a;
printf("a= %d \n",a);
printf("b= %f",b);}
}

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

27

Output :
a= 5
b= 5.000000
b value is assigned with necessary zeros in fractional part.

Explicit Type Conversion


we have to force the conversion between data types.
This type of casting is explicitly defined within the program.

#include <stdio.h>
void main()
{
int a = 15, b = 2;
float div;
// Division of a and b
div = (float)(a / b);
printf("The result is %f\n", div);
}
Output : The result is 7.000000
Here we explicitly convert the integer result into float.

Program for converting char to integer


#include <stdio.h>
void main()
{
char c='a';
int a;
a=(int)c;

printf("character is %c\n", c);


printf("Integer is %d\n", a);
}
Output:
character is a
Integer is 97

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

28

Topic : 11 Operators

Operators can be defined as the symbols that help us to perform specific operation.
In other words, we can say that an operator operates the operands.
For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands.
The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.

Based on the operation, the operators are classified as


1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Special Operators

Arithmetic Operators

Arithmetic operators are the symbols that can be used to perform common
mathematical operations such as addition, subtraction etc.

Operator Meaning of Operator


+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division (modulo division)

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

29

Example Program :
// Working of arithmetic operators
#include <stdio.h>
void main( )
{
int val1 = 10,val2 = 5; // input variables
int add,sub,mul,div,rem,inc,dec; //result variables

add = val1 + val2;


printf("Addition = %d \n",add);

sub = val1 - val2;


printf("Subtraction = %d \n",sub);

mul = val1 * val2;


printf("Multiplication = %d \n",mul);

div = val1 / val2;


printf("Division = %d \n",div);

rem = val1 % val2;


printf("Remainder = %d \n",rem);

inc = ++val1;
printf("Increment is %d \n",inc);

dec = --val2;
printf("Decrement is %d \n",dec);
}

Output: Addition = 15
Subtraction = 5
Multiplication = 50
Division = 2
Remainder = 0
Increment is 11
Decrement is 4

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

30
Relational Operators

A relational operator checks the relationship between two operands.


It compare the operands and return either 1(true) or 0(false).
It helps to take decisions.

A list of all comparison operators:

Operator Name Example


> Greater than x>y
< Less than x<y
Greater than or equal
>= x >= y
to
<= Less than or equal to x <= y
== Equal to x == y
!= Not equal x != y

Example Program :
// Working of Relational operators
#include <stdio.h>
void main( )
{
int a = 100, b = 50; // input variables

if(a>b)
{
printf("Using > Symbol: ");
printf("A(%d) is Bigger\n",a);
}
if(a>=10)
{
printf("Using >= Symbol: ");
printf("A(%d) is Greater than or Equalt to 100\n",a);
}
if(b<a)
{
printf("Using < Symbol: ");

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

31

printf("B(%d) is SMALLER\n",b);
}
if(b<=50)
{
printf("Using <= Symbol: ");
printf("B(%d) is Less than or Equalt to 50\n",b);
}
if(a==100)
{
printf("Using == Symbol: ");
printf("A(%d) is Equal to 100\n",a);
}
if(b!=100)
{
printf("Using != Symbol: ");
printf("B(%d) is NOT Equal to 100\n",b);
}
}
Output

Using > Symbol: A(100) is Bigger


Using >= Symbol: A(100) is Greater than or Equalt to 100
Using < Symbol: B(50) is SMALLER
Using <= Symbol: B(50) is Less than or Equalt to 50
Using == Symbol: A(100) is Equal to 100
Using != Symbol: B(50) is NOT Equal to 100

Logical Operators

Logical operators are used to determine the logic between variables or values:
Logical Operators are used to combining two or more conditions/constraints or to
complement the evaluation of the original condition in consideration.
The result of the operation of a logical operator is a Boolean value either true or false.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

32

Operator Meaning Example


Logical AND.
If c = 5 and d = 2 then, expression
&& True only if all operands are
((c==5) && (d>5)) equals to 0.
true
Logical OR.
If c = 5 and d = 2 then, expression
|| True only if either one operand
((c==5) || (d>5)) equals to 1.
is true
Logical NOT. If c = 5 then, expression
!
True only if the operand is 0 !(c==5) equals to 0.

Example Program :
// Pgm for validating entered data. Application of logical operator
#include <stdio.h>
void main()
{
int age, mark;
printf ("Enter your age: ");
scanf ("%d", &age);
printf ("Enter your mark: ");
scanf ("%d", &mark);

if (mark < 0 || mark > 100)


{
printf ("The entered Mark is invalid: it is out of range\n");
}
if(mark >=0 && mark<=100)
{
printf ("The entered Mark is Valid\n");
}
if(!((age<=0) || (age>=100)) )
{
printf ("The entered Age is Valid\n");
}
else
{
printf ("The entered Age is InValid\n");
}
}

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

33

Output:
Enter your age: -56
Enter your mark: 234
The entered Mark is invalid: it is out of range
The entered Age is InValid

Enter your age: 45


Enter your mark: 88
The entered Mark is Valid
The entered Age is Valid

Bitwise Operators

The bitwise operators are the operators used to perform the operations on the data at
the bit-level.
These operators work at a low level, directly manipulating the binary representation
of data.
It consists of two numbers, either 0 or 1.
To speed up calculations, it is mostly used in numerical computations.
We have different types of bitwise operators in the C programming language.
The following is the list of the bitwise operators:

Operator Meaning of operator


& Bitwise AND operator
| Bitwise OR operator
^ Bitwise exclusive OR operator
~ One's complement operator (unary operator)
<< Left shift operator
>> Right shift operator

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

34

Let's look at the truth table of the bitwise operators.

X Y X&Y X|Y X^Y


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 1

AND : This operator results in 1 when the values of both the bits are 1.
OR : This operator results in 1 when the any one of the bits is 1.
XOR : This operator results in 0 when the both bits are same.
1 when both bits are unique
NOT : The calculation is done with the help of expression – (n+1).
L Shift : It is used to shift all the bits to the left by a specified number of bits.
R Shift : It is used to shift all the bits to the right by a specified number of bits.

// Pgm for demonstrating bitwise & Operator


#include <stdio.h>
void main()
{
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int band = a & b;
int bor = a | b;
int bxor = a ^ b;
int bnot= ~a;
int lshift=a<<2;
int rshift=b>>2;

printf("Result of Bitwise AND Operator is: %d\n", band);

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

35

printf("Result of Bitwise OR Operator is: %d\n", bor);


printf("Result of Bitwise XOR Operator is: %d\n", bxor);
printf("Result of Bitwise NOT Operator is: %d\n", bnot);
printf("Result of Bitwise Lshift Operator is: %d\n", lshift);
printf("Result of Bitwise Rshift Operator is: %d\n", rshift);
}

Output:
Result of Bitwise AND Operator is: 1
Result of Bitwise OR Operator is: 7
Result of Bitwise XOR Operator is: 6
Result of Bitwise NOT Operator is: -6
Result of Bitwise Lshift Operator is: 20
Result of Bitwise Rshift Operator is: 0

Assignment Operators

It is the operator used to assign the right side operand or variable to the left side
variable.
Equals (=) operator is the most commonly used assignment operator.
For example: int i = 10;
• the value 10 is assigned in to varibale i.
The below table displays all the assignment operators present in C Programming with
an example.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

36

Assignment Operators Example Explanation

= x = 25 Value 25 is assigned to x

+= x += 25 This is the same as x = x + 25

-= x -= 25 This is the same as x = x – 25

*= y *= 25 This is the same as y = y * 25

/= y /= 25 This is the same as y = y / 25

%= y%= 25 This is the same as y = y % 25

Example Program

// Pgm for demonstrating assignment operators


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

printf("a=%d,b=%d ",a,b);
c = a;
printf("Assignment of b=a is %d \n",c);

printf("a=%d,b=%d ",a,b);
a+=b; // a=a+b;
printf("(a=a+b)Value of a now = %d\n", a);

printf("a=%d,b=%d ",a,b);
a-=b; // a=a-b;
printf("(a=a-b)Value of a now = %d\n", a);

printf("a=%d,b=%d ",a,b);
a*=b; // a=a*b;
printf("(a=a*b)Value of a now = %d\n", a);

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

37

printf("a=%d,b=%d ",a,b);
a/=b; // a=a/b;
printf("(a=a/b)Value of a now = %d\n", a);

printf("a=%d,b=%d ",a,b);
a%=b; // a=a%b;
printf("(a=a%%b)Value of a now = %d\n", a);
}

Output:
a=10,b=20 Assignment of b=a is 10
a=10,b=20 (a=a+b)Value of a now = 30
a=30,b=20 (a=a-b)Value of a now = 10
a=10,b=20 (a=a*b)Value of a now = 200
a=200,b=20 (a=a/b)Value of a now = 10
a=10,b=20 (a=a%b)Value of a now = 10

Special Operators

Special operators in C programming are operators that are used for unique purposes
and are not usually utilized in standard programming jobs.
Here are a few examples of C special operators:

operator Meaning

sizeof to compute the size of its operand

& (ampersand) To specify the address of the variable

, (comma) Acts as a separator

. (dot) To access the member of structure

* (asterisk) Acts as a pointer of the variable

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

38

Example Program:
// Pgm for demonstrating size of operator
#include <stdio.h>
void 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));
}

Output:
Size of int=4 bytes
Size of float=4 bytes
Size of double=8 bytes
Size of char=1 byte

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

39

Based on the number of operands, the operators are classified as


1. Unary operators
2. Binary operators
3. Ternary operators

Unary Operators

A unary operator operates on only a single operand.


Unary operators are the operators that perform operations on a single operand to
produce a new value.
1. Unary minus ( - )
2. Increment ( ++ )
3. Decrement ( - - )

1.Unary Minus
The minus operator ( – ) changes the sign of its argument.
A positive number becomes negative, and a negative number becomes positive.
int a = 10;
int b = -a; // b = -10
Unary minus is different from the subtraction operator, as subtraction requires two
operands.

2.Increment
The increment operator ( ++ ) is used to increment the value of the variable by 1.
The increment can be done in two ways:
• Prefix increment
• Postfix increment

prefix increment
In this method, the operator precedes the operand (e.g., ++a).
The value of the operand will be altered before it is used.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

40

Example:
int a = 1;
int b = ++a; // b = 2
postfix increment
In this method, the operator follows the operand (e.g., a++).
The value operand will be altered after it is used.

Example:
int a = 1;
int b = a++; // b = 1
int c = a; // c = 2

3.Decrement
The decrement operator ( — ) is used to decrement the value of the variable by 1.
The decrement can be done in two ways:
• Prefix decrement
• Postfix decrement

prefix decrement
In this method, the operator precedes the operand (e.g., – -a).
The value of the operand will be altered before it is used.

Example:
int a = 1;
int b = --a; // b = 0

postfix decrement
In this method, the operator follows the operand (e.g., a- -). The value of the operand
will be altered after it is used.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

41

Example:

int a = 1;
int b = a--; // b = 1
int c = a; // c = 0

Example Program:
// Pgm for demonstrating unary operator
#include <stdio.h>
void main()
{
int a = 10,b,c;

//unary minus
b = -a;
printf("b value is: %d\n",b);

//increment
b=++a;
printf("a value after increment: %d\n",b);

//decrement
c=--a;
printf("a value after deccrement: %d\n",c);
}

Output:
b value is: -10
a value after increment: 11
a value after deccrement: 10

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

42

Binary Operators

Binary operators act upon a two operands to produce a new value.


<refer arithmetic, relational, bitwise operators exmple in previous topic>

Ternary Operators

Ternary Operator in C takes three arguments:


The first argument in the Ternary Operator in C is the comparison condition.
The second argument in the Ternary Operator in C is the result if the condition is
true.
The third argument in the Ternary Operator in C is the result if the condition is false.
Using the Ternary operator in c is a way to shorten the if-else code block.
Syntax: condition ? exp1 : exp2
If the condition in the ternary operator is met (true), then the exp1 executes.
If the condition is false, then the exp2 executes.
It is also called conditional operator
Example Program:
// Pgm for demonstrating unary operator
#include <stdio.h>
void main()
{
int a=10;
int b=a%2;
(b==0)? printf("a is even") : printf("a is odd");
}

Output: a is even

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

43

Operator Precedence

The precedence of operators in C dictates the order in which the operators will be
evolved in an expression.
Operator precedence determines the grouping of terms in an expression and decides
how an expression is evaluated.
Certain operators have higher precedence than others;
for example, the multiplication operator has a higher precedence than the addition
operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a
higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom.
Within an expression, higher precedence operators will be evaluated first.

Operator Precedence Hierarchy


I. First, parenthesized sub expression from left to right are evaluated.
If parentheses are nested, the evaluation begins with the innermost sub-expression.
Ex1. c = d * (a+b); //here a+b is first evaluated.
Ex2. c = a+(b+(d*e)); // here d*e is first evaluated.

II. When two or more operators of the same precedence level appear, then
associativity rule applied, i.e, evaluation happens from left to right.
c = a * b * d; //a * b is first evaluated
The priority is listed below

Priority Operator
1 ( ),[ ]
2 ++, --, -
3 *, / , %, + , -
4 << , >>
5 =

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

44

Topic : 12 Expression

An expression in C is a combination of operands and operators – it computes a single


value stored in a variable.
The operator denotes the action or operation to be performed.
The operands are the items to which we apply the operation.
Ex. c = a + b;
Here a,b,c are operands, and + & = are operators.

Evaluation Of Expressions
Expressions are evaluated using an assignment statement of the form:
variable = expression;

Variable is any valid C variable name.


When the statement is encountered, the expression is evaluated first and the result
then replaces the previous value of the variable on the left-hand side.
All variables used in the expression must be assigned values before evaluation is
attempted.
Examples of evaluation statements are
x = a * b - c;
If a=2, b=4 , c= 3
a*b=8 , (a * b) - c = 8-3 =5
Hence x=5

Types of Expression
Depending upon the position of operand, expression are classified as
1. Infix Expression
2. Prefix Expression
3. Postfix Expression

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

45

Infix
When the operator lies between the operands then the expression is known as an Infix
expression. Below is the representation:
c=a+b
Here + operator is present inbetween the two operands a and b

Prefix
When the operator lies before the operands then the expression is known as a Prefix
expression. Below is the representation:
c = +ab
Here + operator is present before the two operands a and b

Postfix
When the operator lies after the operands then the expression is known as a Postfix
expression. Below is the representation:
c = ab+
Here + operator is present after the two operands a and b

Depending on the operation, expression are classified as


1. Arithmetic Expression
2. Relational Expression
3. Logical Expression
4. Bitwise Expression

Depending on the operand, expression are classified as


1. Unary Expression
2. Binary Expression
3. Ternary Expression

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])


lOMoARcPSD|30801605

Programming for Problem Solving - Unit-1

46

Topic : 13 L-value & R-value in Expression

l-value is for left value and r-value is for right value.


These two terms are used to refer to the expressions in an assignment operator.
An l-value represents a storage region's "locator" value, or a "left" value, implying
that it can appear on the left of the equal sign ( = ).
L-values are often identifiers.
For example: x = 7 Here l-value is expression x which will get the r-value .i.e. 7 after
assignment.
Usually L-value is a variably (named memory location)
Whereas R-value is a direct value or another identifier.
int i = 10; // valid

int i;
10 = i; //invalid
This is because i has an address in memory and is a lvalue.
While 10 doesn't have an identifiable memory location and hence is an rvalue.
So assigning the value of i to 10 doesn't make any sense.

S.PRABU, Assistant Professor, CTECH –SRM-KTR

Downloaded by Ajmal D ([email protected])

You might also like