[go: up one dir, main page]

0% found this document useful (0 votes)
26 views27 pages

Module 1 & 2

c language

Uploaded by

Samuel Johnpeter
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)
26 views27 pages

Module 1 & 2

c language

Uploaded by

Samuel Johnpeter
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/ 27

NARN/ MCA / MODULE – I & II / C PROGRAMMING

MODULE – I
Introduction to Programming, Algorithms and Flowcharts: Programs and
Programming, Programming languages, Compiler, Interpreter, Structured
Programming Concept, Algorithms, Flowcharts, How to Develop a Program.
Fundamental Algorithms: Exchanging the values of Two Variables, Counting,
Summation of a set of numbers, Factorial computation, Generation of the Fibonacci
Sequence, Reversing the digits of an integer.
Introduction : C language is one of structured programming languages. It was developed by Dennis
Ritchie at AT&T Bell laboratories, U.S.A in 1972. It is derived from the language BCPL (Basic Combine
Programming Language).
‘C’ language is called middle level language because ‘C’ supports both low-level language and
high-level language features. Through low-level features, C language is used for memory management,
bit manipulations and direct memory access using pointers. The high-level language features are
conditional statements, functions and files that are used for general purpose.

Features of C language:
1. General Programming Language: It is a general purpose programming language. Hence, it is used
for writing system and application programs.
2. Maintainability: It is reliable, simple and easy to use.
3. System Programming: C language is used to develop compilers, operating systems and other utility
programs for system software.
4. Portability: C language is highly portable language i.e. a C program written on one computer can be
compiled and executed on a different computer.
5. Structured Programming Language: It supports many control structures such as “if, switch, while,
do…while, for” etc. to develop well defined and easy to maintain programs.
6. Modularity: Through modularisation, we can break down a large program into small modules called
functions.
7. Limited Keywords: It has only 32 keywords and hence several standard functions are available with
‘C’ are used for developing error free programs.

Programs and Programming: A Program is a set of instructions compiled together in a file to


perform some specific task by the CPU (Central Processing Unit). It is a series of binary numbers (0s
and 1s) arranged in a sequence, which when given to the computer performs some task.
Programming is the process of writing an algorithm into a sequence of computer instructions. It
is the only way through which we can create our own programs and can execute them on a
computer. Programmers are the person who writes programs in a specific computer programming
language.
Programming languages: Types of Programming Languages: To write a program for a computer,
we must use a computer language. There are 3 types of programming languages.
1. Machine Language:
 In the earliest days of computer, the only programming languages available were machine
languages.
 Each computer has its own machine language which is made up of streams of O’s and 1’s.
Because the internal circuits are made of switches, transistors and other electronic devices that
can be in two states OFF or ON. The OFF state is represented by 0 and ON state by 1.
 Only few programmers are writing programs to work in machine language.
2. Symbolic Language (Assembly Language):
 In 1950, Admiral Grace Hopper a mathematician developed the concept of a special computer
program that will convert programs into machine language. This program uses symbols or
mnemonics to represent various machine language instructions. These languages were known as
symbolic languages.

1
NARN/ MCA / MODULE – I & II / C PROGRAMMING
 A computer does not understand symbolic language; it must be translated to machine. A special
program called an Assembler translates symbolic code into machine language, they known as
Assembly Languages. These languages were also machine dependent.
3. High-level Languages:
 High-level languages are portable to many different computers, and allow the programmer to
concentrate on problem rather than hardware of the computer.
 High-level languages must be converted to machine language. The process of converting is
known as Compilation.
 Some of the most widely used high-level languages are Fortran, Pascal, Cobol, C, C++ and etc.
 A compiler or interpreter is itself a computer program. It accepts a program written in a high-level
language (e.g., C) as input, and generates a corresponding machine-language program as output.
The original high-level program is called the source program, and the resulting machine-language
program is called the object program. Every computer must have its own compiler or interpreter
for a particular high-level language.
Compiler: A compiler is a special type of program that transforms the source code written in a
programming language (the source language)in to the machine language , which uses only two digits 0
and 1(the target language). The resultant code is 0s and 1s is known as the object code. The object code is
used to create an executable program.
 Therefore , a compiler is used to translate the source code from a high-level programming
language to a lower level language(e.g., assembly language or machine code). The work of a
compiler is only to translate human readable source code in to computer-executable machine
code.

Interpreter: like the compiler , the interpreter also executes instructions written in a high-level
language. Basically, a program written in a high-level language can be executed in any of the two ways-
by compiling the program or by passing the program through an interpreter.

2
NARN/ MCA / MODULE – I & II / C PROGRAMMING

Structured Programming Concept: In structured programming approach, the problem is viewed


as a sequence of things to be done such as reading, calculating and printing. The number of functions or
procedures is written to perform these tasks. So it is also called POP language. The primary focus is on
constructing procedures, and a little attention is given to the data.
The following are the characteristics of this approach:
1. Emphasis (Importance) is on preparing functions (algorithms).
2. Large programs are divided in to small programs known as functions.
3. Most of the functions share global data.
4. Data moves openly around the system from one function to another function.
5. Functions transform the data from one form to another.
6. It follows top-down approach in program design.
The high level languages such as COBOL, FORTRAN, PASCAL and C use the concepts of POP.

Algorithms: An algorithm is defined as a finite set of steps that provide a chain of actions for solving a
problem. Algorithm is a step-by-step method of solving a problem.
Characteristics of an Algorithm:
1) Finiteness: - An algorithm terminates after a finite numbers of steps.
2) Definiteness: - Each step in algorithm is unambiguous. This means that the action specified by the step
cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any
confusion.
3) Input: - An algorithm accepts zero or more inputs
4) Output:- An algorithm should produce at least one output.
5) Effectiveness: - It consists of basic instructions that are realizable. This means that the instructions can
be performed by using the given inputs in a finite amount of time.

