0% found this document useful (0 votes)
13 views193 pages

Unit 1

The document outlines the syllabus for a C programming course, covering the basics of C programming including its history, structure, data types, and various programming constructs such as variables, constants, and functions. It details the basic structure of C programs, the role of comments, header files, and storage classes, along with examples of constants and data types. Additionally, it explains the rules for writing C programs and provides examples of enumeration constants and the C character set.

Uploaded by

thirunavukkarasu
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)
13 views193 pages

Unit 1

The document outlines the syllabus for a C programming course, covering the basics of C programming including its history, structure, data types, and various programming constructs such as variables, constants, and functions. It details the basic structure of C programs, the role of comments, header files, and storage classes, along with examples of constants and data types. Additionally, it explains the rules for writing C programs and provides examples of enumeration constants and the C character set.

Uploaded by

thirunavukkarasu
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/ 193

Thanthai Periyar

Govt Institute of Technology


Department of CSE

I CSE C
SEMESTER II
CS3251 Programming in C

UNIT 1
BASICS OF C PROGRAMMING
SYLLABUS

An overview of C: History of C; Compiler Vs.


Interpreter, Structure of a C Program, Library and
Linking, Compiling a C Program; Basic data types ,
Modifying the basic data types, Variables: Type
qualifiers, Storage class specifiers; Constants:
Enumeration Constants; Keywords; Operators:
Precedence and Associativity; Expressions: Order of
evaluation, Type conversion in expression, Casts;
Input/Output statements; Assignment statements,
Selection statements; Iteration statements; Jump
statements; Expression statements; Pre-processor
directives: Compilation process.
Basic structure of C Programs
Basic Structure of C-Programs
Documentation Section
* In this section we write about the program or the person who created
the program. Such as: - This program was created for what. Who made,
what date was made, what will the program do like - will add or
multiply. In this way, things related to the program are written here.
And it has to be written as Comment line.
Comment line
* The Compiler of C cannot read the line that we make as a comment
line. So that the compiler does not compile that line. Only the person
making the program can see the comment.
* Comment Lines are also of two types.
1. Single line comment - In this, the same line is commented.
Eg // this is single line comment
2. multi line comment - In this, more than one line is commented.
/* this line is a multi
line comment */
Link Section
 This part is used to declare all the header files that will be used
in the program. This leads to the compiler being told to link the
header files to the system libraries.
 A header file is a file with extension .h which contains C
function declarations
Eg :-#include<stdio.h> Because of this, we use functions like
printf (), and scanf ().
#include<conio.h> Because of this, we use functions like
clrscr (), and getch ().

Definition Section
define such symbolic constants that we have to use in the entire
program, here the value once defined is never changed during
the entire program. These symbolic constants are also called
macro.
Eg #define PI=3.14
Global Declaration Section
There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the
global declaration section that is outside of all the functions. This
section also declares all the user-defined functions.
Eg: int b=30;
void add(int r, int k);

Main Function Section


 This statement (main) specifies the starting point of the C program
execution.
 Here, main is a user-defined method which tells the compiler that this
is the starting point of the program execution.
 int is a data type of a value that is going to return to the Operating
System after completing the main method execution.
 If we don't want to return any value, we can use it as void.
int main() {}
Basic Structure of C-Programs
• Main function section
• In each C-program, there should be one function called main().

• All statements in this function should be enclosed within { …}

For example
void main() // In some compiler, “void” is optional
{
Statement 1
….
Statement i
}

• main ( ) function may be with a zero or more list of argument(s).

• The last statement of a main function should be a return statement.


For example
return 0; //Carefully note the syntax
1. Declaration Part
*All Variable, Constant, Array used in the program have
to declare here. Here, for whatever we declare, C
program would create space in memory at the time of
execution. And the Scope of all these Variable,
Constant, Array is only up to the main function.
2. Executable Part
*Here are all the statements of the program by which
we want to get a result in the program, this is the
part from which the interface for the user starts. And
this is why all logic or expression is written. like:-
a+b;
Sub Program Section
*Ifthe program is a multi-function program then 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.
An example
This program takes no input, but outputs the volume of a sphere.

# include< stdio.h>

# define PI
_ 4_BY_ 3 4. 1887902048

double radius= 10;

double volOfSphere ( double r)


{
You should save this program with
return PI_4_BY_ 3 * r * r * r;
} an extension .c, for example
geometry.c
main ()
{
double volume;
volume = volOfSphere(radius);
printf(" Radius= %lf , volume= %lf.\n" , radius, volume);
}
General rules for any C program
*Every executable statement must end with a semicolon
symbol (;).
*Every C program must contain exactly one main method
(Starting point of the program execution).
*All the system-defined words (keywords) must be used in
lowercase letters.
*Keywords can not be used as user-definednames(identifiers).
*For every open brace ({), there must be respective
closing brace (}).
*Every variable must be declared before it is used.
Datatypes
 Floating point numbers are stored in 32 bits with 6
