Unit -1
Unit -1
Unit -1
INTRODUCTION TO PROGRAMMING
History of Computers:
The earliest tool is abacus, a device used in china and United Statestoday as a hand held
calculator.
They require human involvement.
The first attempt was made by Charles Babbage in creating aprogrammable computing
machine in England in 1822.
Ada Byron the daughter of famous poet Lord Byron developed theinstruction set for the
machine.
The machine that Babbage called it was analytical engine.
In 1937, Dr. John V Atanas off and a graduate student, Clifford Berry developed a
machine called ABC using electrical components at Lowa State University.
The goal internally was to store a set of instructions. In 1939, Dr.John W Mauchly from
Moore college of Engineering at Pennsylvania University along with Presper Eckert
developed a computer called ENIAC (Electrical Numerical Integrator and Computer).
The fund was given by US government and was completed in 1946.
It consists of 18000 vacuum tubes and can perform 5000 additionsand 360 multiplications
in one second.
At the same time Mark developed a computer by name Mark I atHarvard University using
mechanical relays and completed in 1944.
But it could perform only 6 multiplications in one second.
The final goal of storing the program in computer was achieved in 1949 at
Cambridge University with the successful operation of EDSAC (Electronic Delayed
Storage Automatic Computer).
1
Introduction To Programming
This contains memory where it could store data.
The principles for storing the data and retrieve data and instructions has been proposed by
John Von Neumann.
*****
Definition of Computer:
Computer is an electronic device and it takes the data and instructions as Input and process that
data according to the user instructions and produces the result as output.
1. Speed:
A computer can do the calculations very fastly. A computer can do the 3 to 4 millions of simple
arithmetic calculations per a second. A Human can do a work with in the days that can be done by the
computer with in the milliseconds. The speed of a computer can measured in terms of milliseconds,
micro seconds, nanoseconds and picoseconds.
2. Accuracy:
The computer is capable of doing calculations with a high accuracy. Moreover, it does every
calculation with the same accuracy.
3. Diligence:
The computer is capable of doing work for hours and that too without creating any error. It does not
feel tiredness or lack of concentration.
4. Versatility:
Versatility refers to the capability of a computer to perform different kinds of works with same
5. Memory Capability:
The computer does not differentiate the type of data to be remembered. It is a capable of storing and
recalling any amount of information in its secondary storage device. The memory can be measured in
terms of BITs, Bytes, Kilo Bytes, Mega Bytes, Giga Bytes, etc.
6. Intelligence:
The present day computer does not possess intelligence of its own. Its intelligence quotient is zero.
Computer is obedient servant to its master and works according to the user commands.
2
Introduction To Programming
*****
1. Input Unit.
3. Output Unit.
1. INPUT UNIT
• Computers need to receive data and instruction in order to solve any problem.
• We need to input the data and instructions into the computers.
• The input unit consists of one or more input devices.
• Keyboard is the one of the most commonly used input device.
• Other commonly used input devices are the Mouse, Scanner, Microphone, etc.
3
Introduction To Programming
Supply the converted data to the computer system for further processing.
4
Introduction To Programming
• This memory is generally used to hold the program being currently executed in the
computer, the data being received from the input unit,the intermediate and final results of
the program.
• The primary memory is temporary in nature.
• The data is lost, when the computer is switched off.
• In order to store the data permanently, the data has to be transferredto the secondary
memory.
• The cost of the primary storage is more compared to the secondarystorage.
• Therefore, most computers have limited primary storage capacity.
b) Secondary Storage
Secondary storage is used like an archive. It stores several programs, documents, data
bases etc.
The programs that you run on the computer are first transferred tothe primary memory
before it is actually run.
Whenever the results are saved, again they get stored in the secondary memory.
The secondary memory is slower and cheaper than the primarymemory.
Some of the commonly used secondary memory devices are Hard disk,CD, etc.,
3. OUTPUT UNIT
The output unit of a computer provides the information and results ofa computation to
outside world.
Printers, Visual Display Unit (VDU) are the commonly used output devices.
Other commonly used output devices are Speaker, Headphone,
Projector, etc.
*****
PROGRAM COUNTER
A register is a small place for data holding that the processor uses.
Program counter is just a small register that could hold 8 bit or 16 bitdata.
It depends on the processor that process data either 8 bit or 16 bit.
In computing, a program is a specific set of ordered operations for acomputer to perform.
An instruction is an order given to a computer processor by aprogram.
Within a computer, an address is a specific locationin memory or storage.
5
Introduction To Programming
As each instruction gets fetched, the program counter increases itsstored value by 1.
After each instruction is fetched, the program counter points to the next instruction in the
sequence.
When the computer restarts or reset, the program counter normally reverts to 0.
It is used to keep track of all instructions that are to be processed.
*****
6
Introduction To Programming
There are some problems with the machine language.
It is difficult to understand and remember the various combinations of 0’s and 1’s for
instructions and data.
Writing error free instructions is a slow process.
The user cannot communicate with other machine because every machine has its own
machine language
The programmers even today they prefer assembly language forperforming various tasks.
To initialize and test the system hardware
To write patches for disassembling viruses
To attain optimization
For direct interaction with hardware
To maximize limited resource utilization
For high security
7
Introduction To Programming
They are easy to use, portable and abstract when compared to lowlevel languages.
They use logic to solve the problem.
The high level languages are executed by using a compiler or aninterpreter.
The high level languages are classified into three categories.
Procedure oriented languages (third generation)
Problem oriented languages (fourth generation)
Natural languages (fifth generation)
Natural languages
These languages are known as fifth generation languages.
These languages are designed to make computer to behave like expert and solve
problems.
The programmer specifies both the problem and its constraints forproblem solving.
These languages are used to develop artificial intelligence andexpert systems.
The fifth generation languages allow users to communicate with the
computer in simple and easy manner.
8
Introduction To Programming
Class is the basic building block of the OOP, a class consists dataattributes and methods
that operate on data.
Object is runtime instance of the class. An object has a state, a defined behavior and
unique identity.
The state of the object is represented by the data defined in the class.
Class is template for object.
Abstraction, Encapsulation, Inheritance and Polymorphism are uniquefeatures of OOP.
*****
An algorithm is defined as a finite sequence of instructions eachof which has a clear meaning
and can be performed with a finite amount of effort in a finite amount of time.
The algorithm word originated from the Arabic word “Algorism”which is linked to the name
of the Arabic mathematician AI Khwarizmi.
He is considered to be the first algorithm designer for adding numbers.
Properties of Algorithms
1. Finiteness: An algorithm must terminate after a finite number of steps.
2. Definiteness: The steps of the algorithm must be precisely defined or unambiguously specified.
3. Generality: An algorithm must be generic enough to solve allproblems of a particular
class.
4. Effectiveness: The operations of the algorithm must be effective such that it must easily
converted into machine code in a finite amount of time.
5. Input-Output: The algorithm must have zero, one or more inputs and one or more outputs.
9
Introduction To Programming
Step 1: Start
Step 2: Read a, b
Step 3: c a+b
Step 4: Write C
Step 5: Stop.
*****
FLOW CHART:
Flow chart is diagrammatic representation of an algorithm.
It is built using different types of boxes of symbols.
The operation to be performed is written in the box.
All symbols are interconnected by arrows to indicate the flow ofinformation and
processing.
Any processing to be
performed. An assignment
Rectangle Process operation normally represented
by this symbol.
10
Introduction To Programming
Bracket with Annotation Descriptive comments or
broken line explanations
*****
PSUEDO CODE
The enhanced form of an algorithm that focuses on logic of the program is called
pseudo code.
It refers to false code written in a programming language.
It does not have any syntax for representation but normally usedstructured English
language for representation.
It helps programmer to understand the basic logic before writing thefinal code in a
particular language.
EXAMPLE
To add two numbers
1. DEFINE n1, n2, result
2. READ n1, n2
11
Introduction To Programming
3. COMPUTE result – n1 + n2
4. DISPLAY result
5. EXIT
Advantages of Pseudo Code
1. It is easier to modify the program logic when necessary.
2. It takes less time for writing it
3. It takes less effort for writing it
4. Converting it to programming code is easier.
5. It does not have any syntax therefore we can write it as we like.
12
Introduction To Programming
Compiling Programs
The job of the compiler is to convert the source file into machinelanguage.
There are two separate programs in C compiler:
Preprocessor
Translator
The preprocessor reads the source code and prepares it for thetranslator.
It scans for preprocessor commands and tell to replace the code.
The result of preprocessing is translation unit.
The translator does the actual work of converting the program tomachine language.
The translator reads translation unit and produce object module as
output
This is not yet ready to run because it needs required functions to include.
Linking Programs
C program is made up of many functions, some we write and some they are part of the
source program.
13
Introduction To Programming
There are other functions like input/output and mathematical libraries that are attached
to source program
The linker assembles all these functions to make it finally executable.
Executing Programs
The program is ready for execution if it is linked with necessaryroutines.
To execute the program we use OS command run to load the programin main memory
and execute it.
The loading activity is done by loader. The program execution means
Reads data for processing from file or from user
Process the data
Prepare the output for the user
*****
Structure of a C Program:
14
Introduction To Programming
Ex:
printf(“WELCOME”);
}
15
Introduction To Programming
OUTPUT: WELCOME
2. Write a C program for addition of 2 numbers.
#include<stdio.h>
void main( )
{
int a,b,c;
clrscr( );
a=100; b=200;
c=a+b;
printf(“\n sum=%d”,c);
}
OUTPUT: sum=300
C Character Set
As every language contains a set of characters used to construct words, statements, etc., C language
also has a set of characters which include alphabets, digits, and special symbols. C language
supports a total of 256 characters. C language character set contains the following set of characters...
1. Alphabets
2. Digits
3. Special Symbols
Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters
Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
16
Introduction To Programming
C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell
TOKENS:
A token in C can be defined as the smallest individual element of the C programming language
that is meaningful to the compiler. It is the basic component of a C program.
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keywords: The keywords are pre-defined or reserved words in a programming language.
Each keyword has a specific meaning in C language and they can’t be used for any other
purposes which they define. Since keywords are referred names for a compiler. C language
supports 32 keywords which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
2. Identifiers: A name in C program is called as Identifier that may be variable name, array
name, function name, structure name, etc. Identifiers are the user-defined names consisting of
C character set. Identifiers are used to identify a particular element in a program. Each
Identifier must have a unique name. following are the Rules for writing Identifiers:
17
Introduction To Programming
• They must consist of only letters, digits, or underscore. No other special character is
allowed.
3. Constants: The constants refer to the variables with fixed values. They are like normal
variables but with the difference that their values can not be modified in the program once
they are defined. “const” is a keyword which is used to define the constants.
Example:
float x=4.567;
4. Strings: String is a collection of Characters enclosed with in the double quotes and end with a
null character (‘\0’). This null character indicates the end of the string.
Example:
5. Special Symbols: The following special symbols are used in C having some special meaning
and thus, cannot be used for some other purpose. Some of these are listed below:
• Brackets[]: Opening and closing brackets are used as array element references.
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 mark the start and end of a block of
code containing more than one executable statement.
• Comma (, ): It is used to separate more than one statement like for separating
parameters in function calls.
• Colon(:): It is an operator that essentially invokes something called an initialization
list.
• Semicolon(;): It is known as a statement terminator. It indicates the end of one logical
entity. That’s why each individual statement must be ended with a semicolon.
• Asterisk (*): It is used to create a pointer variable and for the multiplication of
variables.
• Assignment operator(=): It is used to assign values and for logical operation
validation.
18
Introduction To Programming
• Pre-processor (#): The pre processor is a macro processor that is used automatically
by the compiler to transform your program before actual compilation. Period (.):
Used to access members of a structure or union.
6. Operators: Operator is a Symbol which is used to perform either Mathematical or Logical
Operations.
*****
Data Types/Types:
To store data the program must reserve space which is done using datatype. A datatype is a
keyword/predefined instruction used for allocating memory for data. A data type specifies the type of
data that a variable can store such as integer, floating, character etc. It used for declaring/defining
variables or functions of different types before to use in a program.
19
Introduction To Programming
The basic data types are integer-based and floating-point based. C language supports both signed and
unsigned literals. The memory size of basic data types may change according to 32 or 64 bit
operating system. Let‟s see the basic data types. Its size is given according to 32 bit architecture
Size and Ranges of Data Types with Type Qualifiers
20
Introduction To Programming
• Range: -32768 to 32767
• Size: 2 bytes
• Format Specifier: %d
Syntax for declaring the Integer variables:
int var_name;
Ex:
int a;
int x,y;
The integer data type can also be used as
1. unsigned int: Unsigned int data type in C is used to store the data values from zero to positive
numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768 to
32,767.
3. long int: Larger version of the int datatype so can store values greater than int.
4. unsigned short int: Similar in relationship with short int as unsigned int with int.
Note: The size of an integer data type is compiler-dependent. We can use sizeof operator to check the
actual size of any data type.
Character Data Type
Character data type allows its variable to store only a single character. The size of the character is 1
byte. It is the most basic data type in C. It stores a single character and requires a single byte of
memory in almost all compilers. The char keyword is used to declare the variable of character type.
Range: (-128 to 127) or (0 to 255)
• Size: 1 byte
• Format Specifier: %c
Syntax for declaring the Character variables:
char var_name; Ex:
char a;
char x,y;
Float Data Type
In C programming float data type is used to store floating-point values. Float in C is used to store
decimal and exponential values. It is used to store decimal numbers (numbers with floating point
values) with single precision. The float keyword is used to declare the variable as a floating point:
Range: 1.2E-38 to 3.4E+38
• Size: 4 bytes
21
Introduction To Programming
• Format Specifier: %f
Syntax for declaring the floating point variables: float
var_name;
Ex:
float a;
float x,y;
Double Data Type
A Double data type in C is used to store decimal numbers (numbers with floating point values) with
double precision. It is used to define numeric values which hold numbers with decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding 64 bits of
decimal numbers or floating points. Since double has more precision as compared to that float then it
is much more obvious that it occupies twice the memory occupied by the floating-point type. It can
easily accommodate about 16 to 17 digits after or before a decimal point. The variable can be declared
as double precision floating point using the double keyword:
• Range: 1.7E-308 to 1.7E+308
• Size: 8 bytes
• Format Specifier: %lf
Syntax for declaring the double variables:
double var_name;
Ex:
double a;
double x,y;
Void Data Type: The void data type in C is used to specify that no value is present. It does not
provide a result value to its caller. It has no values and no operations. It is used to represent nothing.
Void is used in multiple ways as function return type, function arguments as void, and pointers to
void.
***** Variables:
A variable in C language is the name associated with some memory location to store data of
different types. There are many types of variables in C depending on the scope, storage class, lifetime,
type of data they store, etc. A variable is the basic building block of a C program that can be used in
22
Introduction To Programming
expressions as a substitute in place of the value it stores. Following is the syntax for declaring the
variables in C language.
data_type variable_name; // defining single
variable or
data_type variable_name1, variable_name2; // defining multiple variable
Here,
• data_type: Type of data that a variable can store and it is a valid data type.
• variable_name: Name of the variable given by the user.
Example: int var; // integer variable
char a; // character variable
float fff; // float variables
Rules for Naming Variables in C:
1. A variable name must only contain alphabets, digits, and underscore.
2. A variable name must start with an alphabet or an underscore only. It cannot start with a digit.
3. No whitespace is allowed within the variable name. 4. A variable name must not be any reserved
word or keyword.
Variable Initialization
The process of assigning a value to a variable is called initialization.
The process of giving a value to a variable is called initialization.
The process of presenting a value to a variable is called initialization. The
process of specifying a value to a variable is called initialization.
For example: x = 10;
in the above statement the variable is “x” and the value is “10”. Herethe value 10 is
given to the variable x by using assignment operator “=”.Therefore if we want to assign a value
23
Introduction To Programming
to a variable then we need anassignment operator. The variable here used “x” is called
initialized variable.
For example:
int x=10;
float y=2.5;
char = ‘a’;
in the above statements the variables are initialized to values that are of different data
type. The variables are called initialized variables or variables are said to be initialized.
Types of Variables in C
1. local variable
2. global variable
3. static variable
Constants
Constants refer to fixed values that do not change during the execution of a program.
TYPES OF C CONSTANT:
24
Introduction To Programming
1. Integer constants
3. Character constants
4. String constants
Integer constants:
An integer constant is a numeric constant (associated with number) without any fractional or
For example:
• In C programming, octal constant starts with a 0 and hexadecimal constant starts with a
• 0x
25
Introduction To Programming
7 $77
77 077
+77 7,777
2 : Octal : An integer constants with base 8 is called octal. These rules are:
-012
Ex : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
A floating point constant is a numeric constant that has either a fractional form or an exponent
-2.0
26
Introduction To Programming
0.0000234
-0.22E-5
Character Constant:
Single Character Constant: A character constant is either a single alphabet, a single digit, a
EX : VALID INVALID
„a‟ “12”
String constant : A string constant is a sequence of characters enclosed in double quote, the
characters may be letters, numbers, special characters and blank space etc
27
Introduction To Programming
Introduction To Programming
a) \n newline
b) \r carriage return
c) \t tab
d) \v vertical tab
e) \b backspace
g) \a alert (beep)
h) \‟ single quote(„)
i) \” double quote(“)
k) \\ backslash (\)
1. const keyword
2. #define preprocessor
1) C const keyword
29
Introduction To Programming
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
5. clrscr();
7. getch();
8.}
Output:
2) C #define preprocessor
C#define
The #define preprocessor directive is used to define constant or micro substitution. It can use any
Syntax:
#include <stdio.h>
1. #define PI 3.14
2. main ()
30
Introduction To Programming
3. printf("%f",PI);
4.}
Output:
3.140000
Input / Output (I/O) Functions : In „C‟ language, two types of Input/Output functions are
available, and all input and output operations are carried out through function calls. Several
functions are available for input / output operations in „C‟. These functions are collectively known
Input: In any programming language input means to feed some data into program. This can be
Output: In any programming language output means to display some data on screen, printer or
in any file.
C programming treats all the devices as files. So devices such as the display are addressed in
the same way as files and the following three files are automatically opened when a program
31
Introduction To Programming
Formatted I/O Functions: formatted I/O functions operates on various types of data.
1 : printf() : output data or result of an operation can be displayed from the computer to a
standard output device using the library function printf(). This function is used to print any
combination of data.
Formatting string: it prints all the character given in double quotes (“ “) except formatting Specifier.
2. scanf() : input data can be entered into the computer using the standard input „C‟ library
function called scanf(). This function is used to enter any combination of input.
The scanf() function is used to read information from the standard input device (keyboard).
Each variable name (argument) must be preceded by an ampersand (&). The (&) symbol gives the
meaning “address of “the variable.
a) Character I/O
b) String I/O
a) character I/O:
32
Introduction To Programming
3. getch() and getche(): these are used to take the any alpha numeric characters from the standard
input
b) String I/O:
1. gets(): Used for accepting any string from the standard input(stdin) eg:gets()
Operators : An operator is a Symbol that performs an operation. An operators acts some variables
are called operands to get the desired result.
Ex : a+b;
Types of Operator:
1) Arithmetic Operators.
2) Relational Operators.
3) Logical Operators.
4) Assignment Operators.
5). Unary Operators.
6) Conditional Operators.
7) Special Operators.
8) Bitwise Operators.
33
Introduction To Programming
Arithmetic Operators:
#include <stdio.h>
void main()
int a = 9,b = 4, c; c =
a+b; printf("a+b = %d \
n",c); c = a-b;
printf("a-b = %d \n",c);
c = a*b; printf("a*b =
%d \n",c); c=a/b;
printf("a/b = %d \n",c);
c=a%b;
}
Output
a+b =
13 a-b =
5 a*b =
36 a/b =
2
34
Introduction To Programming
#include <stdio.h>
int main()
int a = 5, b = 5, c = 10;
Output
5 == 5 = 1
5 == 10 = 0
5>5=0
5 > 10 = 0
5<5=0
5 < 10 = 1
35
Introduction To Programming
5 != 5 = 0
Logical Operators.
These operators are used to combine the results of two or more conditions. An expression containing
logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical
operators are commonly used in decision making in C programming.
36
Introduction To Programming
< b);
37
Introduction To Programming
printf("(a != b) || (c < b) equals to %d \n", result);
return 0;
}
Output
„C‟ provides compound assignment operators to assign a value to variable in order to assign a new
value to a variable after performing a specified operation.
Conditional operator checks the condition and executes the statement depending of the condition. A
conditional operator is a ternary operator, that is, it works on 3 operands.
38
Introduction To Programming
1:
que
stio
mar
(?).
2:
colo
n (:
).
It first evaluate the condition, if it is true (non-zero) then the “exp1” is evaluated, if
the condition is false (zero) then the “exp2” is evaluated.
Bitwise Operators:
Bitwise operators are used to manipulate the data at bit level. It operates on integers
only. It may not be applied to float. In arithmetic-logic unit (which is within the
Introduction To Programming
Output
Output =8
Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C
Programming, bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
Introduction To Programming
~ 00100011
________
11011100 = 220 (In decimal)
For Example,
Let us consider the number 14. Now, the binary representation of this number is 00001110
in 8 bits (for convenience, let us consider it this way).
In this case, the 14 >> 1 will shift this binary sequence by a single position to the right.
Like,
In this example, you can clearly notice that all the bits have shifted to the left once we
performed the left shift operation on the binary value. The empty space thus created is now
filled with zeroes (0).
Thus, the value obtained from 40 << 1 is 01010000, and 80 is the decimal equivalent of this
binary value.
Special Operators
1) Comma Operator: The comma operator is used to separate the statement elements such
as variables, constants or expressions, and this operator is used to link the related
expressions together, such expressions can be evaluated from left to right and the value of
right most expressions is the value of combined expressions
Ex : val(a=3, b=9, c=77, a+c)
First signs the value 3 to a, then assigns 9 to b, then assigns 77 to c, and finaly80 (3+77) to value.
2 ) Sizeof Operator : The sizeof() is a unary operator, that returns the length in bytes o the
specified variable, and it is very useful to find the bytes occupied by the specified variable
in thememory.
Syntax : sizeof(variable-name);
int a;
Ex : sizeof(a); //OUTPUT-----2bytes
Example #6: sizeof
Operator #include <stdio.h>
int main() { int a, e[10];
float b; double c; char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
printf("Size of integer type array having 10 elements = %lu bytes\n",
sizeof(e)); return 0; }
Output
Size of int = 4 bytes
Introduction To Programming
Expressions
Expressions: An expression is a combination of operators and operands which reduces to a
Single value. An operator indicates an operation to be performed on data that yields a value.
An operand is a data item on which an operation is performed.
A simple expression contains only one operator.
Ex: 3+5 is a simple expression which yields a value 8, -a is also a single expression.
Operator Precedence: Arithmetic Operators are evaluated left to right using the
Precedence of operator when the expression is written without the paranthesis.They are
two Levels of arithmetic operators in C. 1: High Priority * / % 2: Low Priority + -.
Arithmetic Expression evaluation is carried out using the two phases from left to right.
1: First phase: The highest priority operator are evaluated in the 1st phase.
2: Second Phase: The lowest priority operator are evaluated in the 2nd phase.
Ex:
a=x-y/3+z*2+p/4.
x=7, y=9, z=11, p=8.
a= 7-9/3+11*2+8/4.
1st phase:
1: a = 7-3+11*2+8/4
2: a = 7-3+22+8/4
3: a = 7-3+22+2
2nd phase:
1: a = 4+22+2
2: a = 26+2
3: a = 28
The order of evaluation can be changed by putting parenthesis in an expression.
Ex: 9-12/ (3+3)*(2-1)
Introduction To Programming
Whenever parentheses are used, the expressions within parenthesis highest priority. If two
or more sets of parenthesis appear one after another. The expression contained in the
leftmost set is evaluated first and the right-most in the last.
1st phase:
1: 9-12/6*(2-1)
2: 9-12/6*1
2nd
phase: 1:
9-2*1 2:
9-2.
3rd phase:
1: 7.
5: Apply the associative rule, if more operators of the same precedence occurs.
Operator Precedence and Associativity:
'long' to 'int'. You can convert the values from one type to another explicitly using the cast
Introduction To Programming
1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2
Example
Consider the following code:
int x=7, y=5 ;
float z;
z=x/y; /*Here the value of z is 1*/
If we want to get the exact value of 7/5 then we need explicit casting from
float:int to
int x=7, y=5;
float z;
z = (float)x/(float)y; /*Here the value of z is 1.4*/
42