Advantages of Algorithms:
1. It is a step-wise representation of a solution to a given problem, which makes it easy to understand.
2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to understand for anyone even without
programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
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.

Disdvantages of Algorithms:
1. Alogorithm is Time consuming.
2. Difficult to show Branching and Looping in Algorithms.
3. Big tasks are difficult to put in Algorithms.

Qualities of a good algorithm: The following are the primary factors that are often used to judge the
quality of an algorithm.
Time: The lesser is the time required to execute a program better is the algorithm
Memory: Computer takes some amount of memory to storage to execute a program. The lesser is the
memory required the better is the algorithm
Accuracy: Algorithms which provide the accurate results to a given problem should be chosen.
Sequence: The procedure of an algorithm must form in a sequence
Generability: The designed algorithm must solve the problem for a different range of input data.

Categories of Algorithm: The steps in an algorithm can be divided into three categories, namely
 Sequence
 Selection and
 Iteration

3
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Sequence: The steps described in an algorithm are performed successively one by one without skipping
any step.
 The sequence of steps defined in an algorithm should be simple and easy to understand.
 Each instruction of such an algorithm is executed, because no selection procedure or conditional
branching exists in a sequence algorithm.
Example:
// adding two timings
Step 1: start
Step 2: read h1, m1, h2, m2
Step 3: m=m1+m2
Step 4: h= h1 + h2 + m/60
Step 5: m=m mod 60
Step 6: write him
Step 7: stop

Selection
 We understand that the algorithms written in sequence fashion are not reliable. There must be a
procedure to handle operation failure occurring during execution.
 The selection of statements can be shown as follows
if(condition)
Statement-1;
else
Statement-2;
 The above syntax specifies that if the condition is true , statement-1 will be executed otherwise
statement-2 will be executed.
 In case the operation is unsuccessful. Then sequence of algorithm should be changed/ corrected in
such a way that the system will re-execute until the operation is successful.
Example:
// Person eligibility for vote
Step 1 : start
Step 2 : read age
Step 3 : if age > = 18 then step_4 else step_5
Step 4 : write “person is eligible for vote”
Step 5 : write “ person is not eligible for vote”
Step 6 : stop

Multi-way:
For a single problem, three may be multiple solutions. In such a situation we have to apply multi way
(switch case) decision statements or we can extend two-way statements (example, if else) in a ladder
form.
Example:
// Roots of a quadratic Equation
Step 1 : start
Step 2 : read a,b,c
Step 3 : if (a= 0) then step 4 else step 5
Step 4 : Write “ Given equation is a linear equation “
Step 5 : d=(b * b) _ (4 *a *c)
Step 6 : if ( d>0) then step 7 else step8
Step 7 : Write “ Roots are real and Distinct”
Step 8: if(d=0) then step 9 else step 10
Step 9: Write “Roots are real and equal”
Step 10: Write “ Roots are Imaginary”
Step 11: stop

Iteration
 In a program, sometimes it is very necessary to perform the same action for a number of times.
4
NARN/ MCA / MODULE – I & II / C PROGRAMMING
 If the same statement is written repetitively, it will increase the program code.
 To avoid this problem, iteration mechanism is applied.
 The statement written in an iteration block is executed for a given number of times based on certain
