0% found this document useful (0 votes)
11 views24 pages

Unti 1

The document provides an introduction to algorithms, programming languages, and the C programming language. It defines algorithms, their characteristics, and features, along with flowcharts and pseudocode. Additionally, it discusses the history of C, its structure, uses, and the software development life cycle (SDLC).

Uploaded by

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

Unti 1

The document provides an introduction to algorithms, programming languages, and the C programming language. It defines algorithms, their characteristics, and features, along with flowcharts and pseudocode. Additionally, it discusses the history of C, its structure, uses, and the software development life cycle (SDLC).

Uploaded by

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

UNIT-1

Chapter1: Introduction to algorithms and programming languages

Q) What is an Algorithm?
A set of rules that must be followed in solving a particular problem is called an algorithm.
Or
A sequential solution of any program that written in human language is called an algorithm.

The purpose of algorithms to achieve software re-uses.

Q) What are the characteristics of algorithm?


 Be precise.
 Be unambiguous.
 Not even a single instruction must be repeated infinitely.
 After the algorithm gets terminated, the desired result must be obtained.

Q) What are the key features of algorithm?


An algorithm has a finite number of steps and some steps may involve decision making and
repetition. Broadly an algorithm exhibits three key features. Those are

1. Sequence:
Sequence means that each step of the algorithm is executed in the specified order.
The steps are executed purely sequential order.

Example: Algorithm for adding two numbers

Algorithm: Step 1: Input the first number as A.


Step 2: Input the second number as B.
Step 3: Set sum=A+B;
Step 4: print sum.
Step 5: End.
2. Decision:
Decision statements are used when the outcome of the process depends on the same condition.
The condition may be true or false. This type of form is also known as if-else statement.
The general form is If condition then process.

Example: Algorithm to check equality of two numbers


Algorithm: Step 1: Input the first number as A.
Step 2: Input the second number as B.
Step 3: if A=B
then print “Equal”.
else
print “not Equal”.
Step 4: End.

3. Repetition:
-It involves executing one or more steps for a number of times.
-These can be implemented by while, do-while, for loops.
-These loops execute one or more steps until some condition is true.

1
Example: Algorithm to print first 10 natural numbers.
Algorithm: Step 1: set I=0,N=10.
Step 2: Repeat step3 while I<=n;
Step 3: print I.
Step 4: end.
Examples:
Write an algorithm for exchange two numbers.
Step 1: input the first number as A.
Step 2: Input the second number as B.
Step 3: Set temp=A;
Step 4: set A=B;
Step 5: set B=temp;
Step 6: print A, B.
Step 7: End.
Write an algorithm to find the larger of two numbers.
Step 1: Input first number as A.
Step 2: Input second number as B.
Step 3: if A>B
then print A.
else if A< B
then print B.
else
Print “two are equal”.
Write an algorithm to find number is even or odd.
Step 1: Input the first number as A.
Step 2: if A%2 =0
Then print “Even”.
else
print “odd”.
End.

Q. What is a Flowchart?
1. Diagrammatic (or) pictorial (or) graphical Representation of program logic involve in a problem
is called flowchart.
2. It is used to visualize the logic of the program.
3. When designing the flow chart, each step in the process is depicted by different symbols and is
associated with a short description.
4. A flow chart fallows the top-down approach in solving the problems.

Symbol Purpose Description

Flow line Used to indicate the flow of logic by connecting symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/output Used for input and output operation.

2
Symbol Purpose Description

Processing Used for arithmetic operations and data-manipulations.

Used to represent the operation in which there are two


Decision
alternatives, true and false.

On-page Connector Used to join different flow line

Off-page Connector Used to connect flowchart portion on different page.

Predefined Used to represent a group of statements performing one


Process/Function processing task.

Examples: Draw a flow chart to calculate the sum of two natural numbers:

Draw a flow chart for finding big of two numbers

3
Draw a flow chart for finding sum of n numbers

Q) What are the advantages and disadvantages of flow chat?

Advantages:

