Programming For Problem Solving Using C Notes Unit - I
Programming For Problem Solving Using C Notes Unit - I
-I
INTRODUCTION TO PROGRAMMING
• First is the computer hardware that does all the physical work computers.
• Second is the computer software that commands the hardware what to do and how to
do it.
Computer Hardware
Example: Mother Board, Processor, RAM, Monitor, Keyboard, Mouse, Hard Disk,
DVD Drive, SMPS, etc.
Computer Software
• Computer software is the set of instructions and associated data that direct the
computer to do a task. Software is written by computer programmers using a
programming language.
• The programmer writes a set of instructions (program) using a specific programming
language. Such instructions are known as the source code.
• A program is a set of instructions that are arranged in a sequence to guide a computer
to find a solution for a given problem. The process of writing a program is called
programming.
1. System Software
2. Application Software
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Figure 1.2 Relationship between hardware, system software, and application software
System Software
System software represents programs that allow the hardware to run properly. System
software is software designed to operate the computer hardware and to provide and maintain
a platform for running application software. System software is transparent to the user and
acts as an interface between the hardware of the computer and the application software that
users need to run on the computer.
The computer BIOS and device drivers provide basic functionality to operate and
control the hardware connected to or built into the computer.
BIOS is stored on a ROM chip built into the system and has a user interface like that
of a menu (Below Figure) that can be accessed by pressing a certain key on the keyboard
when the computer starts.
• Tests RAM
Operating System
The primary goal of an operating system is to make the computer convenient and
efficient to use. An operating system offers generic services to support user applications.
Some popular Operating Systems include Linux Operating System, Windows Operating
System, VMS, OS/400, AIX, z/OS, etc.
Utility Software
Utility software is used to analyse, configure, optimize, and maintain the computer system.
Utility programs may be requested by application programs during their execution for
multiple purposes. It is used to support the computer infrastructure - in contrast to application
software, which is aimed at directly performing tasks that benefit ordinary users.
Some of them are as follows: Disk checkers, Disk cleaners, File managers, System
profiler, Anti-virus utilities, Data compression, Network utilities, Command line interface
(CLI) and Graphical user interface (GUI).
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Compiler, Interpreter, Linker, and Loader
Compiler reads source code written in a programming language (the source language
(high-level programming)) into machine language or assembly language (lower level
language) comprising just two digits, 1s and 0s (the target language). The resultant code in 1s
and 0s is known as the object code. It provides error not of one line, but errors of the entire
program. It executes as a whole and it is fast.
Interpreter reads only one line of a source program at a time and convert it into an
object code. In case of error or same will be indicated instantly and it executes line by line
and it is slow.
Linker (link editor binder) It is a program that combines object modules to form an
executable program. Generally, in case of a large program, the programmers prefer to break a
code into smaller modules as this simplifies the programming task.
Loader It is a special type of program that copies programs from a storage device to
main memory, where they can be executed.
Application Software
Application software (app for short) is a program or group of programs designed for
end users. Application software is a type of computer software that employs the capabilities
of a computer directly to perform a user-defined task.
Bits − A bit is a smallest possible unit of data that a computer can recognize or use. Computer
usually uses bits in groups.
Bytes − group of eight bits is called a byte. Half a byte is called a nibble.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
• 1 Byte : 8 Bits
High-level programming languages are easy for humans to read and understand, the
computer understands the machine language that consists of numbers only. Each type of CPU
has its own unique machine language.
High level languages is that they allow the programmer to write programs for all types
of computers and systems. Every instruction in high level language is converted to machine
language for the computer to comprehend.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Types of High-Level Language
Object-Oriented Languages These are high level languages that focus on the ‘objects’ rather
than the ‘actions’. To accomplish this, the focus will be on data than logic. Some examples
include Java, C+, C++, Python, Swift etc.
Procedural Programming Language This is a type of programming language that has well
structured steps and complex procedures within its programming to compose a complete
program. It has a systematic order functions and commands to complete a task or a program.
FORTRAN, ALGOL, BASIC, COBOL are some examples.
Low-level languages are the basic computer instructions or better known as machine
codes. A computer cannot understand any instruction given to it by the user in English or any
other high-level language. These low-level languages are very easily understandable by the
machine.
The main function of low-level languages is to interact with the hardware of the
computer. They help in operating, syncing and managing all the hardware and system
components of the computer. They handle all the instructions which form the architecture of
the hardware systems.
Machine Language: This is one of the most basic low-level languages. The language was
first developed to interact with the first generation computers. It is written in binary code or
machine code, which means it basically comprises of only two digits – 1 and 0.
• They are translation free and can be directly executed by the computers.
• The programs written in these languages are executed very speedily and efficiently by
the CPU of the computer system.
• The programs written in these languages utilize the memory in an efficient manner
because it is possible to keep track of each bit of data.
The following instructions are a part of assembly language code to illustrate addition
of two numbers:
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
ADD AX,BX Adds the contents of AX and BX registers. Stores the result in AX
register
• It is easy to develop understand and modify the program developed in these languages
are compared to those developed in the first generation programming language.
• The programs written in these languages are less prone to errors and therefore can be
maintained with a great case.
• As the program written in these languages are less prone to errors they are easy to
maintain.
• The program written in these languages can be developed in very less time as
compared to the first and second generation language.
languages were designed and developed to reduce the time, cost and effort needed to develop
different types of software applications.
• These programming languages allow the efficient use of data by implementing the
various database.
• They require less time, cost and effort to develop different types of software
applications.
• The program developed in these languages are highly portable as compared to the
programs developed in the languages of other generation.
• These languages can be used to query the database in a fast and efficient manner.
• In this generation of language, the user can communicate with the computer system in
a simple and an easy manner.
Algorithms
• Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one meaning.
Advantages of Algorithms:
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
5. By using algorithm, the problem is broken down into smaller pieces or steps hence, it
is easier for programmer to convert it into an actual program.
Disadvantages of Algorithms:
Step 1: Start
Step 2: Accept the first integer as input from the user (num1)
Step 3: Accept the second integer as input from the user (num2)
Step 6: End
Step 1: Start
4: if A = B
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
print “ Equal”
Equal”
Step 5: End
Flowcharts
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Symbol Symbol Name Purpose
• Flowchart can have only one start and one stop symbol
Example Flowcharts
Pseudo code
Pseudo code is a term which is often used in programming and algorithm based
fields. It is a methodology that allows the programmer to represent the implementation of an
algorithm. 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.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Advantages of Pseudocode
• Improves the readability of any approach. It’s one of the best approaches to start
implementation of an algorithm.
• Acts as a bridge between the program and the algorithm or flowchart. Also works as a
rough documentation, so the program of one developer can be understood easily when a
pseudo code is written out. In industries, the approach of documentation is essential.
And that is where a pseudo-code proves vital.
• 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.
Examples:
Print "passed"
else
Print "failed"
Types of Errors
Errors are the problems or the faults that occur in the program, which makes the
behavior of the program abnormal, and experienced developers can also make these faults.
Programming errors are also known as the bugs or faults, and the process of removing these
bugs is known as debugging.
• Syntax error
• Run-time error
• Linker error
• Logical error
• Semantic error
Syntax error
Syntax errors are also known as the compilation errors as they occurred at the
compilation time, or we can say that the syntax errors are thrown by the compilers. These
errors are mainly occurred due to the mistakes while typing or do not follow the syntax of the
specified programming language.
For example:
Run-time error
Sometimes the errors exist during the execution-time even after the successful
compilation known as run-time errors. When the program is running, and it is not able to
perform the operation is the main cause of the run-time error. The division by zero is the
common example of the run-time error. These errors are very difficult to find, as the compiler
does not point to these errors.
Error:
div = n/0;
Linker Errors
These error occurs when after compilation we link the different object files with
main’s object using Ctrl+F9 key(RUN). These are errors generated when the executable of
the program cannot be generated. This may be due to wrong function prototyping, incorrect
header files. One of the most common linker error is writing Main() instead of main().
Error:
Logical Errors
On compilation and execution of a program, desired output is not obtained when certain
input values are given. These types of errors which provide incorrect output but appears to be
error free are called logical errors. These errors solely depend on the logical thinking of the
programmer and are easy to detect if we follow the line of execution and determine why the
program takes that path of execution.
Error:
No Output
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Semantic Errors
This error occurs when the statements written in the program are not meaningful to the
compiler.
Testing
Testing is the process of verifying and validating that a software or application is bug free,
meets the technical requirements as guided by its design and development and meets the user
requirements effectively and efficiently with handling all the exceptional and boundary cases.
Debugging
Debugging is the process of fixing a bug in the software. It can defined as the identifying,
analyzing and removing errors. This activity begins after the software fails to execute
properly and concludes by solving the problem and successfully testing the software. It is an
extremely complex and tedious task because errors need to be resolved at all stages of
debugging.
TESTING DEBUGGING
Testing is the process to find bugs and Debugging is the process to correct the bugs
errors. found during testing.
It is the process to identify the failure of It is the process to give the absolution to code
implemented code. failure.
Testing can be done by insider as well as Debugging is done only by insider. Outsider
outsider. can’t do debugging.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
It is based on different testing levels i.e. Debugging is based on different types of bugs.
unit testing, integration testing, system
testing etc.
Testing is initiated after the code is Debugging commences with the execution of a
written. test case.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
INTRODUCTION TO C
Introduction
History of C Language
1. “C” became popular because of its reliability, simple and easy to use
2. It was friendly capable and reliable
3. ALGOL 60 was developed and did not become popular because it was too general and
too abstract.
4. They developed “CPU” (Combined Programming Language)
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
5. Next as it could not come up to make ALGOL 60 better one they moved to “BCPL”
(Basic Combines Programming Language. Developed by martin Richard Cambridge
university)
6. At the same time a language called “B” written by ken Thompson at AT & T‟S. Bell
laboaratories as a further simplification of BCPL.
7. “C” s compactness and coherence is mainly due to it‟s one man language. Ex- LISP,
AASCA.
Language Year Developed By
Structure of a C Program
A C program is a set of functions, data type definitions and variable declarations contained in
a set of files. A C program always start its execution by the function with name main. Any
function can invoke any other function and the variables declared outside the function are
either global or local to the current file (if they are declared with the static prefix).
The following figure shows the structure of a C program contained in several files.
Documentation Section: The documentation section is the part of the program where the
programmer gives the details associated with the program. documentation section Consists of
comments, some description of the program, programmer name and any other useful points
that can be referenced later.
Example
Link Section: This part of the code is used to declare all the header files that will be used in
the program. This leads to the compiler being told to link the header files to the system
libraries.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Example
#include<stdio.h>
Definition Section: In this section, we define different constants. The keyword define is used
in this part.
Example
#define PI=3.14
Global Declaration Section: This part of the code is the part where the global variables are
declared. All the global variable used are declared in this part. The user-defined functions are
also declared in this part of the code.
Example
a=7;
Main Function Section: Every C-programs needs to have the main function. Each main
function contains 2 parts. A declaration part and an Execution part. The declaration part is the
part where all the variables are declared. The execution part begins with the curly brackets
and ends with the curly close bracket.
Example
int main(void)
{ int a=10;
printf(" %d",
a); return 0;
}
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Sub Program Section: All the user-defined functions are defined in this section of the
program. Example
{ return
a+b;
#include <stdio.h>
#include <conio.h>
void main()
➢ #include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.
➢ #include <stdio.h> includes the standard input output library functions. The printf()
function is defined in stdio.h .
➢ void main() The main() function is the entry point of every program in c language.
The void keyword specifies that it returns no value.
➢ getch() The getch() function asks for a single character. Until you press any key, it
Hello World!
Header files offer these features by importing them into your program with the help of
a preprocessor directive called #include. These preprocessor directives are responsible for
instructing the C compiler that these files need to be processed before compilation.
Every C program should necessarily contain the header file <stdio.h> which stands
for standard input and output used to take input with the help of scanf() function and display
the output using printf() function.
1. Standard library header files: These are the pre-existing header files already available in
the C compiler.
2. User-defined header files: Header files starting #define can be designed by the user.
#include<filename.h>
Here is the table that displays some of the header files in C language
Sr.No. Header Files & Description
1 stdio.h
Input/Output functions
2 conio.h
3 stdlib.h
4 math.h
Mathematics functions
C program file is compiled and executed the compiler generates some files with the same
name as that of the C program file but with different extensions.
Below image shows the compilation process with the files created at each step of the
compilation process:
Every file that contains a C program must be saved with ‘.c’ extension. This is
necessary for the compiler to understand that this is a C program file. Suppose a program file
is named, first.c. The file first.c is called the source file which keeps the code of the program.
Now, when we compile the file, the C compiler looks for errors. If the C compiler reports no
error, then it stores the file as a .obj file of the same name, called the object file. So, here it
will create the first.obj. This .obj file is not executable. The process is continued by the Linker
which finally gives a .exe file which is executable.
Important Points
• Input to the compiler is .c file and output from the compiler is .exe file, but it also
generates .obj file in this process.
• The compiler converts the file only if there are no errors in the source code.
TOKENS IN C
A token is the smallest element of a program that is meaningful to the compiler (or) In a “C”
program the smallest individual units are known as “C” tokens. Tokens can be classified as
follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
5. Special Symbols
6. Operators
1. Keywords: Keywords are reserved words by compiler. Keywords are assigned with fixed
meaning and they cannot be used as variable name. No header file is needed to include the
keywords.
2. Identifiers:
• Identifier refers to the name of variables, functions and arrays. These are user defined
names and consists of a sequence of letters and digits.
• Both uppercase and lowercase letters can be used, and C language is case sensitive. A
special symbol underscore ( _ ) is also permitted.
• Rules for identifiers o First character must be an alphabet or underscore. o Must
consist of only letters, digits or underscore. o Should not be a keyword and should
not have any blank space.
o C is a case – sensitive language i.e, AREA and area both are different identifiers.
Char name;
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
3. Constants: constants in “C” are applicable to the values which not change during the
execution of a program.
Integer Constants: Sequence of number 0-9 without decimal points, fractional part or any
other symbols. It requires two or four bytes, can be +ve, -ve or Zero the number without a
sign is as positive.
Character Constants: Single character constant: A single character constants are given
within a pair of single quote mark.
String Constant: These are the sequence of character within double quote marks
char a[10] = "pragati"; // The compiler allocates the 10 bytes to the 'a' array.
char a[] = "pragati"; // The compiler allocates the memory at the run time. char
5. Special Symbols: The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose.[] () {}, ; * = #
• Brackets []: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
• Parentheses (): These special symbols are used to indicate function calls and
function parameters.
• Braces {}: These opening and ending curly braces marks the start and end of a
block of code containing more than one executable statement.
• comma (,): It is used to separate more than one statements like for separating
parameters in function calls.
• Semi colon : It is an operator that essentially invokes something called an
initialization list.
• asterisk (*): It is used to create pointer variable.
• assignment operator: It is used to assign values.
• pre processor(#): The preprocessor is a macro processor that is used automatically
by the compiler to transform your program before actual compilation.
6. Operators: Operators are symbols that triggers an action when applied to C variables
and other objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
• Unary Operators: Those operators that require only single operand to act upon are
known as unary operators.
• Binary Operators: Those operators that require two operands to act upon are called
binary operators.
1. Arithmetic operators
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
• Ternary Operators: These operators requires three operands to act upon. For Example
Conditional operator(?:).
Syntax datatypename
1. Character (char)
2. Integer (int)
4. double-precession (double)
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
5. void
1. Character: The most basic data type in C. It stores a single character and requires a
single byte of memory in almost all compilers.
• C has three classes of integer storage short int int long int
• It has a set of qualifiers i.e., sign qualifier
unsigned qualifier
• short int uses half the range of storage amount of data
• signed integer uses one bit for sign and 15 bits for magnitude
• unsigned int use all the bits for the magnitude of the number and are positive.
3. Floating: It is used to store decimal numbers (numbers with floating point value) with
single precision.
4. Double: It is used to store decimal numbers (numbers with floating point value) with
double precision.
5.Void: A void type has no value this is usually used to specify the return type of function ,
this function does not return any value to calling function
Variables
This is a data name used for storing a data, its value may be changed during the execution.
The variables value keep‟s changing during the execution of the program
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Declaration of Variable: It tells the complier what the variable name is used, what type of
date is held by the variable.
Syn:
datetype v1,v2,….vn;
Eg :
Representation of Constant
Eg:
Eg :
float x,p;
x=10.1;
p=5.2; printf
Output:
x= 10.10000 p =
5.2
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Comments
2. Multi-Line Comments
#include<stdio.h>
int main()
//printing information
printf("Hello C");
return 0;
• Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many
lines of code.
• Example:
#include<stdio.h>
int main()
{
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
/*printing information
C");
return 0;
C has many input output functions in order to read data from input devices and display the
results on the screen.
1. Formatted Functions
• Input (scanf())
• Output (printf())
2. Unformatted Functions
• Input (getch(), getche(), gethar(), gets())
• Output (putch(), puts())
Formatted Functions
These functions read and write all types of data values. They require a conversion symbol to
indents the data type using these functions the O/P can be presented in an aligned manner.
Short unsigned %u
long signed % ld
Long unsigned % lu
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Unsigned hexadecimal %x
Unsigned octal %0
Real float % f or % g
double % lf
signed character %c
unsigned char %c
string %s
Escape Sequences with their ASC|| values
\n New line 10
\b Backspace 8
\f Form feed 12
\’ Single Quote 39
\\ Back slash 92
\o Null 0
\t Horizontal tab 9
\r Carriage return 13
\a Alert 7
|? Question marks 63
\“ Double Quote 34
scanf ( ) function is used to read values using key board. It is used for runtime assignment of
variables.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
list_of_addresses_of_Variables );
The format string contains - Conversion specifications that begin with % sign Eg:
&‟ is called the “address” operator. In scanf( ) the „&‟ operator indicates the memory
location of the variable. So that the Value read would be placed at that location. printf()
function is used to Print / display values of variables using monitor. The general form of
printf( ) is Syntax:
Eg:
main ( )
printf(“ Average = %d \n
Output:
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Average = 346
Percentage = 69.200000
printf( ) examines the format string from left to right and prints all the characters until it
encounter a „%‟ or „\‟ on the screen. When it finds % (Conversion Specifier) it picks up the
first value. when it finds „\‟ (escape sequence) it takes appropriate action (\n-new line). This
process continues till the end of format string is reached.
Example: Program ( )
main ( )
Float avg,per;
O/P:
Average = 346
function is used to read one character at a time from the key board Syntax
Eg:
main ( )
{
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
char ch;
printf(“Enter a char”);
ch = getchar ( );
printf(“ch =%c”, ch);
}
O/P
Enter a char M
ch = M
When this function is executed, the computer will wait for a key to be pressed and assigns
the value to the variable when the “enter” key pressed.
Syntax:
putchar (ch);
Eg:
char ch = „M‟
putchar (ch);
The Computer display the value char of variable „ch‟ i.e M on the Screen.
getch ( ): function is used to read a char from a key board and does not expect the “enter” key
press.
Syntax:
ch = getch ( );
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
When this function is executed ,computer waits for a key to be pressed from the dey
board.
getche ( ): function is used to read a char from the key board without expecting the enter key
to be pressed. The char read will be displayed on the monitor.
Syntax:
ch = getche ( );
Note that getche ( ) is similar to getch ( ) except that getche ( ) displays the key pressed from
the dey board on the monitor. In getch ( ) „e‟ stands for echo. String I/O functions
gets ( ) function is used to read a string of characters including white spaces. Note that wite
spaces in a strng cannot be read using scanf( ) with %s format specifier.
variable
Ex:
char S[ 20 ];
gets (S);
When this function is executed the computer waits for the string to be entered.
Header files offer these features by importing them into your program with the help of
a preprocessor directive called #include. These preprocessor directives are responsible for
instructing the C compiler that these files need to be processed before compilation.
Every C program should necessarily contain the header file <stdio.h> which stands
for standard input and output used to take input with the help of scanf() function and display
the output using printf() function.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
3. Standard library header files: These are the pre-existing header files already available in
the C compiler.
4. User-defined header files: Header files starting #define can be designed by the user.
#include<filename.h>
Here is the table that displays some of the header files in C language
Sr.No. Header Files & Description
1 stdio.h
Input/Output functions
2 conio.h
3 stdlib.h
4 math.h
Mathematics functions
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Operators In C
Operator: An operator is a symbol that tells the Computer to perform certain mathematical
or logical manipulations.
1. Arithmetic
2. Relational
3. Logical
4. Assignment
6. Conditional
7. Bitwise
8. Special
Arithmetic Operators: C provides all the basic arithmetic operators, they are +, -, *, /, %
Integer division truncates any fractional part. The modulo division produces the remainder of
an integer division.
* multiplication
/ division
Integer Arithmetic: When the operands in an expression are integers then the expression is
an integer expression and the operation is called integer arithmetic. This always yields an
integer value.
a/b=3 - 14 % 3 = -2
a%b=2 -14 % - 3 = 2
14 % -3 = 2
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
main ( )
sum = a+b ;
sub); prod = a * b ;
div = a/b;
mod = a % b ;
Real Arithmetic / Floating Pont Arithmetic: Floating Point Arithmetic involves only real
operands of decimal or exponential notation. If x, y & z are floats, then
x = 6.0/7.0 = 0.857143
y = -1.0/3.0 = 0.333333 z
= 3.0/2.0 = 1.500000
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Mixed mode Arithmetic: When one of the operands is real and the other is integer the
expression is a mixed mode arithmetic expression.
Eg:
15/10.0 = 1.500000
15/10 = 1
10/15 = 0
-10.0/15 = -0.666667
Relational Operator: These are the operators used to Compare arithmetic, logical and
character expressions. The value of a relational express is either one or zero .it is 1 if one is
the specified relation is true and zero if it is false.
Operator Meaning
< is less than
== is equal to
!= is not equal to
Example:
#include <stdio.h>
int main()
{
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
int a = 5, b = 5; printf("%d
return 0;
Output
5 == 5 is 1
5 > 5 is 0
5 < 5 is 0
5 != 5 is 0
5 >= 5 is 1
5 <= 5 is 1
Logical operator: Logical Operators are used when we want to test more than one condition
and make decisions. here the operands can be constants, variables and expressions Logical
operators are &&, ||, !
Example:
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Assignment Operator: Used to assign the result of an expression to a variable. “=” is the
assignment operator. In addition C has a set of „short hand‟ assignment operators of the form
Example:
main() { int a = 5, c;
c = a; // c is 5
c += a; // c is 10
c -= a; // c is 5
c *= a; // c is 25
c /= a; // c is 5
c %= a; // c = 0
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
return 0; }
Output
c=5
c = 10
c = 5 c = 25
c=5 c=0
a+=1 a = a+1
a-=1 a=a-1
a * = n+1 a = a* (n +
1) a / = n+1 a = a/(n+1)
a%=b a=a%b
Increment and Decrement Operators: C programming has two operators increment ++ and
decrement -- to change the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These
two operators are unary operators, meaning they only operate on a single operand.
++ and - -
Example:
return 0; }
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
Conditional operator: is used to check a condition and Select a Value depending on the
Value of the condition.
If the Value of the condition is true then Value 1 is e valued assigned to the varable,
otherwise Value2.
if (a>b)
big = a;
else big = b;
Bitwise operator: are used to perform operations at binary level i. e. bitwise. these operators
are used for testing the bits, or Shifting them right or left . These operators are not applicable
to float or double. Following are the Bitwise operators with their meanings.
Operators Meaning of operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
a = 13 Binary 00001101
b=6 00000110
Consider a << 2 which Shifts two bits to left , that is 2 zeros are inserted at the right and two
bits at the left are moved out.
00001101
Moved
00110100
sizeof operator: is used to find the on. of bytes occupied by a variable / data type in
computer memory.
#include <stdio.h>
int main() {
return 0; }
Output
comma operator: can be used to link the related expressions together. A comma- linked: list
of expressions are evaluated left to right and the value of right-most exp is the value of
combined expression.
Precedence: precedence is nothing but priority that indicates which operator has to be
evaluated first when there are more than one operator.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Example:
int x = 5 - 17* 6;
Associativity: when there are more than one operator with same precedence [ priority ] then
we consider associativity , which indicated the order in which the expression has to be
evaluated. It may be either from Left to Right or Right to Left.
Example:
5 * 4 + 10 / 2
= 20 + 5
=25
+ Unary plus
- Unary minus
++ Increment
-- Decrement
* Pointer reference
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
/ Divide
% Remainder
- Binary minus(subtraction)
!= Not equal to
*= Assign product
/= Assign quotient
%= Assign remainder
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
+= Assign sum
-= Assign difference
|= Assign bitwise OR
Normally before an operation takes pace both the operands must have the same type. C
converts One or both the operands to the appropriate date types by “Type conversion”. This
can be achieved in 3 ways.
Implicit Type conversion: In this the data type /Variable of lower type (which holds lower
range of values or has lower precision ) is converted to a higher type (which holds higher
range of values or has high precision). This type of conversion is also called “promotion”.
Example:
int I; char
C; C=
„A‟;
I = C;
Now the int Variable I holds the ASCII code of the char „A‟
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
c) Operation b/w a real & an integer always yields a real result Example:
5/2 = 2 2/5 = 0
Example:
int k; yes float a; yes k= 5/2 2 k=2/5 0 a = 5/2 2.0 k=5.0/2 2 k=2.0/5 0
2/5 0.0
a = 2.0/5 0.4
a = 2.0/0.5 0.4
Explicit Type Conversion: When we want to convent a type forcibly in a way that is
different from automatic type conversion, we need to go for explicit type conversion.
Syntax
Type name is one of the standard data type. Expression may be a constant variable or an
expression this process of conversion is called as casting a value.
MALLA REDDY INSTITUE OF TECHNOLOGY AND SCIENCE
Arya vardhan(564) CSE
Example:
x = (int) 7.5
Y =( int) (a + b)
P = (double)sum/n