condition.
Example:
Step 1 : start
Step 2 : read n
Step 3 : repeat step 4 until n>0
Step 4 : (a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop

Flow charts:
A flowchart is a pictorial representation of an algorithm. It shows the flow of operation in pictorial form
and any error in the logic of the problem can be detected very easily. A flowchart uses different boxes
and symbols to denote different types of instructions. These symbols are connected by solid lines with
arrow marks to indicate the operation flow. Normally an algorithm is represented in the form of a
flowchart and the flowchart is then expressed in some programming language to prepare a computer
program.
Flow chart symbols: A few symbols are needed to indicate the necessary operations in flowcharts.
These symbols have been standardized by the American National Standard Institute (ANSI).These
symbols are
1.Terminal: The terminal (oval)symbol as the name implies is used to indicate the
beginning(start), ending(stop) and pause in the logic flow. It is the first and last symbol
in the programming logic.
2. Input/output:
The input/output (parallelogram) symbol is used to denote any function of an
input/output device in the program. All input/output instructions in the program are
indicated with this symbol.
3. Processing: A processing(rectangle) symbol is used in a flowchart to represent
arithmetic and data movement instructions. Thus all arithmetic processes of addition
,subtraction, multiplication etc
4. Flow lines: Flow lines with arrow heads are used to indicate the flow of operations i.e. the exact
sequence in which the instructions are to be executed. The normal flow of flowchart is
from top to bottom and left to right.
5. Decision: The decision (diamond) symbol is used in a flowchart to indicate a point at
which a decision has to be made and a branch to one of two or more alternate points is
possible.
Connectors: If a flowchart becomes very long the flow chart starts criss crossing at many
places that causes confusion and reduces understandability of the flowchart. Moreover there
are instances when a flowchart becomes too long to fit in a single page and the use of flow
lines become impossible. A connector symbol is represented by a circle. A pair of identically labeled
connector symbols is commonly used to indicate a continued flow when the use of a line is confusing. So
two connectors with identical labels can be used.
Predefined process: The predefined process(double sided rectangle) symbol is used in
flowcharts to indicate that modules or subroutines are specified elsewhere. Annotation:
The annotation (bracket with broken line) symbol is used in flowcharts to indicate the
descriptive comments or explanation of the instruction.

Ex1.Algorithm to find sum of two integer numbers


Algorithm sum ()
Process: To calculate of sum of two numbers
Pre condition: read two values
Post condition: sum of two values

5
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Return:nothing
Step 1:start
Step 2:read two integer numbers
Step 3:perform of sum of 2 numbers
Step 4:display the sum:
Step 5:stop
Ex2:Alogrithm to find sum of three integer numbers
Algorithm addition( )
Process:sum of three integers
Pre: read three integer values
Post:addition of three values
Return:nothing
Step 1 :start
Step2:read the three integers
Step 3:peform addition three values
Step 4: display the sum
Step 5: stop
Ex3:Algorithm to find sum of three floating point numbers
Algorithm floatsum( )
Process:addition of three floating point numbers
Pre: read three floating point numbers
Post:addition of three floating point numbers
Return:nothing
Step 1:start
Step 2:read three floating point numbers
Step 3:perform addition of three floating point values
Step 4:display the sum
Step 5:stop
Ex4:Algorithm to find average of two numbers
Algorithm average( )
Process: average of two numbers
Pre: read two values
Post :average of two values
Return:nothing
Step 1:start
Step2:read first number
Step 3: read second number
Step 4:perform sum of two numbers
Step 5:divide sum with 2
Step 6:print the average
Step 7:stop
Selection: Algorithm to find gretest among two numbers
Algorithm greatest( )
Process: greatest among two numbers
Pre: read two values
Post :large value among two
Return :nothing
Step 1:start
Step 2:read two numbers
Step 3:compare two values(ex a and b)
Step 4:if a is greater than b display a is greater otherwise b is greater
Step 5:stop
Iterative: Algorithm to find sum of n numbers
Algorithm sumofnnumbers( )
Process: cacluate sum of n numbers
Pre: read n numbers
Post: sum of n numbers
6
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Return:nothing
Step 1:start
Step 2:read numbers upto n(suppose if n=10 read 10 numbers)
Step 3: perform the addition
Step 4:repeat step 2 and step 3 upto n numbers addition
Step 5:display the result
Step 6:stop
Examples on flowcharts and algorithms:
1.Write an algorithm for finding the average of three numbers and draw the flowchart for the
same.
Step 1: read the value
Read a,b and c
Step2:compute sum=a+b+c
Avg=sum/3
Step 3:print avg
Step 4:stop
Example 2.Write an algorithm for finding greatest among two numbers
Step 1:start
Step 2:read two numbers
Step 3:compare two values(ex a and b)
Step 4:if a is greater than b display F
a is greater otherwise b is greater
Step 5:stop
Example 3: write an algorithm and flowchart for finding the sum of n numbers
Step 1:start
Step 2:read numbers upto n
Initialize count =1 sum=0
Step 3:repeat through count<=n
Step 4: x=1 sum=sum+x
Count=count+1
Step 5:print sum
Step 6:stop

Example 1 Example 2 Example 3


Advantages of flowchart:
1. A flowchart can easily explain the program logic to the program development team.
2. The flowchart details help prepare efficient program coding.
3. The flowchart helps detect and remove the mistakes in a program
4. A flowchart is useful to test the logic of the program.

7
NARN/ MCA / MODULE – I & II / C PROGRAMMING
1. Algorithm for exchanging the values of given two variables:
Algorithm 1: using a third variable
Step 1 : Start
Start 2 : READ num1, num2
Start 3 : temp = num1
Start 4 : num1 = num2
Start 5 : num2 = temp
Start 6 : PRINT num1, num2
Start 7 : Stop

Algorithm 2: without using a third variable


Step 1 : Start
Start 2 : READ num1, num2
Start 3 : num1 = num1 + num2
Start 4 : num2 = num1 - num2
Start 5 : num1 = num1 - num2
Start 6 : PRINT num1, num2
Start 7 : Stop

Program:
/* Exchange the values of two variables */
#include<stdio.h>
#include<conio.h>
int main()
{
int first, second, temp;
clrscr();
printf("Enter first number: ");
scanf("%d", &first);
printf("Enter second number: ");
scanf("%d", &second);
temp = first;
first = second;
second = temp;
printf("\nAfter swapping, firstNumber = %d\n", first);
printf("\nAfter swapping, secondNumber = %d\n", second);
return(0);
}
2. Algorithm for counting the number of digits in an integer:
Step 1 : Start
Step 2 : Initialize ‘n’ as integer variable and ‘count’ as 0
Step 3 : READ ‘n’ value
Step 4 : check the condition (n!=0)
Step 4.1 : update n=n/10
Step 4.2 : increment count by 1(count++)
Step 5 : PRINT ‘count’ value
Step 6 : Stop

Program:
8
NARN/ MCA / MODULE – I & II / C PROGRAMMING
/* counting the number of digits */
#include<stdio.h>
#include<conio.h>
int main()
{
int n,count=0;
clrscr();
printf("Enter the number: ");
scanf("%d", &n);
while(n!=0)
{
n=n/10;
count=count+1;
}
printf("\n Number of digits = %d ", count);
return(0);
}

3. Algorithm for summation of a set of numbers:


Step 1 : Start
Step 2 : Initialize ‘sum’ as 0
Step 3 : Declare ‘n’ and ‘i’ as integer type variables
Step 4 : Read the ‘n’ value
Step 5 : check for(i=1;i<=n;++i)
Step 5.1: sum=sum+i
Step 6 : Print ‘sum’ value
Step 7 : Stop

/* To find the summation of set of numbers */


#include <stdio.h>
#include<conio.h>
int main()
{
int n, i, sum = 0;
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);
for (i = 1; i <= n; ++i)
{
sum += i;
}
printf("Sum = %d", sum);
return 0;
}
4. Algorithm for factorial computation:
Step1: Start
Step 2: Declare ‘n’,’i’ and ‘f’ as integer variables
Step 3: Assign ‘f’ as 1