digits of precision. Floating point numbers are defined
in C by the keyword float.
 When the accuracy provided by a float number is not
sufficient, the type double can be used to define the
number.
 Remember that double type represents the same data
type that float represents but with a greater precision.
 To extend the precision further, we may use long
double which uses 80 bits.
There are three standard floating-point types in C:
 float: for numbers with single precision.(6)
 double: for numbers with double precision.(15)
 long double: for numbers with extended precision.(19)
The precision is defined as how many digits that a
number can represent without data loss.
float f = 11.243567; double d = 11676.2435676542;
*
ASCII value
An unsigned char is a (unsigned)byte value (0 to 255). You
may be thinking of "char" in terms of being a "character" but it
is really a numerical value. The regular "char" is signed, so you
have 128 values, and these values map to characters using
ASCII encoding.
*storage classes are used to define things like storage
location (whether RAM or REGISTER), scope, lifetime and
the default value of a variable.
*the memory of variables is allocated either in computer
memory (RAM) or CPU Registers. The allocation of memory
depends on storage classes.
*A storage class defines the scope (visibility) and life-time of
variables and functions within a C Program.
*Storage classes are auto, static, extern, and register.
*A storage class can be omitted in a declaration and a default
storage class is assigned automatically.
*The default storage class of all local variables (variables
declared inside block or function) is auto storage class.
*Auto variables can be only accessed within the block/function
they have been declared and not outside them.
*the variables declared inside a block without any storage class
specification can be considered as automatic storage class.
*These variables are also called as local variables as they get
destroyed after the execution of the block.
*As the variables are created automatically, garbage values are
assigned by the compiler.
*Have the same functionality as that of the auto variables. The only
difference is that the compiler tries to store these variables in the
register of the microprocessor if a free register is available.
*The memory of the register variable is allocated in CPU Register but
not in Computer memory (RAM).
*Register variables to be much faster than variables stored in
memory . But, we cannot obtain the address of a register variable
using pointers.
* As the number of registers inside the CPU is very less we can use
very less number of register variables.
External storage class
*Extern storage class simply tells us that the variable is
defined elsewhere and not within the same block where it is
used.
*Basically, the value is assigned to it in a different block and
this can be overwritten/changed in a different block as well.
*An extern variable is nothing but a global variable initialized
with a legal value.
* Static variables have a property of preserving their value even after they
are out of their scope!
* They are initialized only once and exist till the termination of the
program. By default, they are assigned the value 0 by the compiler.
* No new memory is allocated because they are not re-declared.
* Their scope is local to the function to which they were defined.
* Global static variables can be accessed anywhere in the program.
*The static storage class instructs the compiler to keep a local
variable in existence during the life-time of the program.
*Making local variables static allows them to maintain their
values between function calls.
void test();
void main()
{
test();
test();
test();
}
void test()
{
static int a=2;
a=a+1;
printf("%d\t",a);
}
*A constant is a named memory location which holds only
one value throughout the program execution.
*once a value is assigned to the constant, that value can't
be changed during the program execution.
*Once the value is assigned to the constant, it is fixed
throughout the program.
Constants
• There are two types of constants
Numeric Constant
Numeric Constant can contain digits in It can be
categorized into two types:
 Integer Constant
 Floating point Constant/Real Constant
1. Integer Constant
Integer Constants can contain numbers without decimal
point. They are of three types:
 Decimal
 Octal
 Hexadecimal
Integer Constant
a. Decimal
Decimal Integer Constant can contain digits from 0 to 9. So base of
decimal integer constant is 10.
Examples of valid Decimal Integer Constants
101 490 4467

b. Octal
Octal Integer Constant can contain digits from 0 to 7. Octal numbers
always start with 0 in C.
Examples of valid Octal Integer Constants:
0123 06663
Integer Constant
c.Hexadecimal
Hexadecimal Integer Constant can contain digits from 0 to 9 and
alphabets from A to F. where
A = 10
B = 11
C = 12
D = 13
E = 14
F = 15
Hexadecimal numbers always start with 0X in C.
Examples of valid Hexadecimal Integer Constants:
0X123 0X6663
Integer constants
 An integer constant can be a decimal integer or octal integer
or hexadecimal integer.

 A decimal integer value is specified as direct integer value


whereas octal integer value is prefixed with 'o' and
hexadecimal value is prefixed with 'OX‘.

 An integer constant can also be unsigned type of integer


constant or long type of integer constant.

 Unsigned integer constant value is suffixed with 'u' and long


integer constant value is suffixed with 'l' whereas unsigned
long integer constant value is suffixed with 'ul'.
Integer Constants
• Consists of a sequence of digits, with possibly a plus or a minus sign before it.
• Example: 12345, +596, -137

• Embedded spaces, commas and non-digit characters are not permitted between
digits.

• Maximum and minimum values (for 32-bit representations)