• Communication: Flowcharts are better way of communicating the logic of a system to all
concerned or involved.
• Effective analysis: With the help of flowchart, problem can be analyzed in more effective way
therefore reducing cost and wastage of time.
• Proper documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes, making things more efficient.
• Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
• Proper Debugging: The flowchart helps in debugging process.
• Efficient Program Maintenance: The maintenance of operating program becomes easy with the
help of flowchart. It helps the programmer to put efforts more efficiently on that part

Disadvantages:
• Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
• Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely. This will usually waste valuable time.
• Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem.

Q) What is pseudocode?
1. It is a form of structured English that describes algorithms.
2. An ideal pseudocode must be complete, describing the entire logic of the algorithm.
3. It is basically meant for human reading.
4. Pseudocode is an outline of a program that can easily be converted into programming languages.
5. The main purpose is to enhance human understandability of the solution.
6. The keywords associated with the pseudocode are “ while—endwhile,if—endif,case—endcase”.

4
Q) What is programming language?
A programming language is a language specifically designed to express computations that can be
performed using the computer.
Programming languages usually referred as “high-level languages. These are easy for humans to
understand.

Q) Generations of programming languages?


The generations of programming languages means advances in technologies that brought about the
different generations of the computer.

1. First generation languages (Machine languages)


 The first generation of programming language, or 1GL, is machine language.
 Machine language is a set of instructions are written in binary code that is just ones and zeros
 Machine language is the only programming language that the computer can understand
directly without translation.
 The main advantage is code can be run very fast and efficiently.

2. SECOND GENERATION LANGUAGE


 The second generation programming language, or 2GL, is assembly language.
 Assembly language is the human-readable notation for the machine language used to control
specific computer operations.
 An assembly language programmer writes instructions using symbolic instruction codes that
are meaningful abbreviations or mnemonics.
 An assembler is a program that translates assembly language into machine language.

3. THIRD GENERATION PROGRAMMING LANGUAGE


 The third generation of programming language, 3GL, or procedural language uses a series of
English-like words, that are closer to human language, to write instructions.
 High-level programming languages make complex programming simpler and easier to read,
write and maintain.
 Programs written in a high-level programming language must be translated into machine
language by a compiler or interpreter.
 PASCAL, FORTRAN, BASIC, COBOL, C and C++ are examples of third generation
programming languages.

4. FOURTH GENERATION PROGRAMMING LANGUAGE

 The fourth generation programming language or non-procedural language, often abbreviated


as 4GL, enables users to access data in a database.
 A very high-level programming language is often referred to as goal-oriented programming
language because it is usually limited to a very specific application and it might use syntax that
is never used in other programming languages.
 SQL, NOMAD and FOCUS are examples of fourth generation programming languages.

5. FIFTH GENERATION PROGRAMMING LANGUAGE

 The fifth generation programming language or visual programming language, is also known as
natural language.
 Provides a visual or graphical interface, called a visual programming environment, for creating
source codes.
5
 Fifth generation programming allows people to interact with computers without needing any
specialized knowledge.
 People can talk to computers and the voice recognition systems can convert spoken sounds
into written words.
 Prolog and Mercury are the best known fifth-generation languages.

Q) Structured programming languages?


In structured programming, the program is divided into small parts (functions) and each part
performs a specific job. The main importance is on functions rather than data. The same data can
be used and manipulated by several functions and such type of data is made global.

Structured Programming Constructs:

1. Sequence Control Structure (Sequence Logic or Sequential Flow).


2. Selection Control Structure (Selection Logic or Conditional Flow).
3. Repetition Control Structure (Iteration Logic or Repetitive Flow).
Structured programming frequently employs a top-down design model, in which developers map
out the overall program structure into separate subsections

Advantages of Structured Programming


 Complexity can be reduced using the concepts of divide and conquer.
 Logical structures ensure clear flow of control.
 Increase in productivity by allowing multiple programmers to work on different parts of the
project independently at the same time.
 Modules can be re-used many times, thus it saves time, reduces complexity and increase
reliability.
 Easier to update/fix the program by replacing individual modules rather than larger amount of
code.
 Ability to either eliminate or at least reduce the necessity of employing GOTO statement.

Disadvantages of Structured Programming


 Lack of encapsulation
 Same code repetition
 Lack of information hiding.
 Not much reusability of code.