9
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Step 4: Read the ‘n’ value
Step 5: Check for(i=1;i<=n,i++)
Step5.1: Assign ‘f’ as f*i
Step 6: Display the factorial value ‘f’
Step 7: Stop
Program:
/* To find factorial of the given number */
#include <stdio.h>
#include <conio.h>
int main()
{
int n,i,f=1;
clrscr();
printf("\n Enter the number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n The factorial of %d is %d",n,f);
return(0);

5. Algorithm for generation of the Fibonacci sequence to the first ‘n’ terms:
Step 1: Start
Step 2: Declare i, n, f, f1, f2 as integer variables
Step 3: Read the ‘n’ value
Step 4: Initialize ‘f’ as 0 and ‘f1’ as 1
Step 5: Display ‘f’ and ‘f1’ values
Step 6: Check for(i=1;i<=n-2;i++)
Step 6.1: Find ‘f2’ as f+f1
Step 6.2: Display the value of ‘f2’
Step6.3: Assign ‘f’ as ‘f1’
Step 6.4: Assign ‘f1’ as ‘f2’
Step7: Stop
Program:
/ * c program to generate the first n terms of the fibonacci sequence */
#include<stdio.h>
void main()
{
int i,n,f,f1,f2;
clrscr();
printf("Enter Number of Fibonacci Values Needed : ");
scanf("%d",&n);
f=0;
f1=1;
printf(“%d\n%d\n”,f,f1);
for(i=1;i<=n-2;i++)
{

10
NARN/ MCA / MODULE – I & II / C PROGRAMMING
f2=f+f1;
printf(“%d\n”,f2);
f=f1;
f1=f2;
}
getch();
}

6. Algorithm for reversing the digits of an integer:

Step 1: Start
Step 2: Declare n, rev, rem as integer variables
Step 3: Initialize rev as zero
Step 4: Read ‘n’ value
Step 5: Check while (n!=0)
Step 5.1: rem=n%10
Step 5.2: rev=rev*10+rem
Step 5.3: n=n/10
Step 6: Display ‘rev’ value as output
Step 7: Stop
}
Program:
/* Reverse the digits of an given integer */
#include <stdio.h>
#include <conio.h>
int main()
{
int n, rev = 0, rem;
clrscr();
printf("\nEnter an integer: ");
scanf("%d", &n);
while (n != 0)
{
rem = n % 10;
rev = rev * 10 + rem;
n=n/10;
}
printf("\n The Reversed number of %d = %d",n,rev);
return(0);
}

Practice Programs in ‘C Language’:


To find the sum of two numbers
void main()
{
int a,b,sum; // Variable Declarations
clrscr(); // To clear the Text Mode Window
printf(“Enter a and b values:”);
scanf(“%d%d”,&a,&b); // To read Input
11
NARN/ MCA / MODULE – I & II / C PROGRAMMING
sum=a+b; // Method
printf(“%d+%d=%d”,a,b,sum); // To display Output
}
To exchange the values of two variables
void main()
{
int a,b,t; // Variable Declarations
clrscr(); // To clear the Text Mode Window
printf(“Enter a and balues:”);
scanf(“%d%d”,&a,&b); // To read Input
printf(“Before swapping a=%d b=%d”,a,b);
t=a;
a=b;
b=t; // Method
printf(“\n After swapping a=%d b=%d”,a,b); // To display Output
}
To caliculagte Simple Interest
void main()
{
int p,t;
float r,si; // Variable Declaration
clrscr(); // To clear the Text Mode Window
printf(“Enter Principle Amount, Time in months and Rate of interest:”);
scanf(%d%d%f”,&p,&t,&r); // To read Input
si=(p*t*r)/100; // Method
printf(“Simple Interest is %f”,si); // To display Output
}

How to develop a program: When we want to develop a program by using any programming
language, we have to follow a sequence of steps. These steps are called phases in program development.
The program development life cycle is a set of steps or phases which are used to develop a
program in any programming language.
Phases of program development
Program development life cycle contains 6 phases, which are as follows −

 Problem Definition.
 Problem Analysis.
 Algorithm Development.
 Coding & Documentation.
 Testing & Debugging.
 Maintenance.

12
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Problem Definition: In this phase, we need to understand what the problem statement is, what our
requirement is and what the output of the problem solution is.
Problem Analysis: Here, we determine the requirements like variables, functions, etc. to solve the
problem. It means that we gather the required resources to solve the problem, which are defined in the
problem definition phase.
Algorithm Development: Here, we develop a step-by-step procedure that is used to solve the problem
by using the specification given in the previous phase.
Coding & Documentation: Here, we use a programming language to write or implement the actual
programming instructions for the steps defined in the previous phase. We write the program to solve the
given problem by using the programming languages like C, C++, Java, etc.
Testing & Debugging: Here we try to test the program whether it is solving the problem for various
input data values or not. We also test if it is providing the desired output or not.
Maintenance: In this phase, we make the enhancements. If the user gets any problem or wants any
enhancement, then we need to repeat all these phases from the starting, so that the encountered problem
is solved or enhancement is added.
These six phases are depicted in the diagram given below –

13
NARN/ MCA / MODULE – I & II / C PROGRAMMING
MODULE – 2 Basic Elements of C
Basics of C: Introduction, Character Set, Structure of a C Program, A Simple C Program,
Variables, Data Types and Sizes, Declaration, how does The Computer Store Data in
Memory, Identifiers, Keywords, Constants, Assignment, and Initialization.
Operators and Expressions: Arithmetic Operators, Relational Operators, Logical
Operators, Bitwise Operators, Conditional Operator, Comma operator, sizeof operator,
Expressions, L values and R values, Expression Evaluation- Precedence and
Associativity, Type Conversion.

Introduction: C language facilitates a very efficient approach to the development and


implementation of computer programs. The History of C started in 1972 at the Bell
Laboratories, USA where Dennis M. Ritchie proposed this language. In 1983 the
American National Standards Institute (ANSI) established committee whose goal was to
produce “an unambiguous and machine independent definition of the language C “while
still retaining its spirit.

‘C’ TOKENS
The ‘C’ tokens are basic elements of a program that understood by compiler. The following are
the elements of a ‘C’ program.
1. C character set
2. Keywords (Reserved Words)
3. Identifiers (User-defined Words)
4. Constants
5. Operators
1. 'C' character Set:
A character represents any alphabet, digit and symbol used to indicate the information. The
following table shows valid alphabets, digits and symbols allowed in C language.

Lowercase Alphabets  a…z