• Maximum: 2147483647
• Minimum: – 2147483648
Floating point/ Real Constant
Floating point constants/Real constants are those constants which
can contain numbers with decimal point.
Floating point constants can be categorized into two types
 Standard Form
 Exponent Form
a. Standard Form
In standard form, Floating point constant can contain a whole
number followed by a decimal point further followed by fractional
part.
Examples of valid Floating Point Constants in standard form:
320.25 -65.50 +3.5 5. .450
Floating point/ Real Constant

b. Exponent Form
 Exponent form of floating point constant is also called scientific
notation.
 In this form, a floating point number is represented in terms of
power of 10.
 The power of 10 is represented by E or e where E represents
exponent.
Example
23000000 can be represented as 2.3e7
Character Constant
Character Constants are those constants which can contain any
symbol which can include alphabets, digits, special symbols as well
as blank spaces. Character constant can be categorized into two
types:
 Single Character Constant
 String Constant
 Escape Sequence

a. Single Character Constant


It can contain an alphabet, digit, special character or space within
the pair of single quotes (’). It should not contain more than one
character in it .
Examples of valid single character constant:
‘A’ ‘1’ ‘#’ ‘:’
Character Constant
b. String Constant
 It is defined as a sequence of one or more characters enclosed in
double quotes (“).
 We can use alphabets, digits, special characters as well as blank
spaces in a string constant.
 String constant is always terminated with a special character known
as null character (‘\0’).
Examples of valid string constant:
“joy” “2012” “$5000” “[email protected]
c. Escape Sequence
Escape sequences start with backward slash \ followed by a character
meant for a particular purpose. Various escape sequences are:
Eg:\n (New Line):
It is used to insert one blank line where it appears.
Single Character Constants
• Contains a single character enclosed within a pair of single quote marks (‘ ’).
Examples :: ‘2’, ‘+’, ‘Z’

• Some special backslash characters


‘\n’ new line
‘\t’ horizontal tab
‘\’’ single quote
‘\”’ double quote
‘\\’ backslash
‘\0’ null
Creating constants in C

 In a c programming language, constants can be created using


two concepts...
 Using the 'const' keyword
const datatype constantName = value ;
Example : const int x = 10 ; or int const x= 10;

 Using '#define' preprocessor


#define CONSTANTNAME value
Example: #define PI 3.14
Enumeration Constant
 An enum is a keyword, it is an user defined data type. All
properties of integer are applied on Enumeration data type so
size of the enumerator data type is 2 byte. It work like the
Integer.
 It is used for creating an user defined data type of integer.
Using enum we can create sequence of integer constant
value.
Syntax
enum tagname {value1, value2, value3,..... };
 enum is a keyword. It is a user defiend data type.
 tagname is our own variable. tagname is any variable name.
 value1, value2, value3,.... are create set of enum values.
It is start with 0 (zero) by default and value is incremented by 1 for
the sequential identifiers in the list. If constant one value is not
initialized then by default sequence will be start from zero and next
to generated value should be previous constant value one.
Program1:
enum week {sun, mon, tue, wed, thu, fri, sat};
void main()
{
int i;
for(i=sun; i<=sat; i++)
{

printf("%d ",i);
}
}
Program2:
enum day {sunday = 1, monday, tuesday = 5,wednesday, thursday = 10, friday,
saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
wednesday, thursday, friday, saturday);
return 0;
}
Language Elements in C
The C-Character Set
• The C language alphabet:
• Uppercase letters ‘A’ to ‘Z’
• Lowercase letters ‘a’ to ‘z’
• Digits ‘0’ to ‘9’
• C special characters:
, < > . _
( ) ; $ :
% [ ] # ?
' & { } "
^ ! * / |
- \ ~ +

• White space character in C