Q) Design and implementation of correct, efficient and maintainable programs(SDLC).


Design and implementation of correct, efficient and maintainable programs depends upon the
approach adopted by the programmer to perform various activities that need to be during the
development process.
The entire program development process is divided into a number of phases, where each phase
performs a well-defined task.
The phases in the software development life cycle (SDLC) are

1. Requirements analysis:
In this phase, the user’s expectations are gathered to know why the program has to be built. Then,
all the gathered requirements are analyzed and documented to arrive at the scope or the objective
of the program.

6
2. Design:
The requirements documented in the previous phase act as input to the design phase. In the
design phase, a plan of actions is made before the actual development. In this phase the program
is divided into modules. We prepare alogorithms and flow charts for all modules.

3. Implementation:
In this phase, the designed algorithms are converted into program code by using any of the high-
level languages.

4.Testing:
In this phase all the modules are tested together to ensure that the overall system works well as a
whole product.
In this phase the software or program is tested using a large number of varied inputs also known
as test data, to ensure that the software or program is meet the requirements.

5.Software development, training and support:


After the testing the program or software, it is installed in the production environment.

6.Maintenance:
Maintenance and enhancements are ongoing activities that are done to cope with new
requirements. Once when the customers starts using the developed system then the actual
problems comes up and needs to be solved from time to time. This process where the care is
taken for the developed product is known as maintenance.

UNIT – 1
CHAPTER 2: INTRODUCTION TO C

 C was developed in the early 1970 s by Dennis Ritchie at Bell laborites.


 It is developed for portable application software’s.
 It is being used in several different soft wares.
 C is structured, high-level, machine independent language.

Q) History of c or background:

7
ALGOL:
 The root of all modern languages is ALGOL.
 ALGOL means “Algorithmic Language”.
 It is the first computer language to use a block structure.
 It is used for structured programming language.

BCPL:
 In 1967, Martin Richards developed BCPL.
 BCPL means Basic Combined Programming language.
 It is used for System software.
B:
 In 1970, Ken Thompson created a language called B.
 It is used to create UNIX operating system.
 It is type less system programming language.
C:
 C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell laborites.
 It uses the concept of data types.
 It was used for academic environments.
 It is also known as “traditional c”.

K & R C:
The traditional c is popular by releasing the book “the C programming language” by Kernighan
and Ritchie in 1978.

ANSI C:
American national standards institute define standards for c in 1983. So it is known as ANSI C.
ISO C:
International standards organization approved c in 1990.It is referred as C89.
In 1999 a modified version c99 was released with character, Boolean and integer data types.

Q2) what are the characteristics of c?


 C is a robust language.
 C has rich set of built- in functions.
 C is highly portable.
8
 C is well suited for structures programming.
 C has the ability to extent itself.
 Programs written in c are efficient and fast.

Q3) what are the uses of c?


 It is primarily used for system programming.
 It is used as intermediate language for implementing other language.
 It is used for end-user application.

Q4) Explain basic structure of a C program?


A C program is composed of preprocessor commands, a global declaration section and one or more
functions.

1. Documentation section:
The documentation section consists of a set of comment lines giving the name of the program,
the author and other details, which the programmer would like to use later.
2. Link section:
 This provides instructions to the compiler to link system library function.
 The most common function is ‘include’ statement.

3. The definition section:


 Definition section defines all symbolic constants.
 These link and definition sections are called preprocessor directivities.

4. Global declaration section: These are some variables that are used in more than one function
Such variables are called global variables declared in this section.

5. Main ( ):
Every c program must have one main ( ) function section.
9
This section contains 2 parts
Declaration part: it is used for variable declaration
Executable part: it is contains opening logic for problem.
The main function contains opening brace for program execution starting and closing brace for
program execution ends.
All the statements in declaration and executable parts ends with a semicolon (;).
The subprogram section contains all user defined functions that are called in main () function.

/*Documentation Section: program to find the area of circle*/

#include "stdio.h" /*link section*/


#include "conio.h" /*link section*/
#define PI 3.14 /*definition section*/
float area; /*global declaration section*/
void main()
{
float r; /*declaration part*/
printf("Enter the radius of the circle\n"); /*executable part starts here*/
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
getch();
}