Uppercase Alphabets  A…Z
Digits  0...9
Special Characters

14
NARN/ MCA / MODULE – I & II / C PROGRAMMING
2. Keywords: A keyword is a sequence of characters that has pre-defined meaning. It is also known as
reserved or pre-defined word. There are 32 keywords used in ‘C’ language. The keywords must be used
only for their specified purpose. The following are the list of keywords:
Auto break Case Char const continue default do
double else Enum Extern float for goto if
Int long Register Return short signed sizeof static
Struct switch Typedef Union unsigned void volatile while

3. Identifiers:
An identifier is a name given to a program element such as variables, constants, function names,
array names and so on. An identifier is also called user-defined word.

Rules for naming an identifier:


1. An identifier must contain combination of alphabets, digits and underscore only.
2. The first letter must be an alphabet.
3. The length of an identifier should not exceed 8 characters. But, some compilers allow upto 31
characters.
4. Blank spaces are not allowed
5. Special symbols other than underscore are not allowed
6. Keywords must not be used as identifiers.
7. An identifier must not be repeated (declaration) in a program
Examples:
Valid Identifiers: a salary sum emp_name c123 etc.
Invalid Identifiers: a+b 2abc float etc.
4. Constants:
A constant is a fixed value. It doesn’t change its value during the execution of the program. The
following are various types of constants.
 Integer Constants
 Floating Point Constants Number Type
 Single Character Constants
Character Type
 String Constants
Integer constants: Any number without fractional part is called an integer constant. The integer numbers
can contain digits (0…9) and sign (+ or -). An integer constant must not contain commas and spaces.
Integers can be decimal, octal or hexa-decimal.
Ex: 3 -3 15 -15 2500 -9700 etc.  Decimal Integers
03 0123 etc.  Octal Integers
0x3 0x123 etc.  Hexa-Decimal Integers

Floating Point (Real) Constants:


Floating point constants are also called real constants. A floating point number can contain digits
(0…9), a decimal point and/or exponent. The letter ‘E’ or ‘e’ represents the exponent.
Ex: 45.0 4520.2587 -6847.000 -74.56000 etc.
The exponent format (‘e’ notation) can be used to represent very small or large number.
Ex: 6.5E5 or 6.5E+5 means 6.5x105
6.5E-5 means 6.5x10-5
Single Character Constants:
A single character constant contains only one character enclosed within single quotes. It may
contain any alphabet, digit or special symbol. It can be used for arithmetic operations. However, its
ASCII value is used in arithmetic operation.
Ex: ‘A’ ‘h’ ‘4’ ‘+’ ‘&’ etc.
String Constants:
A string constant is a sequence of one or more characters enclosed within double quotes. It can
contain alphabets, digits or special symbols.
Ex: “A” “ABCDE” “%d” “Result = %d” etc.

15
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Structure of a c program:
Every C program consists of one or more modules called functions. One of the functions must be
called main. The program will always begin by executing the main function, which may access other
functions. Any other function definitions must be defined separately, either before or after main.
A C program may contain one or more sections as given below.
 The Documentation section consists a set of comment lines that gives the name of the program,
author and other details. The comments must be enclosed within the pair /* ………. */
 The Link Section provides instructions to the compiler to link functions from the system library.
 The Definition section defines all symbolic constants.
 The Global Declaration section contains the variables such as global, to be used in more than one
function.
 Every program have one main( ) section, it contains two parts, Declaration part and Executable part.
The declaration part declares all the variables used in the executable part. There is at least one
executable part in the program. These two parts must appear between the opening { and closing }
braces.
 The subprogram section contains all the user-defined functions that are called in the main function.

Documentation Section
Link Section
Definition Section
Global Declaration Section
main( )
{
Declaration Part
Executable Part
}
Subprogram Section
Function1
Function2
…… …..
Function n
A Simple C Program:
Below are few commands and syntax used in C programming to write a simple C program. Let’s
see all the sections of a simple C program line by line.

C Basic commands Explanation

This is a preprocessor command that includes standard input output header


#include <stdio.h> file(stdio.h) from the C library before compiling a C program

int main() This is the main function from where execution of any C program begins.

{ This indicates the beginning of the main function.

whatever is given inside the command “/* */” in any C program, won’t be
/*_some_comments_*/ considered for compilation and execution.

printf(“Hello_World! “); printf command prints the output onto the screen.

getch(); This command waits for any character input from keyboard.

return 0; This command terminates C program (main function) and returns 0.

} This indicates the end of the main function.

16
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Below C program is a very simple and basic program in C programming language. This C
program displays “Hello World!” in the output window. And, all syntax and commands in C
programming are case sensitive. Also, each statement should be ended with semicolon (;) which is a
statement terminator.

1 #include <stdio.h>
2 int main()
3{
4 /* Our first simple C basic program */
5 printf("Hello World! ");
6 getch();
7 return 0;
8}
OUTPUT:
Hello World!

Steps To Write C Programs And Get The Output:


Below are the steps to be followed for any C program to create and get the output. This is common to all
C program and there is no exception whether its a very small C program or very large C program.

1. Create
2. Compile
3. Execute or Run
4. Get the Output

Creation, Compilation And Execution Of A C Program:


 If you want to create, compile and execute C programs by your own, you have to install C
compiler in your machine. Then, you can start to execute your own C programs in your machine.
 You can refer below link for how to install C compiler and compile and execute C programs in
your machine.
 Once C compiler is installed in your machine, you can create, compile and execute C programs as
shown in below link.
 If you don’t want to install C/C++ compilers in your machine, you can refer online compilers
which will compile and execute C/C++ and many other programming languages online and display
outputs on the screen. Please search for online C/C++ compilers in Google for more details.

Variables:
 C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
 The value of the C variable may get change in the program.
 C variable might be belonging to any of the data type like int, float, char etc.

Rules for naming C variable:


1. Variable name must begin with letter or underscore.
2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. sum, height, _value are some examples for variable name

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.

