PSTC Unit-1
PSTC Unit-1
UNIT-I
Introduction to Computer:
A Computer is an electronic device that takes data and instructions as an input from
the user, process data, and provides useful information known as output. This cycle of
operation of a computer is known as the input-process-output cycle.
Data : Data is the collection of different types of entities (i.e A-Z,0-9, symbols and
character sets etc.) or the raw facts of a computers are called data.
Information : The meaning full results occurred from data after performing process
on it.
Process : The intermediate work performed between data and information is know
as process.
Client
Cloud Server
Distribu
ted
Cloud Computing Environment : The computing is moved away from individual computer
systems to a cloud of computers in cloud computing environment. The cloud users only see the
service being provided and not the internal details of how the service is provided. This is done
by pooling all the computer resources and then managing them using a software.
There are three levels of programming languages are available. They are:
1. Machine languages (Low-level Languages)
2. Assembly languages (Symbolic Languages)
3. High level languages
Machine Languages
A language that is directly understood by the computer without any translation is
called machine languages. A machine language is string of 0s and 1s. Machine language are
usually referred to as the first generation languages. It is also referred to as machine code or
object code. Therefore, all instructions and data should be written using binary codes i.e., 0’s
and 1’s.Each instruction performs a specific task, such as a load, a jump, or an ALU operation
on a unit of data in a CPU register or memory.
Advantages:
Execution speed is very fast
Efficient use of primary memory
It does not require any translation because machine code is directly understood by the
computer.
Disadvantages
Machine dependent: The machine language is different for different types of
computers.
Difficult to write program: because it requires memorizing dozens of opcodes for
different commands.
Error prone: Difficult to modify
Advantages
Easier to memorize and use:Assembly language program is easy to use,
understand and memorize because it uses mnemonic codes in place of binary codes
Easy to write input data: In assembly language programs the input data can be
written in decimal number system, later they are converted into binary.
It is easier to correct errors and modify program instructions.
The Assembly Language has the same efficiency of execution as the machine level
language. Because this is one-to-one translator between assembly language
program and its corresponding machine language program.
Easy print out.
Good library facility.
Disadvantages
Machine dependent. A program written for one computer might not run in other
computers with different hardware configuration.
Knowledge of hardware is required.
Time consuming
Translators required (i.e. Assembler)
Assembler: The software used to convert an assembly language programs into machines
codes is called an assembler.
High-level programming languages can be classified into the following three categories:
English words are used to denote variables, programming structures and commands, and
Structured Programming is supported by most 3GLs. commonly known 3GLs are FORTRAN,
BASIC, Pascal and the C-family (C, C+, C++, C#, Objective-C) of languages.
4GLs are designed to reduce the overall time, effort and cost of software development. The
main domains and families of 4GLs are: database queries, report generators, data
manipulation, analysis and reporting, screen painters and generators, GUI creators,
mathematical optimization, web development and general purpose languages. also known as a
4th generation language, a domain specific language, or a high productivity language.
Advantages:
High-level languages are user-friendly
They are easier to learn
They are easier to maintain
They are problem-oriented rather than 'machine'-based
A program written in a high-level language can be translated into many machine
languages and can run on any computer for which there exists an appropriate translator
The language is independent of the machine on which it is used i.e. programs
developed in a high-level language can be run on any computer text
They are similar to English and use English vocabulary and well-known symbols
A high-level language has to be translated into the machine language by a translator,
which takes up time
The object code generated by a translator might be inefficient compared to an
equivalent assembly language program
Syntax Error
Syntax is a set of rules by which a programming language is governed. Syntax error
occurs when these rules are violated while coding of the program.
Logical Error
Improper coding of individual statements either or sequence of statements causes this
type of computer program. It does not stop the program execution but gives wrong results.
Runtime Error
This error in a computer program stops its execution. It may be caused by an entry of
invalid data.
1.4 Algorithm:
An algorithm is a finite set of step-by-step instructions to solve a problem. The
essential properties of an algorithm are:
1. Finiteness: The algorithm must always terminate after a finite number of steps.
2. Definiteness: Each and every instruction should be precise and unambiguous i.e. each
and every instruction should be clear and should have only one meaning.
3. Effectiveness: Each instruction should be performed in finite amount of time.
4. Input and Output: An algorithm must take zero or more inputs, and produce one or
more outputs.
5. Generality: An algorithm applies to different sets of same input type.
Advantages:
1. It is step-by-step solution to a given problem which is very easy to understand.
2. It has got a definite procedure.
3. It is easy to first develop an algorithm, then convert into a flowchart and then into a
computer program.
4. It is easy to debug as every step has got its own logical sequence.
5. It is independent of programming languages.
Disadvantages:
1. It is time consuming and cumbersome as an algorithm is developed first which is
converted into flowchart and then into a computer program
2. Algorithm lacks visual representation hence understanding the logic becomes
difficult.
Examples:
Write an algorithm to add two numbers
Step 1: Start
Step 2: Declare variables num1, num2 and sum
Step 3: Read num1 and num2
Step 4: Add num1 and num2 and assign the result to sum. sum←num1+num2
Step 5: Display sum
Step 6: Stop
1.5 Flowchart
Flowchart is a pictorial or symbolic representation of an algorithm.It indicates process of
solution. They are constructed by using special geometrical symbols. Each symbol represents
an activity. Flowcharts are read from top to bottom unless a branch alters the normal flow.
Advantages
1. It clarifies the program logic.
2. Before coding begins the flowchart assists the programmer in determining the type of
logic control to be used in a program
3. The flowchart gives pictorial representation
4. Serves as documentation
5. Serves as a guide for program writing.
6. Ensure that all possible conditions are accounted for.
7. Help to detect deficiencies in the problem statement.
Disadvantages:
1. When the program logic is complex the flowchart quickly becomes complex and
clumsy and lacks the clarity of decision table.
2. It alterations and modifications are required, the flowchart may require re-drawing
completely.
3. As the flowchart symbols cannot be typed reproduction of flowcharts often a problem.
4. It is sometimes difficult for a business person or user to understand the logic depicted
in a flowchart.
The example of a pseudo code to add two numbers and display the result as shown below:
Advantages
Developing program code using Pseudo codeis easier.
The program code instructions are easier to modify in comparison to a flowchart.
It is well suited for large program design.
Disadvantages
It is difficult to understand the program logic since it does not use pictorial
representation.
There is no standard format for developing a Pseudocode
Debugger
This program helps us identify syntax errors in the source code.
Pre Processer
There are certain special instructions within the source code identified by the # symbol
that are carried on by a special program called a preprocessor.
Compiler
It is a program which translates a high level language program into a machine language
program.
Interpreter
An Interpreter is a program which translates statements of a program into machine code. It
translates only one statement of the program at a time.
Linker
The machine code relating to the source code you have written is combined with
some other machine code to derive the complete program in an executable file. This is done
by a program called the linker.
Loader
Loader is a program that loads machine codes of a program into the system memory.
In Computing, a loader is the part of an Operating System that is responsible for loading
programs.
6. Errors are displayed after entire Errors are displayed every instruction
program is checked. Eg: C compiler interpreted. Eg: BASIC
C language is not high level language and not a low level language. It is a middle level
language with high level and low level features.
Importance of C
It is a robust language whose rich set of built in functions and operators can be used to
write any complex program. The C compiler combines the capabilities of an assembly
Why Use c?
Powerful and flexible
C is a powerful and flexible language. The language itself places no constraints on you.
C is used for projects as diverse as operating systems, Word Processors, graphics,
spreadsheets, and even compilers for other languages.
Popular
C is a popular language preferred by professional programmers. As a result, a wide
variety of C compilers and helpful accessories are available for use by programmers.
Portable
C is a portable language. Portable means that a C program written for one computer
system (say an IBM PC) can be compiled and run on another system (say a DEC VAX
system) with little or no modification. Portability is enhanced by the ANSI standard for
C, the set of rules for C compilers.
Minimum keywords
C is a language of few words, containing only a handful of terms, called keywords,
which serve as the base on which the language's functionality is built. There is a
misconception with many that a language with more key words (sometimes called
reserved words) would be more powerful. This isn't true.
Modular
C is a modular. C code can (and should) be written in routines called functions. These
functions can be reused in other applications or programs. By passing pieces of
information to the functions, you can create useful, reusable code.
Source Characters
These are characters that are used to create source text file. Source characters include
Alphabets A to Z, a to z
Digits 0,1,2,3,4,5,6,7,8,9
Special Characters , . ; : ? ‘ “ ! | / \ ~ _ $ % # & ^ * + - <> ( ) { } [ ] and blank
Execution Characters
The meaning of these characters is interpreted at the time of execution. These are also
known as “Escape sequences because the backslash (\) is considered as an ‘escape’ character.
It causes an escape from normal interpretation of a string. so that the next character is
recognized as one having special meaning.
Escape sequences
Escape
Meaning Result
Sequence
Moves the cursor to the previous position of the current
Backspace Line
\b
Multi-line comments start with characters /* and end with characters */. Any text
between those characters is considered a multi-line comment.
1. Constants:
Constant can be defined as a value that can be stored in memory and cannot be
changed during execution of the program. Constants are used to define fixed values like pi. C
has four basic types of constants. They are:
Integer Constant
An integer constant must have at least one digit and should not have a decimal point. It can be
either positive or negative.
Examples for integer constants
1 9 234 999
Floating point Constant
A floating point constant is decimal number that contains either a decimal point or an
exponent. In the other words, they can be written in 2 forms: fractional and exponential.
When expressed in fractional form, note the following points.
1. There should be at least one digit, and could be either positive or negative value. A
decimal point is must.
2. There should be no commas or blanks.
Examples for fractional form
12.33 -19.56 +123.89 -0.7
When expressed in exponential form, a floating point constant will have 2 parts. One is before
e and after it. The part which appears before e is known as mantissa and the one which follows
is known as exponent. When expressed in this format, note the following points.
1. mantissa and exponential should be separated by letter E.
2. mantissa can have a positive and negative sign.
3. default is positive.
Character Constant
These are single character enclosed in single quotes. A character can be single
alphabet, single digit, single special symbol enclosed with in single quotes. Not more than a
single character is allowed.
Example
‘a’ ‘Z’ ‘5’ ‘$’
String Constant
A String constant is sequence of characters enclosed in double quotes. So “a” is not
same as ‘a’. The characters comprising the string constant are stored in successive memory
locations.
Example: “hello” “programming” “cse”
2. Variables/Identifiers
Variable is named memory location that can be used to store values. These variables
can take different values but one value at a time. These values can be changed during
execution of a program.
Identifiers are basically names given to program elements such as variables, arrays and
functions.
3. Key words:
These are also called as reserved words.
All Keywords have fixed meanings and these meanings cannot be changed.
There are 32 keywords in C programming.
Keywords serve as basic building blocks for a program statement.
All keywords must be written in lowercase only.
ANSI C Keywords
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
4. Delimiters
Delimiters are used for syntactic meaning in C. These are given below:
2. Character variables
Numeric variables
Numeric variables can be used to store either integer values or floating point values.
While an integer value is a whole number without a fraction part or decimal point. A floating
point value can have a decimal point.
Numeric values may be associated with modifiers like short, long, signed, and
unsigned.
Character variables
Character variables can include any letter from the alphabet or from ASCII chart and numbers
0-9 that are given within single quotes.
Variable declaration
To declare a variable, specify the data type of the variable followed by its name. The
data type indicates the kind of data that the variable will store. Variable names should always
be meaningful and must reflect the purpose of their usage in the program. In C, variable
declaration always ends with a semicolon, for example:
char grade;
int emp_no;
float salary;
double bal_amount
unsigned short int acc_no;
C allows multiple variable of same type to be declared in one statement, so the following
statement is absolutely legal in C
float temp_in_deg, temp_in_farh;
Initializing variables
Assigning value to variable is called variable initialization. For example:
char grade= ‘A’;
int emp_no=1007;
float salary=8750.25;
double bal_amount=100000000
Note: When variables are declared but not initialized they usually contain garbage values.
Declaring Constants
To declare a constant, precede the normal variable declaration with const keyword and
assign it a value. For example,
const float pi=3.1415;
This const keyword specifies that the value of cannot change.
C provides a standard minimal set of data types. Sometimes these are also called as ‘Primitive
types’. They are:
‘char’ is used to store any single character.
‘int’ is used to store integer value.
‘float’ is used to store floating point value
‘double’ is used for storing long range of floating point number.
Type Qualifiers
In addition, C has four type qualifiers, also known as type modifiers which precede the basic
data type. A type modifier alters the meaning of basic data type to yield a new data type. They
are as follows:
Short
long ( to increase the size of an int or double type)
signed
unsigned
Size qualifiers: alters the size of basic data type. The keywords long and short are two size
qualifiers. For example:
long int i;
The size of int is 2 bytes but, when long keyword is used, that variable will be either 4 bytes or
8 bytes.
Sign qualifiers: Whether a variable can hold only positive value or both values is specified by
sign qualifiers. Keywords signed and unsigned are used for sign qualifiers.
Example
Suppose a variable can be assigned only an integer value. Such variable can be declared as
int a;
This declaration reserves two bytes of memory for storing the number. Such a variable can
store a number in range -32768 to 32767. In order to increase the range you can add a qualifier
to the declaration.
long int a;
The following table shows the basic data types with qualifiers and their ranges.
void type
This type holds no value and thus valueless. It is primarily used in three cases:
1. To specify the return type of a function (when the function returns no value)
2. To specify the parameters of the function (when the function accepts no arguments
from the caller.
3. To create generic pointers.
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. There are
two types of comment lines.
1. Block comment lines /* */ and
2. Single line comment lines. //
Link section
The link section provides instructions to the compiler to link functions from the system
library.
#include directive
The #include directive instructs the compiler to include the contents of the file
"stdio.h" (standard input output header file) enclosed within angular brackets.
Definition section
The definition section defines all symbolic constants. #define PI 3.1413
Every C program must have one main function section. This section contains two
parts:
1. Declaration part and
2. Executable part
Declaration part: It declares all the variables used in the executable part.
Subprogram section
The subprogram section contains all the user-defined functions that are called in the
main () function. User-defined functions are generally placed immediately after the main ()
function, although they may appear in any order.
For Example a ‘C’ program that prints welcome message:
#include<stdio.h>
int main( )
{
printf(“Welcome to C Programming\n”);
return 0;
}
Output
Welcome to C Programming.
Format specifiers
Format
Data Type Display
specifier
%c Char Single character
%c unsigned char
%s Sequence of characters (String)
Int Signed integer (both +ve and –ve
%d values)
%u unsigned int Unsigned integer (only +ve values)
%hd short int Signed short integer
%ld long int Long integer
unsigned long Unsigned long integer (only +ve
%lu
Int values)
%o Int Octal values
%x Int Hexa decimal values
%f Float Floating-point value
Long Double precision floating-point
%lf
float/double value
long double Double precision floating-point
%Lf
value
%p pointer Address stored in pointer
%% None Prints %
Flag Meaning
-- Left justify the display
+ Display the positive sign of value
0 Pad with leading zeros
space Display space if there is no sign
Examples:
printf(“Result:%d%c%f\n”,12,’a’,2.3);
Result:12a2.3
printf(“Result:%d\t%c\t%f\n”,12,’a’,2.3);
Result:12 A 2.3
printf(“%6d\n”,1234);
1 2 3 4
printf(“%06d\n”,1234);
0 0 1 2 3 4
printf(“%-6d\n”,1234);
1 2 3 4
printf(“%-06d\n”,1234);
- 0 1 2 3 4
printf(“%2d\n”,1234);
1 2 3 4
printf(“%9.2f\n”,123.456);
1 2 3 . 4 6
char ch=’A’;
printf(“%c\n%2c\n%3c\n”,ch,ch,ch);
A
A
A
printf(“%X\n”,255);
FF
Syntax
scanf(“control string”,variable1,variable2,…,variable n);
This function should have at least two parameters. First parameter is control string which is
conversion specification character. It should be within double quotes. This may be one or
more, it depends on the number of variables. The other parameter is variable names.
Each variable must preceded by ampersand (&) sign. This gives starting address of the
variable name in memory. scanf ( ) uses all the format specifiers used in printf( ) function.
Note: comments are not allowed in scanf()
For example, consider the following simple programs.
#include <stdio.h>
int main()
{
int x;
printf(“Enter number:”);
scanf(“%d”, &x);
M.Ramesh , Dept of CSE, IIIT-Nuzivid, RGUKT. Page 21
UNIT-I C Programming
1.13 Operators in C :
An operator is defined as a symbol that operates on operands and does
something. The something may be mathematical, relational or logical operation. C language
supports a lot of operators to be used in expressions. These operators can be categorized into
the following groups:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Increment/Decrement operators
5. Bitwise operators
6. Conditional operators
7. Assignment operators
8. Special operators
Arithmetic operators
These are used to perform mathematical operations.
These are binary operators since they operate on two operands at a time.
They can be applied to any integers, floating-point number or characters.
C supports 5 arithmetic operators. They are +, -, *, /, %.
The modulo (%) operator can only be applied to integer operands and cannot be used
on float or double values.
Consider three variables declared as,
int a=9,b=3,result;
We will use these variables to explain arithmetic operators. The table shows the arithmetic
operators, their syntax, and usage in C language.
#include<stdio.h>
int main()
{
int a=9,b=3;
printf("%d+%d=%d\n",a,b,a+b);
printf("%d-%d=%d\n",a,b,a-b);
printf("%d*%d=%d\n",a,b,a*b);
printf("%d/%d=%d\n",a,b,a/b);
printf("%d%%%d=%d\n",a,b,a%b);
return 0;
}
Output
9+3=12
9-3=6
9*3=27
9/3=3
9%3=0
Relational operators
A relational operator, also known as a comparison operator, is an operator that
compares two operands. The operands can be variables, constants or expressions. Relational
operators always return either true or false depending on whether the conditional relationship
between the two operands holds or not.
C has six relational operators. The following table shows these operators along with their
meanings
#include<stdio.h>
int main()
{
int a=9,b=3;
printf("%d>%d=%d\n",a,b,a>b);
printf("%d>=%d=%d\n",a,b,a>=b);
printf("%d<%d=%d\n",a,b,a<b);
printf("%d<=%d=%d\n",a,b,a<=b);
printf("%d==%d=%d\n",a,b,a==b);
printf("%d!=%d=%d\n",a,b,a!=b);
return 0;
}
Output
9>3=1
9 >= 3 = 1
9<3=0
9 <= 3 = 0
9= =3 = 0
9 != 3 = 1
Logical operators
Operators which are used to combine two or more relational expressions are known as
logical operators. C language supports three logical operators – logical AND(&&), logical
OR(||), logical NOT( !).
Logical&& and logical || are binary operators whereas logical ! is an unary
operator.
All of these operators when applied to expressions yield either integer value 0
(false) or an integer value 1(true).
Logical AND
It is used to simultaneously evaluate two conditions or expressions with relational
operators. If expressions on the both sides (left and right side) of logical operators is true then
the whole expression is true otherwise false. The truth table of logical AND operator is given
below:
A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1
Logical OR
It is used to simultaneously evaluate two conditions or expressions with relational
operators. If one or both the expressions on the left side and right side of logical operators is
true then the whole expression is true otherwise false. The truth table of logical OR operator is
given below:
A B A||B
0 0 0
0 1 1
1 0 1
1 1 1
Logical NOT
It takes single expression and negates the value of expression. The truth table of logical NOT
operator is given below
A !A
0 1
1 0
For example: x and y are two variables. The following equations explain the use of logical
operators.
z1 = x&&y …1
z2 = x||y …2
z3 =!x …3
Unary operators
Unary operators act on single operands. C language supports three unary operators. They are:
1. Unary minus
2. Increment operator
3. Decrement operator
Unary minus
The unary minus operator returns the operand multiplied by –1, effectively changing its
sign. When an operand is preceded by a minus sign, the unary minus operator negates its value.
For example,
int a, b=10;
a=-(b);
the result of this expression is a=-10.
printf("x=%d\n", x++);
printf("x=%d\n",++x);
printf("x=%d\n",x--);
printf("x=%d\n",--x);
printf("x=%d\n",-x);
return 0;
}
Output
x=5
x=7
x=7
x=5
x=-5
Bitwise operators
As the name suggests, the bitwise operators operate on bits. These operations include:
1. bitwise AND(&)
2. bitwise OR(|)
3. bitwise X-OR(^)
4. bitwise NOT(~)
5. shift left(<<)
6. shift right(>>)
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
For example:
In a C program, the | operator is used as follows.
int a=4,b=2,c;
c=a^b;
printf(“%d”,c); //prints 6
Shift operators
C supports two bitwise shift operators. They are shift-left (<<) and shift-right (>>).
These operations are simple and are responsible for shifting bits either to left or to the right.
The syntax for shift operation can be given as:
Assignment operators
Assignment operator (=)
In C, the assignment operator (=) is responsible for assigning values to variables. When
equal sign is encountered in in an expression, the compiler processes the statement on the right
side of the sign and assigns the result to variable on the left side. For example,
int x;
x=10;
Assigns the value 10 to variable x. if we have,
int x=2,y=3,sum=0;
sum = x + y;
then sum=5.
The assignment has right-to-left associativity, so the expression
int a=b=c=10;
is evaluated as
(a=(b=(c=10)))
#include <stdio.h>
int main()
{
int a = 21,c;
c = a;
printf("Operator is = and c = %d\n", c ); c += a;
printf("Operator is += and c=%d\n",c); c −= a;
printf("Operator is −= and c=%d\n",c); c *= a;
printf("Operator is *= and c=%d\n",c); c /= a;
printf("Operator is /= and c=%d\n", c);
iii. = 200; c %= a;
printf("Operator is %= and c=%d\n",c); c <<= 2;
printf("Operator is <<= and c=%d\n",c);
c >>= 2;
printf("Operator is >>= and c=%d\n",c);
c &= 2;
Output
Operator is = and c = 21
Operator is += and c = 42
Operator is −= and c = 21
Operator is *= and c = 441
Operator is /= and c = 21
Operator is %= and c = 11
Operator is <<= and c = 44
Operator is >>= and c = 11
Operator is &= and c = 2
Operator is ^= and c = 0
Operator is |= and c = 2
Advantages:
1. Short hand expressions are easier to write.
2. The statement involving short hand operators are easier to read as they are more
concise.
3. The statement involving short hand operators are more efficient and easy to
understand.
Conditional operator (? : )
It is also called ternary operator because it takes three operands. It has the general form:
variable = expression1 ? expression2 : expression3;
If the expression1 is evaluated to true then it evaluates expression2 and its value is
assigned to variable, otherwise it evaluates expression3 and its value is assigned to variable.
For example
#include<stdio.h>
int main()
{
int a=5,b=6,big;
big = a>b ? a : b;
printf("%d is big\n", big);
return 0;
}
Output
6 is big
Output:i=5 j=6
Output: i=5 j=9
Sizeof() Operator
The operator sizeof is a unary operator used calculates the size of data types and
variables. The operator returns the size of the variable, data type in bytes. i.e. the sizeof
operator is used to determine the amount of memory space that the variable/data type will take.
The outcome is totally machine-dependent. For example:
#include<stdio.h>
int main()
{
printf("char occupies %d bytes\n",sizeof(char));
printf("int occupies %d bytes\n",sizeof(int));
printf("float occupies %d bytes\n",sizeof(float));
printf("double occupies %d bytes\n",sizeof(double));
printf("long double occupies %d bytes\n",sizeof(long double));
return 0;
}
Output
char occupies 1 bytes
int occupies 2 bytes
float occupies 4 bytes
double occupies 8 bytes
long double occupies 10 byte
1.14 Expressions :
In C programming, an expression is any legal combination of operators and operands
that evaluated to produce a value.Every expression consists of at least one operand and can
have one or more operators. Operands are either variables or values, whereas operators are
symbols that represent particular actions.
In the expression x + 5; x and 5 are operands, and + is an operator.
In C programming, there are mainly two types of expressions are available. They are as
follows:
1. Simple expression
2. Complex expression
Simple expression: In which contains one operator and two operands or constants.
Example: x+y; 3+5; a*b; x-y etc.
Complex expression: In which contains two or more operators and operands or constants.
Example: x+y-z; a+b-c*d; 2+5-3*4; x=6-4+5*2 etc.
1. Operator Precedence
It defines the order in which operators in an expression are evaluated depends on their
relative precedence. Example: Let us see x=2+2*2
st
1 pass- 2+2*2
nd
2 pass- 2+4
rd
3 pass- 6 that is x=6.
2. Associativity
It defines the order in which operators with the same order of precedence are
evaluated. Let us see x=2/2*2
st
1 pass-- 2/2*2
nd
2 pass-- 1*2
rd
3 pass-- 2that is x=2
The below table lists C operators in order of precedence (highest to lowest) and their
associativity indicates in what order operators of equal precedence in an expression are
applied.
Output:
The value of a is 16
The value of a is 14
The value of a is 6
If the both operands are of the same type, promotion is not needed. If they are
not, promotion follows these rules:
The smallest to the largest data types with respect to size are given as follows:
A Sample ‘C’ program that illustares the use implicit type conversion
#include<stdio.h>
int main()
{
int sum, num=17;
char ch='A';
sum=num+ch;
printf("The value of sum=%d\n", sum);
return 0;
}
Output:
The value of sum= 82 i.e. sum=num+ch=>17+65 (ASCII value of ‘A’)
Explicit typecasting: Which is intentionally performed by the programmer for his requirement
in a C program? The explicit type conversion is also known as type casting.We can convert
the values from one type to another explicitly using the cast operator as follows:
Syntax
(data_type) expression;
Where, data_type is any valid C data type, and expression may be constant, variable or
expression.
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.
Let us look at some examples of type casting.
Function Meaning
Trigonometric
asin(x) Arc sin of x.
acos(x) Arc cosine of x
atan(x) Arc tangent of x
atan2(y,x) Arc tangent of y/x
sin(x) sine of x
M.Ramesh , Dept of CSE, IIIT-Nuzivid, RGUKT. Page 35
UNIT-I C Programming
cos(x) cosine of x
tan(x) tangent of x
Hyperbolic
sinh(x) hyperbolic sine of x
cosh(x) hyperbolic cosine of x
tanh(x) hyperbolic tangent of x
Other functions
x
exp(x) e to the power of x (e )
ceil(x) x rounded up to the nearest integer.
floor(x) x rounded down to the nearest integer
fabs(x) absolute value |x|
log(x) Natural logarithm of x, x>0.
log10(x) Base 10 logarithm x, x>0.
fmod(x,y) Remainder of x/y
sqrt(x) square root of x, x>=0.
pow(x,y) x to the power y.
Note:
1 x and y should be declared as double.
2 In trigonometric and hyperbolic functions, x and y are radians.
3 All the functions return a double.
We should include the line:
#include<math.h>
in the beginning of the program
#include <stdio.h>
#include <math.h>
int main()
{
printf("sin 90 = %.0f\n",sin(90));
printf("cos 0= %.0f\n",cos(0));
printf("sqrt(9) = %.0f\n",sqrt(9));
printf("floor(9.56) = %.2f\n",floor(9.56));
printf("ceil(9.56) = %.2f\n",ceil(9.56));
printf("abs(-9) = %.2f\n",fabs(-9));
printf("power(2,3) = %.0f\n",pow(2,3));
printf("Remainder of 9/3 = %.0f\n",fmod(9,3));
return 0;
Output
sin 90 = 1
cos 0= 1
sqrt(9) = 3
floor(9.56) = 9.00
ceil(9.56) = 10.00
abs(-9) = 9.00
power(2,3) = 8
Remainder of 9/3 = 0