Q) What are the Files used in c?

1. Source code file: It contains the source code of the program with extension “.c”.
It contains main () function and may be other functions.
2. Header files: It contains all built in functions with .h extension. In C we have header files like
stdio.h, string.h, stdlib.h etc….
3. Object files: object files are generated by the compiler as a result of processing the source code
file. They contain binary code for the source code with extension .obj.
4. Executable files: Linker uses the object files to produce executable files. These files contain
extension .exe.

Q) Explain Compiling and Execution a ‘C’ program?

They are four general steps involved in the execution of a program written in ‘C’ language
irrespective of the operating system being used.

1. Create the source program:


Creation of the source program is done with the help of a text editor. A text editor us to create
a new text file, modify the contents of an existing file, et The source program is type into a file
say, filename.c.note that the ‘C’ program files end with extension.c.
2. Compiling the source program:

10
Once the source program is ready in a text file, next the file is submitted to the ‘C’ compiler.
The ‘C’ compilers process the source program and if the program is syntactically correct,
produce the object code.
3. Linking the program with functions in the standard ‘C’ library:
Once the object code of the program is obtained after successful compilation, the linker links
the object code with the functions in the standard library referred by the program.
4. Executing the program to get the expected output:
After the compilation of linking the functions the code should be executed.
Note: For compilation --> Alt+f9
 For runnig --->ctrl+f9
To see the output screen—> Alt+f5.

Q) Write about comments in c?


 A comment is a programmer-readable explanation provides clarity to the C source code
allowing others to better understand and are generally ignored by compilers and interpreters.
 Comments are especially important in large projects containing hundreds or thousands of lines
of source code or in projects in which many contributors are working on the source code.
 Comments are non-executable code used to provide documentation to the programmer.

Comments are two types.

Single line comments:


1. Single Line Comment Can be Placed Anywhere
2. Single Line Comment Starts with ‘//’
3. Any Symbols written after ‘//’ are ignored by Compiler

Multi line comments:


1. Multi line comment can be placed anywhere.
2. Multi line comment starts with /*.
3. Multi line comment ends with */.
4. Any symbols written between '/*' and '*/' are ignored by Compiler.
5. It can be split over multiple lines

Example:
#include<stdio.h> //this is link section
void main()
{
printf("Hello"); /* this is used to display the message hello */
printf("By");
}

Q) Write about key words in c?


 Keywords are the reserved words used in programming.
 Each keyword has fixed meaning and that cannot be changed by user
 Keywords serve as basic building blocks for program statements.
 All keywords must be written in lowercase.

11
Keywords in C Language
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

Q) Write about identifiers?


 In C programming, identifiers are names given to C entities, such as variables, functions,
structures etc.
 Identifiers are created to give unique name to C entities to identify it during the execution of
program. For example:

 Identifiers refer to the names of variables, functions and arrays. These are user-defined names
and consist of a sequence of letters and digits, with a letter as a first character.
 Both uppercase and lowercase letters are permitted. The underscore character is also
permitted.

Rules for writing identifier


1. An identifier can be composed of letters (both uppercase and lowercase letters), digits and
underscore '_' only.
2. The first letter of identifier should be either a letter
3. There is no rule for the length of an identifier. However, the first 31 characters of an identifier
are discriminated by the compiler. So, the first 31 letters of two identifiers in a program should be
different.
4. Key words cannot be used as identifier.
5. Identifiers are case sensitive.

Examples:
Valid identifiers: invalid identifiers:
Rol_number, money, name, DeptCode 23_money, &deptcode, auto

Q) Explain basic data types in c?


C data types are defined as the data storage format that a variable can store a data to perform a
specific operation.
“C” supports several different data types
C data types

Primary data types Secondary data types


12
Character data type:
 Character type variable can hold a single character and are declared by using the keyword