17
NARN/ MCA / MODULE – I & II / C PROGRAMMING
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’;
There are two types of variables in C program They are,
1. Local variable
2. Global variable
Local variable
 The scope of local variables will be within the function only.
 These variables are declared within the function and can’t be accessed outside the function.
Global variable
 The scope of global variables will be throughout the program. These variables can be accessed
from anywhere in the program.
 This variable is defined outside the main function. So that, this variable is visible to main function
and all other sub functions.

Data types and sizes


In C programming language, data types refer to an extensive system used for declaring variables
or functions of different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted. C data types are defined as the data storage format that a
variable can store a data to perform a specific operation. Data types are used to define a variable before to
use in a program.
Fundamental Data Types in C:
Integer type Floating type Character type

Following table gives you details about standard integer types with its storage sizes and value ranges:
Type Storage size Value range
Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295

Floating-Point Types: Following table gives you details about standard floating-point types with storage
sizes and value ranges and their precision:
Type Storage size Value range Precision
Float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
Double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Identifiers: C identifiers represent the name in the C program, for example, variables, functions,
arrays, structures, unions, labels, etc. An identifier can be composed of letters such as uppercase,
lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an underscore.
If the identifier is not used in the external linkage, then it is called as an internal identifier. If the identifier
is used in the external linkage, then it is called as an external identifier.
18
NARN/ MCA / MODULE – I & II / C PROGRAMMING
We can say that an identifier is a collection of alphanumeric characters that begins either with an
alphabetical character or an underscore, which are used to represent various programming elements such
as variables, functions, arrays, structures, unions, labels, etc. There are 52 alphabetical characters
(uppercase and lowercase), underscore character, and ten numerical digits (0-9) that represent the
identifiers. There is a total of 63 alphanumerical characters that represent the identifiers.

Rules for constructing C identifiers


 The first character of an identifier should be either an alphabet or an underscore, and then it can be
followed by any of the character, digit, or underscore.
 It should not begin with any numerical digit.
 In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers
are case sensitive.
 Commas or blank spaces cannot be specified within an identifier.
 Keywords cannot be represented as an identifier.
 The length of the identifiers should not be more than 31 characters.
 Identifiers should be written in such a way that it is meaningful, short, and easy to read.
Example of valid identifiers: total, sum, average, _m _, sum_1, etc.
Example of invalid identifiers:
1. 2sum (starts with a numerical digit)
2. int (reserved word)
3. char (reserved word)
4. m+n (special character, i.e., '+')

Constants:
 C Constants are also like normal variables. But, only difference is, their values cannot be
modified by the program once they are defined.
 Constants refer to fixed values. They are also called as literals
 Constants may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of C constant:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
S.no Constant type data type Example
int 53, 762, -478 etc
unsigned int 5000u, 1000U etc
1 Integer constants
long int 483,647
long long int 2,147,483,680
float 10.456789
2 Real or Floating point constants
doule 600.123456789
3 Octal constant Int 013 /* starts with 0 */
4 Hexadecimal constant Int 0×90 /* starts with 0x */
5 character constants char ‘A’ , ‘B’, ‘C’
6 string constants char “ABCD” , “Hai”

19
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Rules for constructing C constant:
1. Integer Constants in C:
 An integer constant must have at least one digit.
 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.
 If no sign precedes an integer constant, it is assumed to be positive.
 The allowable range for integer constants is -32768 to 32767.
2. Real constants in C:
 A real constant must have at least one digit
 It must have a decimal point
 It could be either positive or negative
 If no sign precedes an integer constant, it is assumed to be positive.
 No commas or blanks are allowed within a real constant.
3. Character and string constants in C:
 A character constant is a single alphabet, a single digit or a single special symbol enclosed within
single quotes.
 The maximum length of a character constant is 1 character.
 String constants are enclosed within double quotes.
4. Backslash Character Constants in C:
 There are some characters which have special meaning in C language.
 They should be preceded by backslash symbol to make use of special function of them.
 Given below is the list of special characters and their purpose.
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\o Octal constant (N is an octal constant)
\x Hexadecimal constant (N – hex.dcml cnst)

Assignment and initialization


 C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
 The value of the C variable may get change in the program.
 C variable might be belonging to any of the data type like int, float, char etc.
Rules For Naming C Variable:
1. Variable name must begin with letter or underscore.
2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. sum, height, _value are some examples for variable name
20
NARN/ MCA / MODULE – I & II / C PROGRAMMING
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.
Type Syntax

data_type variable_name;
Variable declaration Example: int x, y, z; char flat, ch;

data_type variable_name = value;


Variable initialization Example: int x = 50, y = 30; char flag = ‘x’, ch=’l’;

OPERATORS
An operator is a symbol used to perform arithmetic and logical operations. It is used to
manipulate data stored in the variables.
‘C’ language has the following types of operators.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional or Ternary operator
7. Bitwise operators
8. Special operators
1. Arithmetic operators: Arithmetic operators are used to perform arithmetic calculations. The
following are the various arithmetic operators.
Operator Meaning Example Result
+ Addition 10+3 13
– Subtraction 10-3 7
* Multiplication 10*3 30
/ Division 10/3 3
10/3.0 3.3333
% Modulo division (Remainder) 10%3 1
2. Relational Operators: The relational operators are used to compare two values and give either true
(1) or false (0) result. These are used to form simple conditions.

Operator Meaning Example Result


== Equal to 10 = = 15 0 (F)
!= Not equal to 10 != 15 1 (T)
> Greater than 10 > 15 0 (F)
< Less than 10 < 15 1 (T)
>= Greater than or equal to 10 >= 15 0 (F)
<= Less than or equal to 10 <= 15 1 (T)

3. Logical Operators: These are used to combine two conditions or to negate the result of a condition.
They also give the result either true or false. They are used to form compound conditions.

Operator Meaning Description Example Result