\b blank space \t horizontal tab \v vertical tab \r carriage return
\f form feed \n new line \\ Back slash \’ Single quote
\" Double quote \? Question mark \0 Null \a Alarm (bell)
ASCII Codes of C-Character Set
ASCIISymbol ASCII Symbol ASCIISymbol ASCIISymbol ASCIISymbol ASCIISymbol ASCIISymbol ASCIISymbol
0 NUL 16 DLE 32 (space) 48 64 @ 80 P 96 ` 112
0 p
1 SOH 17 DC1 33 ! 49 65 A 81 Q 97 a 113 q
1
2 STX 18 DC2 34 " 50 66 B 82 R 98 b 114
2 r
3 ETX 19 DC3 35 # 51 67 C 83 S 99 c 115 s
3
4 EOT 20 DC4 36 $ 52 68 D 84 T 100 d 116
4 t
5 ENQ 21 NAK 37 % 53 69 E 85 U 101 e 117 u
5
6 ACK 22 SYN 38 & 54 70 F 86 V 102 f 118 v
6
7 BEL 23 ETB 39 ' 55 71 G 87 W 103 g 119 w
7
8 BS 24 CAN 40 ( 56 72 H 88 X 104 h 120
8 x
9 TAB 25 EM 41 ) 57 73 I J 89 Y 105 i j 121 y
9
10 LF 26 SUB 42 * 58 74 K 90 Z 106 k 122 z
:
11 VT 27 ESC 43 + 59 75 L 91 [ 107 l 123 {
;
12 FF 28 FS 44 , 60 76 M 92 \ 108 m 124 |
<
13 CR 29 GS 45 - 61 77 N 93 ] 109 n 125
= }
14 SO 30 RS 46 . 62 78 O 94 ^ 110 o 126
> ~
15 SI 31 US 47 / 63 79 95 _ 111 127
? •

C language recognizes total 256 ASCII codes; other 128 ASCII codes are for extended
characters’ symbols
Keywords in C
• Keywords
• Keywords are those words whose meaning is already defined by Compiler; also
called “reserved words” and cannot be used in identifier declaration
• There are 32 keywords in C
auto double int struct
break else long switch
case enum register typedef
char extern return union C is a case-sensitive
const float short unsigned programming
continue for signed void language!
default goto sizeof volatile
do if static while
Identifiers in C
Rules for Identifiers in C –
* First character: The first character of the identifier should necessarily begin
with either an alphabet or an underscore. It cannot begin with a digit.
* No special characters: C does not support the use of special characters
while naming an identifier. For instance, special characters like comma or
punctuation marks can’t be used.
* Nokeywords: The use of keywords as identifiers is strictly prohibited, as
they are reserved words which we have already discussed.
* No white space: White spaces include blank spaces, newline, carriage
return, and horizontal tab, which can’t be used.
* Word limit: Theidentifier name can have an arbitrarily long sequence that
should not exceed 31 characters, otherwise, it would be insignificant.
* Case sensitive: Uppercase and lowercase characters are treated differently.
Variables
• It is a data name that can be used to store a data value.
Example: x = 39, here x being a variable presently stored 39 in it

• Unlike constants, a variable may take different values in memory during


execution.

• Variable names follow the naming convention for identifiers.


Examples: temp speed name2 current

int a, b, c;
char x;

a = 3;
b = 50; c = a-b;
x = ‘d’;

b = 20; a = a+1;
x = ‘G’;
Declarations of Variables
• There are two purposes:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.

• General syntax:
data-type variable-list;

• Examples:
int velocity, distance;
int a, b, c, d;
float temp;
char flag, option;
Declarations of Variables
• According to C-language, in an expression
• A variable say x, refers to the contents of the memory location.
• &x refers to the address of the memory location.

• Examples:
scanf (“%f %f”, &x, &y);
printf (“%f %f %f”, x, y, x + y);
Declarations of Variables
Operators in C-Language
Operators in C

Operators

Arithmetic Relational Logical


Operators Operators Operators

Increment Bit-wise
Operators Operators
Arithmetic Operators
x = 13; y = 5;
• Addition: +
• Subtraction: -
• Multiplication: *
• Division: /
• Modulus: %

Example:
distance = rate * time ;
netIncome = income - tax ;
speed = distance / time ;
area = PI * radius * radius;
y = a * x * x + b*x + c;
quotient = dividend / divisor;
remain = dividend % divisor;
int a = 21; int b = 10; int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
Operation Result Example

int/int int 5/2 = 2

int/real real 5/2.0 = 2.5

real/int real 5.0/2 = 2.5

real/real real 5.0/2.0 = 2.5


int main()
{
int a=10,b=4,c;
float d=3,e;
c = a/b;
printf(" \n value a/b is:%d",c);
e = a/d;
printf("\n value a/d is:%f",e);
}
Output :
value a/b is:2

value a/d is:3.333333


The increment operators adds one to the existing value of the operand
and the decrement operator subtracts one from the existing value of
the operand.
Pre-Increment or Pre-Decrement
*In the case of pre-increment/decrement, the value of the
variable is increased/decreased by one before the
expression evaluation.
*when we use pre-increment or pre-decrement, first the
value of the variable is incremented or decremented by one,
then the modified value is used in the expression evaluation.
Post-Increment or Post-Decrement
*In the case of post-increment or post-decrement, the value
of the variable is increased/decreased by one after the
expression evaluation.
* when we use post-increment or post-decrement, first the
expression is evaluated with existing value, then the value
of the variable is incremented or decremented by one.
Program1:
main(){int a=5;
printf(" \n Post increment Value:%d",a++);
printf(" \n Pre increment Value:%d",++a);
printf(" \n Pre decrement Value:%d",--a);
printf(" \n Post decrement Value:%d",a--);
}
Output
Post increment Value:5
Pre increment Value:7
Pre decrement Value:6
Post decrement Value:6
void
main(){int
i = 5,j;
j = ++i; // Pre-Increment
printf("i = %d, j = %d",i,j);
}
i = 6, j = 6
void main()
{
int i = 5,j;
j = i++; // Post-Increment
printf("i = %d, j = %d",i,j);
}
i = 6, j = 5
Bitwise Operators(&, |, ^, ~, >>, <<)
• C provides six operators for bit manipulation
• These operators may be applied to only integral operands, that is, char, short, int,
and long (both signed and unsigned)

x = 5 (0101), y = 12 (1100)
Operator Meaning Usage Example
& Bitwise AND z=x&y z = 0100 (4)
| Bitwise OR z=x|y z = 1101 (13)
^ Bitwise exclusive OR z= x^y z = 1001 (9)
<< Left shift z = x << u z = 0100 (4)
>> Right shift z = x >> u z = 0001(1)
~ One’s complement z = ~x z = 1010 (10)
u is an unsigned integer

See illustrations for left-shift and right-shift operations in the next slide
*Bit wise left shift and right shift : In left shift operation “x
<< 1 “, 1 means that the bits will be left shifted by one
place. If we use it as “x << 2 “, then, it means that the bits
will be left shifted by 2 places.
EXAMPLE
212 = 11010100 (In binary)
212>>2 = 00110101(In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)
x = 00101000
*x << 1 = 01010000 (binary) = 80 (decimal)
*x >> 1 = 00010100 (binary) = 20 (decimal)
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
Relational Operators

Used to compare two quantities.

< is less than


> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
Relational Operators
• Examples:
10 > 20 is false
25 < 35.5 is true
12 > (7 + 5) is false
12 >= (7 + 5) is true

When arithmetic expressions are used on either side of a relational operator, the
arithmetic expressions will be evaluated first and then the results compared.

Example:
a + b > c – d is the same as (a+b) > (c-d)
Relational Operators
• Example:

Sample code segment in C

if (x > y)
printf (“%d is larger\n”, x);
else
printf (“%d is larger\n”, y);
Logical Operators
• logical operators in C (also called logical connectives).
&&---------- Logical AND
|| ------- Logical OR
! -------- Logical NOT
Logical Operators
• Logical AND
• Result is true if both the operands are true.
• Logical OR
• Result is true if at least one of the operands are true.
Assignment in C-Language
It is used to assign a value or expression etc to a variable.
Compound operator
It is also used to assign a value to a variable.
Eg: x + = y means x = x + y
Nested operator
It is used for multiple assignment. Eg: i = j = k = 0;
Statement with simple Statement with
assignment operator shorthand operator
var_name op= expression;

a=a+1 a += 1
a=a–1 a -= 1
a = a * (n+1) a *= (n+1)
a = a / (n+1) a /= (n+1)
a=a%b a %= b
Assignment in C
• Used to assign values to variables, using the assignment operator (=).
• General syntax:
variable_name = expression;
Examples:
velocity = 20;
b = 15; temp = 12.5;
A = A + 10;
v = u + f * t;
s = u * t + 0.5 * f * t * t;

• Assignment during declaration


int speed = 30;
char flag = ‘y’;

• Multiple variable assignment


a = b = c = 5;
flag1 = flag2 = ‘y’;
speed = flow = 20.0;
 It is similar to the if-else statement. The if-else statement takes
more than one line of the statements, but the conditional
operator finishes the same task in a single statement.

 The conditional operator in C is also called the ternary


operator because it operates on three operands.

 The operands may be an expression, constants or variables. It starts


with a condition, hence it is called a conditional operator. It is used
to checks the condition and execute the statement depending on the
condition.

 The conditional operator consists of 2 symbols the question mark (?)


and the colon (:)
 syntax:
exp1 ? exp2 : exp3
a = 10;
b = 15;
x = (a > b) ? a : b
#include<stdio.h>
#include <conio.h>
void main ( )
{
int a=5,b=8,c;
c = a>b?a:b; //Conditional operator
printf(" \n The Larger Value is%d",c);
}

Output: The Larger Value is 8


 comma operator ( , )
 sizeof operator
 pointer operator (& and *)
 member selection operators (. and ->).

The Comma Operator -to link related expressions together.


Eg: int x=5,y=10;
Operator Precedence and Associativity
Operator Associativity Precedence
() Left to Right 1
- (unary)
--, ++ Right to Left 2
!, ~
*, /, % Left to Right 3 Assignment operators
+, - Left to Right 4 namely =, +=, -=, *=
<<, >> Left to Right 5 and %= are of
<, <=, >, >= Left to Right 6 lowest priority and
== , != Left to Right 7 right to left associativity
& Left to Right 8
^ Left to Right 9
| Left to Right 10
&& Left to Right 11
|| Left to Right 12
?: Right to Left 13
 The arithmetic expressions evaluation are carried out based on
the precedence and associativity.
 The evaluation are carried in two phases.
 First Phase: High Priority operators are
evaluated.
 Second Phase: Low Priority operators are
evaluated.
Operator Precedence and Associativity
• Assignment operators namely =, +=, -=, *= and %= are of lowest priority and right to
left associativity
• For operators of the same priority, evaluation is from left to right as they appear.
• Parenthesis may be used to change the precedence of operator evaluation.
Examples:
v = u + f * t;  v = u+(f*t);
X = x * y / z  X = (x*y)/z
A = a + b – c * d / e  A = ((a+b)-((c*d)/e))
A = -b * c + d % e  A = (((-b)*c)+(d%e))
Operator Precedence

• Parenthesis may be used to change the precedence of operator evaluation.

Example:
a + b * c – d / e  a + (b * c) – (d / e)
a * – b + d % e – f  a * (– b) + (d % e) – f
a – b + c + d  (((a – b) + c) + d)
x * y * z  ((x * y) * z)
a + b + c * d * e  (a + b) + ((c * d) * e)
Integer arithmetic

• When the operands in an arithmetic expression are integers, the expression is


called integer expression, and the operation is called integer arithmetic.

• Integer arithmetic always yields integer values.

• Operators applicable
• All arithmetic operators
• All logical operators
• All relational operators
• All increment and decrement operators
• All bit-wise operators
Real Arithmetic

• Arithmetic operations involving only real or floating-point operands.


• Since floating-point values are rounded to the number of significant digits permissible,
the final value is an approximation of the final result.
Examples
1.0 / 3.0 * 3.0 will have the value 0.99999 and not 1.0
a = 22/7*7*7 = (((22/7)*7)*7) = 153.86
b = 22*7/7*7 = (((22*7)/7)*7) = 154

• The modulus operator cannot be used with real operands.


Mixed-mode Arithmetic

• When one of the operands is integer and the other is real, the expression is called a
mixed-mode arithmetic expression.

• If either operand is of the real type, then only real arithmetic is performed, and the
result is a real number.
25 / 10  2
25 / 10.0  2.5

• Some more issues will be considered later.


Automatic Type Conversion
• C language permits mixing of constants and variables of different types in an
expression
• During evaluation it adheres to very strict rules of type conversion
• If operands are of different types, the lower type is automatically converted to the
higher type before the operation proceeds
LOWER int < long < float < double HIGHER
• char and short are automatically converted to int.
• If one operand is unsigned, then other is converted to unsigned and the
result is in unsigned
• float is automatically converted to double
• If one operand is double, then other is converted to double and the result
is in double
• If one operand is long, then the other operand is converted to long
Automatic Type Conversion
int a = 10, b = 4, c;
float x, y;
double z;
c = a / b; float to int causes truncation of the fractional part
x = a / b; double to float causes rounding of digits
long int to int causes dropping of the excess higher order bits
y = a / 3.0
z = 2 / 1.0;

The value of c will be 2


The value of x will be 2.0
The value of y will be 3.333333333
The value of z will be 2.00000000000000 (and in double precision)
Automatic Type Conversion
int i, x;
float f;
double d;
long int l;

x = l / i + i * f - d

long double

double

int double
Type Casting
• C language allows to force a type conversion, which is different than the
automatic type conversion
• The syntax for such a type casting is
(type_name) expression;

Example
int a = 4, b = 5; float x; double y;
x = (float) a / b; // division is done in floating point mode, x = 0.8
a = (int) x / b; // Result is converted to integer by truncation, a = 0
y = (char) b / a; // It may report wrong type conversion
The Standard Input Output File
*Character Input / Output
*getchar, getc
*putchar, putc
*Formatted Input / Output
*printf
*scanf
*Whole Lines of Input and Output
*gets
*puts
 C uses two functions for formatted input and output.

 Formatted input : reads formatted data from the


keyboard.

 Formatted output : writes formatted data to the


monitor.
Formatted Input and Output
*
*Formatted reading of data from the keyboard.
*Arguments-control string, followed by the list of items to be
read.
*Wants to know the address of the items to be read, the
names of variables are preceded by & sign.
*Character strings are an exception to this.
Example:
int a,b;
scan f(“%d%d”, &a, &b);
*It reads a whole line of input into a string until a new line or
EOF is encountered.
*It is critical to ensure that the string is large enough to hold
any expected input lines.
#include <stdio.h>
main()
{
char ch[20];
gets(x);
puts(x);
}
*It writes a string to the output, and follows it with a new line
character.
*putchar, printf and puts can be freely used together

#include <stdio.h>
main()
{
char line[256]; /* large to store a line of input */
while(gets(line) != NULL) /* Read line */
{
puts(line); /* Print line */
printf("\n"); /* Print blank line */
}
}
◾ Expresses some action to be carried out
◾ Program is a sequence of one or
more statements.
void main()
{
int a;
a=10;
printf(“%d”,a);
}
◾ Decision making (Branching) Statement is used
to specify the order in which statements are to
be executed.
◾ The statements are
 If
 If…else
 Nested if
 If….else if….else
 Switch…case
if ( condition)
statement;

Or

if (condition)
{
Statements;
}
if ( a>b)
c=a;

Or
if (a>b)
{
c=a;
printf(“a is big”);
}
int main() Output:
{ Please Enter Ur Pin
int pin; 1234
printf(“Please Enter ur Pin”); Proceed
scanf(“%d”,&pin); Home
if(pin==1234) Test Case2:
printf(“Proceed”); Please Enter Ur Pin
printf(“Home”); 11111
Home
}
Case:
• Ask a user to enter a number
• If it is negative, then display “Wrong”
• Other wise display “Correct”
int main()
{ Test Case1:
Enter any Num
int num;
-45
printf(“Enter any Num”); Wrong
scanf(“%d”, &num );
if( num<0)
printf(“Wrong”); Test Case2:
else Enter any Num
123
printf(“Correct”); Correct
}
Nested IF
if ( condition) Case:
statement 1; • Ask a user to enter his
else if(condition) age
statement 2; • If it is more than 50, then
else “OLD”
statement 3; • If it is more than 35 ,
then “MIDDLE”
• Otherwise, “YOUNG”
int main()
{ Test Case1:
Enter Ur Age
int age; 45
printf(“Enter Ur Age”); MIDDLE
scanf(“ %d ”, &age ); Test Case2:
if( age >= 50 ) Enter Ur Age
printf (“OLD”); 12
YOUNG
else if(age >= 35 && age<50 )
printf (“MIDDLE”); Test Case3:
Enter Ur Age
else 66
printf (“YOUNG”); OLD
}
switch ( expr)
{ Note:
case constant: • expr value :
stmt; integer / char
break;
• case constant must be
case constant:
stmt; • Int
break; • char
default: case 1:
stmt; case ‘a’:
}
int main()
Test Case1:
{
Enter the choice
int choice; 2
printf(“Enter the choice”); Monday
switch( choice )
{ Test Case2:
Enter the choice
case 1: 9
printf(“Monday”); Pls enter between 1 to 7
break;
Test Case3:
default: Enter the choice
printf(“Pls enter between 1 to 7); 7
} saturday
}
◾ Iteration Statement is used to execute set of
statements repeatedly until condition holds
true
◾ Types
 for
 while
 do … while
for ( initialization ; condition; increment/decrement)
statement;

Control Variable is used to control the no. of repetitions


Initialize the control variable i=1
Condition i<=10
Increment or decrement the control variable i++

Case:
• Print Values from 1 to 50
int main()
{ Numbers from 1 to 50
1
int i; 2
printf(“Numbers from 1 to 50”); 3
.
for( i=1;i<=50;i++) .
{ .
printf (“%d”,i); .

} 50
printf(“Over”); Over
}
Initialization;
while( condition)
{
statements;
Increment/decrement;
}
How while loop works?
•The while loop evaluates the test expression inside the
parenthesis ().
•If the test expression is true, statements inside the body
of while loop are executed. Then, the test expression is
evaluated again.
•The process goes on until the test expression is evaluated to
false.
•If the test expression is false, the loop terminates (ends).
•The do..while loop is similar to the while loop with one
important difference.
•The body of do...while loop is executed at least once. Only
then, the test expression is evaluated.
How do...while loop works?
•The body of do...while loop is executed once. Only then,
the test expression is evaluated.
•If the test expression is true, the body of the loop is
executed again and the test expression is evaluated.
•This process goes on until the test expression becomesfalse.
•If the test expression is false, the loop ends.
Example: (while) Example: (for)
int x = 2; int x;
while(x < 100) for(x=2;x<100;x*=2)
{ printf("%d\n", x);
printf("%d\n", x);
x = x * 2;
}

Example: (do-while)
do{
printf("Enter 1 for yes, 0 for no :");
scanf("%d", &input_value);
} while (input_value == 1);
Output
#include<stdio.h>
#include<conio.h>
Enter the Number:3
void main() The value of 3! is: 6
{
int i=1,fact=1,n;
printf("\nEnter the Number:"); for(i=1;i<=n;i++)
scanf("%d",&n); {
while(i<=n) fact =fact *i;
{
fact =fact *i; }
i++; // i=i+1
}
printf("\n The value of %d! is:%d",n,fact);
getch();
}
unconditional control statements/Jump Statements

In c, there are control statements that do not need any


condition to control the program execution flow. These
control statements are called as unconditional control
statements. C programming language provides the following
unconditional control statements...
 break
 continue
 goto
The above three statements do not need any condition to
control the program execution flow.
break statement

In C, the break statement is used to perform the


following two things...
 break statement is used to terminate the switch
case statement
 break statement is also used to terminate looping
statements like while, do-while and for.
When a break statement is encountered inside the
switch case statement, the execution control moves
out of the switch statement directly.
◾ terminates the loop (for, while and do...while
loop) immediately when it is encountered.
The break statement is used with decision
making statement such as if...else,switch.
Initialization;
while( condition) if(condition)
{
statements; break;
break;
Increment/decrement;
}
int main()
{ Numbers from 1 to 5
1
int i; 2
printf(“Numbers from 1 to 5”); Over
for( i=1;I<=5;i++)
{
if(i==3)
break;
printf (“%d”,i);
}
printf(“Over”);
}
 The continue statement is used to move the program execution
control to the beginning of the looping statement.
 When the continue statement is encountered in a looping statement,
the execution control skips the rest of the statements in the looping
block and directly jumps to the beginning of the loop.
 The continue statement can be used with looping statements like
while, do-while and for.
 When we use continue statement with while and do-
while statements the execution control directly jumps to the
condition.
 When we use continue statement with for statement the execution
control directly jumps to the modification portion
(increment/decrement/any modification) of the for loop.
◾ is a jump statement-can be used only inside
for loop, while loop and do-while loop.
int main()
{ Numbers from 1 to 5
1
int i; 2
printf(“Numbers from 1 to 5”); 4
5
for( i=1;i<=5;i++) Over
{
if(i==3)
continue;
printf (“%d”,i);
}
printf(“Over”);
}
 The goto statement is used to jump from one line to
another line in the program.
 Using goto statement we can jump from top to
bottom or bottom to top.
 To jump from one line to another line, the goto
statement requires a label.
 Label is a name given to the instruction or line in
the program.
 When we use a goto statement in the program, the
execution control directly jumps to the line with the
specified label.
Syntax
Syntax
goto label;
label:
... .. ... ... .. ...
label:
statement;
... .. ... ... ..
statement; ...
goto label;

-used to alter the normal sequence of a C program.


-The label is an identifier.
-When goto statement is encountered, control of
the program jumps to label: and starts executing
the code.
int main()
{ Numbers from 1 to 5
int i; 1
2
printf(“Numbers from 1 to 5”); End
for( i=1;I<=5;i++)
{
if(i==3)
goto A;
printf (“%d”,i);
}
printf(“Over”);
A: printf(“End”);
}
RETURN
◾ used to return the program control from called
function to a calling function
#include <stdio.h>
int main()
{
int anga, angb, angc, sum;
/* Three angles are given as input */
/* Calculate the sum of all angles */
/* Check whether sum=180 then its a valid triangle
otherwise not */
}
A macro is a segment of code which is replaced by the value of
macro. Macro is defined by #define directive. There are two
types of macros:
Object-like Macros
Function-like Macros
1. Object-like Macros
The object-like macro is an identifier that is replaced by value.
It is widely used to represent numeric constants. For example:
#define PI 3.1415
2. Function-like Macros
The function-like macro looks like function call. For example:
#define MIN(a,b) ((a)<(b)?(a):(b))
*you are including either Library header files or
User defined files
The conditional directives check for EXISTENCE of a MACRO and
compiles code accordingly

#IFNDEF is the reverse of #IFDEF. IFNDEF works if the MACRO


does not exist.
#undef is a special preprocessor directive in C language to
Nullify or Remove Definition of existing Macros.
Predefined
Value
macro
String containing the current
DATE
date
FILE String containing the file name
Integer representing the
LINE
current line number
If follows ANSI standard C, then
STDC
* value is a nonzero integer
String containing the current
TIME
date.
#include <stdio.h>
void main()
{
printf("Current time: %s", TIME );
}

O/P:
Current time: 19:54:39
Compilation process
 The compilation is a process of converting the source code
into object code. It is done with the help of the compiler.
 The compiler checks the source code for the syntactical or
structural errors, and if the source code is error-free, then it
generates the object code
Compilation process
 The c compilation process converts the source code taken
as input into the object code or machine code.
 The compilation process can be divided into four steps,
i.e., Pre-processing, Compiling, Assembling, and Linking.
 The preprocessor takes the source code as an input, and it
removes all the comments from the source code.
 The preprocessor takes the preprocessor directive and
interprets it.
 For example, if <stdio.h>, the directive is available in the
program, then the preprocessor interprets the directive and
replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our
program passes before being transformed into an
executable form:
 Preprocessor
 Compiler
 Assembler
 Linker
Preprocessor
The source code is the code which is written in a text editor and the source code
file is given an extension ".c". This source code is first passed to the
preprocessor, and then the preprocessor expands this code. After expanding the
code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The
compiler converts this code into assembly code. Or we can say that the C
compiler converts the pre-processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The
name of the object file generated by the assembler is the same as the source file.
The extension of the object file in DOS is '.obj,' and in UNIX, the extension is'o'. If
the name of the source file is 'hello.c', then the name of the object file would
be 'hello.obj'.
Linker
linker is to link the object code of our program with the object code of the
library files and other files. The output of the linker is the executable file. The
name of the executable file is the same as the source file but differs only in their
extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the
executable file can be named as 'a.out'.
*First,the input file, i.e., hello.c, is passed to the preprocessor,
and the preprocessor converts the source code into expanded
source code. The extension of the expanded source code would
be hello.i.
*The expanded source code is passed to the compiler, and the
compiler converts this expanded source code into assembly code.
The extension of the assembly code would be hello.s.
*This assembly code is then sent to the assembler, which converts
the assembly code into object code.
*After the creation of an object code, the linker creates the
executable file. The loader will then load the executable file for
the execution.

You might also like