char.
 The size of a variable of char type is one byte.
 The range of values that can be stored in a variable of char type is -128 to -127(
Syntax: char variable name;
Example: char ch=’a’;

Unsigned char:
 The unsigned char is a variation of char type.
 The size of a variable of unsigned char type is also one byte.
 The range of values that can be stored ina a variable of byte unsigned char is 0 to 255(0 to

Integer data types:


 All numeric data items with no fractional part belong to integer type.
 The keyword int is used to represent integer type.
 In generally an integer occupies 2 bytes memory space.
 The range of values be stored in a variable of int is -32,768 to 32,767.
 Integer type provides three modifiers
unsigned int
short int
long int

syntax: int variablename;


Example: int a;
int salary;

unsigned int:
 The size of a variable of unsigned int is also 2 bytes.
 It can store only positive range of values. The range of values be stored in a variable of
unsigned int is 0 to65535(0 to
Syntax: unsigned int variablename;
Example:unsigned int ui;

 short int:
 The size of a variable of short int is also 2 bytes. It is similar to int.
Syntax: short int variablename;
Example:short int si;
13
 long int:
 The size of a variable of long int is also 4 bytes.
 The range of values be stored in a variable of unsigned int is -2147483648 to 2147483647.
Syntax: long int variablename;
Example:long int li;
Unsigned Short int:
 Unsigned short int is similar to unsigned int.
 The range of values that can be stored in a variable of unsigned long int is 0 to 65,535 or 0 to

Floating point data types:


Float:
 The float data type is used to store fractional numbers(real numbers) with 6-digit of precision.
It‘s size is 4 bytes.
 A variable of float type requires 4 bytes and the range of values that can be stored in it is
3.4E-38 to 3.4E+38
Syntax: float variablename;
Example: float num1;
 To extend the precision further we can use
 Double
 Long double
Double:
 A variable of double type requires 8 bytes of memory space and the range of values that can
be stored in 1.7E-308 to 1.7E+308
 It stores floating point numbers with 14 digits of precision.
Syntax: double variablename;
Example: double num1;
Long double:
 It requires 10 bytes of memory space and the range of values that can be stored in it is 3.4E-
4932 to 1.1 E+4932
 It stores floating point numbers with more than 14 digits of precision.
Syntax: long double variable name;
Example: long double num1;
Void:
It is used in two situations:
 To explicitly declare function which do not return any value.
 To create generic pointers.

Derived data types:


 By using a single primary data type a new data type is created, it is known as Derived data
types.
 ex: arrays, functions, pointers

Q) Write about Constants?


 A constant is an entity that doesn't change during the execution of a program.
 . They are

14
Constants

Numeric Constants Character Constants

Integer Real Single char String


Constant Constant Constants Constant
s s s

1. Integer Constant:
 It must have at least one digit.
 It should not contain a decimal place.
 It can be positive or negative.
 Use of blank space and comma is not allowed between real constants.
 Example:1990, 194, -394

2. Real Constant:
 It must have at least one digit.
 It must have a decimal point which may be positive or negative.
 Use of blank space and comma is not allowed between real constants.
 Example:+194.143, -416.41
3. Character Constant:
 It is a single alphabet or a digit or a special symbol enclosed in a single quote.
 Maximum length of a character constant is 1.
 Example:'T', '9', '$'

4. String Constant:
 It is collection of characters enclosed in double quotes.
 It may contain letters, digits, special characters and blank space.
 Example: “ravi”, “123”, ”it is c-language”

Q) Write about variables?


 A variable is a named memory location in computer's memory to store data.
 To indicate the memory location, each variable should be given a unique name called
identifier.
 Variable names are just the symbolic representation of a memory location.
 Variable value, changes during the execution of a program.
a

65536 6

a : variable
65536 : address of cell
6 : value in the cell

15
Declaring & initializing C variable:
 Variables should be declared in the C program before to use.
 Memory space is not allocated for a variable while declaration. It happens only on variable
definition.
 Variable initialization means assigning a value to the variable.
S.No Type Syntax Example
1 Variable declaration data_type variable_name; int x, y, z; char flat, ch;

2 Variable initialization data_type variable_name = value; int x = 50, y = 30; char flag = ‘x’, ch=’l’;

Rules for writing a variable name


 Every variable name should be started with an alphabet.
 The length of the variable should not exceed more than 8 characters. Some compilers may
support upto 40 characters.
 Spaces should not be provided in a variable name.
 Reserved words should not be used as a variable name.
 Except underscore, other symbols should not be used as a variable name.
 A variable can store the value of particular data type only.
Syntax: data_type variable;
1. Ex: int a;
To declare more than one variable of same type, the variables are separated by commas as
shown:
Syntax: datatype variable1,variable2,---------------------variable n;
Example: int a,b,c;

Q) What are input/output statements in c?