&& Logical AND Gives true if both conditions 10>15 && 10>15 False (0)
are true
¦¦ Logical OR Gives true if any or both 10>15 ¦ ¦ 100>15 True (1)
conditions are true
! Logical NOT Gives true if condition is false, ! (10>15) True (1)
gives false if condition is true

21
NARN/ MCA / MODULE – I & II / C PROGRAMMING

4. Assignment Operators: The assignment operators are used to assign (store) a value to a variable. An
assignment operator always consists of a variable on left hand side and a valid expression / constant /
variable on right hand side. There are two types of assignment operators. They are
1. Simple Assignment Operator
2. Compound Assignment Operators
Simple Assignment Operator: The equal sign ‘=’ is used as simple assignment operator. The general
format of this operator is as follows:
Expression
Variable = Constant
Variable
In the above syntax, the value of Expression / Constant / Variable is assigned to the variable on the left
hand side of ‘=’ sign.
Eg: x = 35: y = a + b * c: z = y: a = b = 50:

Compound Assignment Operators:


The general form of compound assignment operators is as follows

Expression
Variable Compound Constant
operator
Variable

In the above syntax, the operator can be either +=, –=, *=, /= or %=
Example, Let a=10, then
Operator Example Meaning Final Value of ‘a’
+= a+=5 a=a+5 15
–= a–=5 a=a–5 5
*= a*=5 a=a*5 50
/= a/=5 a=a/5 2
%= a%=5 a=a%5 0
5. Increment and Decrement Operators:
Increment Operator (++):
The increment operator is a unary operator. It is used to increase the value of a variable by
1. It is used in two ways. They are pre-increment and post-increment.

Pre-increment: If the ‘++’ operator precedes the variable then it is called “Pre increment”. In this
method, the pre-increment operator increments the value of variable first and then the new value is used
in the expression.
For example: c = ++a; means a = a + 1; and then
c = a;
Post-increment: If the ‘++’ operator succeeds the variable then it is called “Post increment”. In this
method, the value of the variable is used in expression and then it is incremented.

For example: c = a++; means c = a; and then


a = a + 1;
Decrement Operator (– –):
The decrement operator is a unary operator. It is used to decrease the value of a variable by
1. It is used in two ways. They are pre-decrement and post-decrement.

Pre-decrement: If the ‘– –’ operator precedes the variable then it is called “Pre decrement”. In this
method, the pre-decrement operator decrements the value of variable first and then the new value is used
in the expression.
For example: c = – – a; means a = a – 1; and then
c = a;

22
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Post-decrement: If the ‘– –’ operator succeeds the variable then it is called “Post decrement”. In this
method, the value of the variable is used in expression and then it is decremented.

For example: c = a – –; means c = a; and then


a = a – 1;
Initial Values Expression Final Values
A b A B
3 7 a = ++b
3 7 a = b++
3 7 a = – –b
3 7 a=b––
3 7 a = ++b
3 7 a=b––
6. Conditional or Ternary Operator:
This operator executes statements based on condition. This operator operates on three operands.
Hence it is also known as Ternary Operator. It simplifies “if…else” control statement.

Syntax: (condition) ? Statement-block1 : Statement-block2 :


Working: The conditional operator first tests the given condition. If the condition is true then
‘Statement-block1’ is executed. If the condition is false then ‘Statement-block2’ is executed. Statement
blocks may contain one or more statements. When there is more than one statement, they must be
separated by commas.
Example :
large = (a>b) ? a : b;

In the above example, if a>b then the value ‘a’ is assigned otherwise the value of ‘b’ is assigned to the
variable ‘large’.

7. Bitwise Operators:
‘C’ language has the capability of manipulating the bits (0 or 1) directly stored in the memory.
These operators perform operations on bit by bit level. They must be used only with integer or character
type of values. The operators are as follows

Operator Meaning
& Bitwise AND
¦ Bitwise OR
^ Bitwise XOR (Exclusive OR)
~ Bitwise 1’s complement
>> Bitwise Right shift
<< Bitwise Left shift

Bitwise AND (&) operator:


If all the bits are “1” then this operator returns “1” otherwise it returns “0”.

Truth table: Example: Let x=240 and y=170 then


& 1 0
1 1 0 x : 0000000011110000
0 0 0 y : 0000000010101010
x & y: 0000000010100000

Bitwise OR ( ¦ ) operator:
If any or all the bits are “1” then it returns “1” otherwise it returns “0”.

23
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Truth table: Example: Let x=240 and y=170 then

¦ 1 0 x : 0000000011110000
1 1 1 y : 0000000010101010
0 1 0 x ¦ y: 0000000011111010

Bitwise XOR ( ^ ) operator:


If one bit is “1” and other is “0” then it returns “1” otherwise it gives “0”.
Truth table: Example: Let x=240 and y=170 then

^ 1 0 x : 0000000011110000
1 0 1 y : 0000000010101010
0 1 0 x ^ y: 0000000001011010

1’s complement (~) operator:


It is unary operator that reverses the state of each bit. That means it changes “0” as “1” and “1” as
“0”.
Example: Let x=240 then x : 0000000011110000
~x: 1111111100001111

Left Shift (<<) operator:


This operator is used to move bit patterns to the left. It is used in the following form
op<<n
Here, ‘op’ is an integer value and ‘n’ is number of bit positions. It shifts bits of ‘op’ to the left by
‘n’ positions. The left most ‘n’ bits will be lost and ‘n’ zeros will be added on right side.

Example: Let x=240 then x : 0000000011110000


x<<3 : 0000011110000000
x<<5 : 0001111000000000
Right Shift (>>) operator:
This operator is used to move bit patterns to the right. It is used in the following form
Op>>n
Here, ‘op’ is an integer value and ‘n’ is number of bit positions. It shifts bits of ‘op’ to the right by
‘n’ positions. The right most ‘n’ bits will be lost and ‘n’ zeros will be added on left side.

Example: Let x=240 then x : 0000000011110000