1. Input: In any programming language input means to feed some data into program. This can be
given in the form of file or from command line. C programming language provides a set of built-
in functions to read given input and feed it to the program as per requirement.
2. Output: In any programming language output means to display some data on screen, printer
or in any file. C programming language provides a set of built-in functions to output required
data.
3. In c we use printf() function for output and scanf() function for input data.
4. printf() and scanf() functions are inbuilt library functions in C programming language which are
available in C library by default. These are defined in “stdio.h”

Printf()
 Printf() means print formatting.
 In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen.
 Syntax: printf (“format string”, argument list);
o Format string may be a collection of escape sequence or/and conversion specification
or/and string constant. The format string directs the printf function to display the entire
text enclosed within the double quotes without any change.
 Escape sequence is a pair of character. The first letter is a slash followed by a character.
Escape Meaning
16
sequence
\n New line
t Tab
\b Back space
\a Bell
\o Null character
\? To print question mark
\\ To print slash
\' To print single quote
\" To print double quote
 Conversion specification is also a pair of character. it is preceded by % and followed by a
quote which may be a character. The Conversion specification inscribes the printf() function
that it could print some value at that location in the text.
Conversion Specification Output
%c Character
%s string of characters
%d or %i decimal integer
%e floating point number in e-notation
%f floating point number in decimal notation
%g uses %f or %e whichever is shorter
%p Pointer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer, using lower case
%X hexadecimal integer, using upper case
%% Prints a % sign
Example:
#include <stdio.h>
int main()
{
char ch = 'A';
char str[20] = "fresh2refresh.com";
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf("Character is %c \n", ch);
printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}

2. SCANF()
1. It usually used input statement is scanf () function.

17
2. Syntax of scanf function is
scanf (“format string”, argument list);
3. The format string must be a text enclosed in double quotes. It contains the information for
interpreting the entire data for connecting it into internal representation in memory.
Example: integer (%d) , float (%f) , character (%c) or string (%s).
4. The argument list contains a list of variables each proceeded by the address list and
separated by comma. The number of argument is not fixed;
Example: if i is an integer and j is a floating point number, to input these two numbers we may use
scanf (“%d%f”, &i, &j);

Example:
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}

Q) Explain different types of operators in c?


 An operator is defined as a symbol that specifies the mathematical, logical, or relational
operation to be performed.
 C language supports a lot of operators to be used in expressions.
 These operators can be categorized into the following major groups
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Conditional operators
6. Comma operators
7. Unary operators
8. Bitwise Operators

1.Arithmetic operators:
These are used to perform mathematical calculations like addition, subtraction, multiplication, division
and modulus.

Arithmetic Operators/Operation Example

+ (Addition) A+B

– (Subtraction) A-B

* (multiplication) A*B

18
/ (Division) A/B

% (Modulus) A%B
All arithmetic operators execute from left to right.
If all operators are in one expression higher precedence operators like multiplication, division and
modulus carries first and then lower precedence operators like addition and subtraction from left to
right manner.

Example: #include <stdio.h>


int main()
{
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);
printf("Modulus of a,b is:%d\n,mod); }

2. Relational operators:
 Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.
 Expression that contains relational operators is called relational expression.
 Relational expressions return only true or false values.
Operators Example/Description

> x > y (x is greater than y)

< x < y (x is less than y)

x >= y (x is greater than or


>= equal to y)

x <= y (x is less than or


<= equal to y)

== x == y (x is equal to y)

!= x != y (x is not equal to y)

Example:
#include <stdio.h>
void main()
{
int m=40,n=20;
clrscr();
19
printf(“m and n are equal%d\n”,(m==n));
printf(“m and n are not equal%d\n”,(m!=n));
printf(“m is greater than n d\n”,(m>n));
printf(“m is less than n %d\n”,(m<n)); getch(); }
3. LOGICAL OPERATORS:
 These operators are used to perform logical operations on the given expressions.
 These are used to test two or more conditions at a time.
 There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).
Operator
s Example/Description

&& (x>5)&&(y<5)
(logical It returns true when both conditions
AND) are true

(x>=10)||(y>=10)
|| (logical It returns true when at-least one of
OR) the condition is true

!((x>5)&&(y<5))
It reverses the state of the operand
“((x>5) && (y<5))”
! (logical If “((x>5) && (y<5))” is true, logical
NOT) NOT operator makes it false
Example: #include <stdio.h>
void main()
{
int m=40,n=20;
int o=20,p=30;
clrscr();
printf(“%d”, (m>n && m !=0))
printf(“%d”, (o>p || p!=20))
getch();
}
4. BIT WISE OPERATORS:
 These operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits.
 Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).
 Bitwise Negation b = 00010110
a=00000011 a|b=00010111
~a =11111100
 Bitwise And
a = 00000011  Bitwise Exclusive Or
b = 00010110 a = 00000011
a&b=00000010 b = 00010110
 Bitwise Or a^b=00010101
a = 00000011

20
 Right Shift
a = 0000 0011 = 3
(a<<=1) = 00000110 = 6
(a<<=2) = 00011000 = 24
(a<<=3) = 11000000 = 192
 Left Shift
a=11000000 =192
(a>>=1) = 01100000 = 96
(a>>=2) = 00011000 = 24
(a>>=3) = 0000 0011 = 3

21
5. Unary Operators
The operators that act upon a single operand to produce a new value are known as Unary operator.
The frequently used Unary operators in C are

1. Unary minus
The operand of Unary minus operator must have arithmetic type, and the result is the –ve of its
operand.
Example:
-(p+q)
x=-y
-10*(p+q)

2. Increment and Decrement operator: (++,--):

1. Increment operator:
It is indicated with ++. It is used to increase the value of the variable by one. It is
classified into two types. They are:
 Pre increment:
In pre-increment the value is incremented first and then the value will be assigned.
Syntax: ++operand;
 Post increment:
In post-increment the value is assigned first and then the value is incremented.
Syntax: operand++;

Examples:

i) A=5; B=A++;
Now A =6, B=5.
ii) A=5; B=++A;
Now A =6, B=6.

2. Decrement operator:
It is indicated with --. It is used to decrease the value of the variable by one. It is classified into
two types. They are:
 Pre decrement:
In pre-decrement the value is decremented first and then the value will be assigned.
Syntax: --operand;
 Post decrement:
In post-decrement the value is assigned first and then the value is decremented.
Syntax: operand--;

Examples:
i) A=5; B=A--;
Now A =4, B=5.

ii) A=5; B=--A;

Now A =4, B=4.

Example:
22
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
clrscr();
printf(“ the value of a is%d\n”,a);
printf(“ the value of pre increment is%d\n”, ++a);
printf(“ the value of post increment is%d\n”, a++);
printf(“ the value of pre decrement is%d\n”, --a);
printf(“ the value of post decrement is%d\n”, a--);
}

5. The assignment operator:- It is used to assign the value to a variable.

Operator Example Same as


= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b

Example: a=10; a=a+20;


Var a=5 //5 is assigned to var
a=c; //value of c is assigned to a
5=c; // Error! 5 is a constant.

6. Conditional operator or ternary operators (? :)


The conditional operator is also known as ternary operator. This first evaluates an
expression for a true or false value and then execute one of the two given statements depending
upon the result of the evaluation.
Syntax: (test-condition)? statement1:statement2;
In this first test-condition is evaluated, if it is true then the statement1 is executed otherwise
statement2 is executed.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=20,b=10,max;
clrscr();
max=(a>b)?a:b;
printf(“the a value is %d”,a);
printf(“the b value is %d”,b);
printf(“the max value is %d”,max);
}
7. Special Operators
i)Comma Operator
23
Comma operators are used to link related expressions together. For example:
int a,c=5,d;

ii)sizeof operator
It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.
Syntax: sizeof (operand);

example:
#include <stdio.h>
void main()
{
int a;
float b;
double c;
char d;
clrscr();
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
return 0;
}

24

You might also like