x>>3 : 0000000000011110
x>>5 : 0000000000000111
8. Special Operators:
The following are the special operators used in ‘C’ language.
 Sizeof operator
 Typecast operator
 Address operator (&)
 Indirection operator (*)
 Comma operator (,)

Sizeof operator: This operator returns the memory size of an operand.


Syntax: sizeof(operand) The operand may be a variable or data type.
Examples:
Expression Value of ‘a’
a=sizeof(int) 2
a=sizeof(float) 4
a=size(char) 1
a=sizeof(long double) 10
24
NARN/ MCA / MODULE – I & II / C PROGRAMMING
Typecast Operator (Typecasting):
When a value is converted from a data type to another data type then it is called type casting. The
type cast operator is used to convert the value to a different data type. The value must be preceded by the
required data type name enclosed within parenthesis.
Syntax: (datatype) operand Here, operand may be constant, variable or expression.
Example:
main ( )
{ int a=25 ;
float x, y ;
x=a/4;
y = (float) a / 4 ;
printf(“x = %f”,x) ;
printf(“y = %f”,y) ;
}
Output:
X = 6.0000
Y = 6.25000
Address Operator (&):
The address operator gives the address of the variable. This operator returns unsigned integer.
Syntax: &variable
Example:
main( )
{ int a=10; a b
float b=25.5; 10 25.5
printf(“The value of a is %d”,a); 4958 5677
printf(“The address of a is %u”,&a);
printf(“The value of b is %f”,b);
printf(“The address of b is %u”,&b);
}

Indirection Operator (*):


The indirection operator gives the value at the specified address.
Syntax: * (address)
Example:
main( ) a
{ 10
int a=10: 4958
printf(“The value of a is %d”,a);
printf(“The address of a is %u”,&a);
printf(“The value at address of a is %d”,*(&a));
}

Comma Operator:
This operator is used to separate multiple statements. It appears in the following statements:
Variable declaration
Input and output statements
Control statements
Example:
main( )
{
int a, b, c;
clrscr( );
scanf(“%d%d”,&a,&b);
c = a, a = b, b = c;
printf(“a=%d \n”, a);
printf(“b=%d”,b);
}
25
NARN/ MCA / MODULE – I & II / C PROGRAMMING

EXPRESSIONS
Definition: An expression is a collection of operands joined together by certain operator that represent
a value. There are two types of expressions. They are
1. Arithmetic or Numeric Expression
2. Relational or Boolean Expression

Arithmetic Expression:
When an expression uses arithmetic operators then it is called arithmetic or numeric expression.
An arithmetic or numeric expression always represents numeric value.

1. Two successive operators are not permitted. However, the space(s) or parenthesis can be used to
separate two successive operators.
Example: a*-25 is invalid, a*(-25) is valid
2. Arithmetic operations cannot be implied. It means, no operator is assumed to be present.
Example: a = bc+d(x+y+z) is invalid
a = b*c+d*(x+y+z) is valid.
3. The evaluation of an arithmetic expression follows the precedence order of operators.
For example: 5+2*5 gives 15 and (5+2)*5 gives 35
4. There cannot be imbalance of parenthesis. The number of left parenthesis must be equal to the
number of right parenthesis.
5. The arithmetic operation between two integers gives integer result. It is Integer mode expression.
Example: 5/2 gives 2
6. The arithmetic operation between two float values gives float result. It is real mode expression
Example: 5.0 / 2.0 gives 2.5
7. The arithmetic operation between an integer and a float value gives float result. It is mixed mode
expression.
Example: 5 / 2.0 gives 2.5
8. The arithmetic operation can be performed between integer and character datatypes.
Example: ‘A’+30 gives 95

Relational or Boolean Expression:


When an expression uses relational and logical operators then it is called relational expression. A
relational expression is also known as condition or logical expression. This expression gives the result
either true (1) or false (0).
Examples:
1. a>b
2. salary <= 5000
3. x==0
4. (a>b¦ ¦a>c)
5. ((avg >= 50) && (avg <= 75))

OPERATOR PRECEDENCE

Question: Explain about operator precedence. (or) Explain about hierarchy of operators. (or) Explain
how an expression is evaluated with examples. (or) Write about operator priority in an expression with
examples.
---
In ‘c’ language, an expression is evaluated based on the precedence order of operators. The
following table shows various operators and their precedence.

Precedence Operator Type Operators Associativity


Order
1 Special Symbols ()[]. LR
2 Unary operators +, –, *, &, !, ++, – – RL
26
NARN/ MCA / MODULE – I & II / C PROGRAMMING
3 Arithmetic operators *, /, % LR
(Multiply, Divide, Modulo)
4 Arithmetic Operators +, – LR
(Add, Subtract)
5 Relational operators >, <, = =, >=, <=, != LR
6 Logical operators &&, ¦ ¦ LR
7 Conditional operator ?: RL
8 Bitwise operators &, ¦, ^, ~, >>, << LR
9 Assignment operators =, *=, /=, %=, +=, –= RL
10 Post-increment and decrement ++, – – RL
Operators

Evolution of operators in an expression is as follows:


1. An expression will be evaluated based on the priority of operators.
Example: 5+3*2
In the above expression, there are two operators (+ and *) in which * has high priority. So the
operator * is evaluated first and then + is evaluated. Hence the result is 11.
2. If an expression has equal priority operators then the expression is evaluated based on the
associativity.
Example: 5+3–2
In the above expression, the operators ‘+’ and ‘–’ have equal priority. Their associativity is left to
right. So first “+” is evaluated and then ‘–’ is evaluated. Hence the result is 6.
3. In case, if we want to change priority order then we can put an expression within parenthesis.
Example: (5+3)*2 gives the result 16

Example: x=3*2/2+3/2+2–2+3*2
=6/2+3/2+2–2+3*2
=3+3/2+2–2+3*2
=3+1+2–2+3*2
=4+2–2+6
=6–2+6
=4+6
= 10

27

You might also like