[go: up one dir, main page]

0% found this document useful (0 votes)
106 views64 pages

Components of C Program

The document discusses the components of a C program, including its structure, variables, data types, constants, statements, expressions and operators. It provides examples of a simple "Hello World" C program and explains each component such as comments, library inclusion, main function, print statement etc. It also covers C tokens like keywords, identifiers, constants and their rules.

Uploaded by

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

Components of C Program

The document discusses the components of a C program, including its structure, variables, data types, constants, statements, expressions and operators. It provides examples of a simple "Hello World" C program and explains each component such as comments, library inclusion, main function, print statement etc. It also covers C tokens like keywords, identifiers, constants and their rules.

Uploaded by

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

The Components of a C Program

 C program structure
 Program’s Components
 Variables
 Numeric data types
 Constants
 Statements, expressions and operators
 Program instructions are formed using certain symbols and
words according to some rules known as syntax rules or
grammar.

 Every program instruction must confirm precisely to the


syntax rules of the language.

 C has its own vocabulary and grammar.


/* A first program in C */

#include <stdio.h>
void main( )
{
printf(“Hello, World!”) ;
}
 /* A first program in C */ : It is a comment
 #include <stdio.h>:Library of standard

input output functions.


 main( ): Every C program starts execution

with this function.


 { } : Body of the function- enclosed in braces.
 Semicolon (; ) - Statement & terminator.
 (\n ) Escape sequence – newline character.
 printf –

◦ a function from C Standard library stdio.h


◦ prints a char string on the standard output
 Keywords

 Variables

 Constants

 Data Types

 Statements, Expressions and Operators


 The smallest individual units are known as C tokens.

 It may be a single character or a sequence of characters to


form a single item.

 Tokens can be:


◦ – Keywords
◦ – Names (identifiers)
◦ -- Constants
◦ – Punctuation
◦ – Operators
 Also known as reserved words.

 Are defined as a part of the C language.

 They have fixed meaning.

 Can not be used for anything else

 Must be written in lowercase


 Refers to the names of variables, constants, functions.
 Can be of any length, but only the first 31 are significant (too
long is as bad as too short).
 Are case sensitive:
◦ – abc is different from ABC
 Must begin with a letter and the rest can be letters, digits, and
underscores.
 There can be one exception to beginning letter that variable
name can start with underscore( _ ) but it is used by C library.
 Rules for identifiers:

 First character must be an alphabet ( or underscore)


 Must consist of only letters, digits or underscore
 Only first 31 characters are significant
 Cannot use a keyword
 Must not contain white space.
 It refers to fixed values that do not change during the
execution of a program.

Constants

Numeric Character
Constants Constants

Single String
Integer Real
Character Constants
Constants Constants
Constants
 Integer Constants:
 Refers to a sequence of digits
 Spaces, commas and non-digit characters are not permitted.
 There are 3 types of integers: decimal, octal and hexadecimal.
Decimal – (0-9), preceded by – or+ sign eg., 123, -321
Octal- (0-7) with a leading 0 eg., 037, 0435
Hexadecimal- digits preceded by 0x or 0X, also it may include
alphabets A – F or a-f.

 The largest integer value that can be stored is m/c dependent.


 To store large integer constants is possible by appending
qualifiers such as U, L and UL to the constants.
 Real Constants:
 Refers to numbers containing fractional parts.
 These numbers are shown in decimal notation, having a whole
number followed by a decimal point and the fractional part.
 Example: 0.0083, -.75, 435.76

 A real number may also be represented in exponential notation.


mantissa e exponent

 Example: 215.65  2.1565e2


 Single Character Constants:
 One character from a defined character set.
 Enclosed within a pair of single quote marks.
 Examples:
◦ – ‘A’
◦ –‘’
◦ – ‘$’
◦ – ‘4’
 Character constants have integer values known as ASCII
values.
 Hence, it is possible to perform arithmetic operations.
 String Constants:
 Sequence of characters enclosed in double quotes.
 It may be letters, numbers, special characters and blank
spaces.
 Examples:
◦ – “MPSTME”
◦ – “I like ice cream.”
◦ – “123”
◦ – “DHOOM-2”
◦ – “car”
 Note: a character constant (‘X’) is not equivalent to the single
character string constant (“X”).
 Backslash Character Constants:
 Used in output functions
 C language is rich in its data types.
 ANSI C supports three classes of data types:
◦ Primary data types
◦ Derived data types
◦ User-defined data types
 There are 5 primary data types:
◦ Integer (int)
◦ Floating point (float)
◦ Double-precision floating point (double)
◦ Character (char)
◦ void
 Integer Types:
 Integers are whole numbers with a range of values supported
by a particular m/c.
 For a 16-bit machine, the size of the integer value is limited to
the range -32768 to 32767.
 In order to provide some control over the range of numbers, C
has 3 classes of integer storage.

short int
int
long int
 Integer Types:

 All three types are in signed and unsigned forms.


 Signed integers uses one bit for sign and 15 bits for the magnitude
of the number.
 Unsigned integers use all the bits for the magnitude and are positive.
 The default declaration of integer is signed.
 Floating Point Types:
 Real numbers are stored in 32 bits with 6 digits of precision.
 A double data types uses 64 bits giving a precision of 14 digits.
They are known as double precision numbers.
 Long double uses 80 bits

float
double
long double
 Character Types:
 A single character can be defined as a character (char) type data.
 They are stored in 8 bits.
 The qualifier signed and unsigned may be applied explicitly to char.
 Unsigned char: 0 to 255
 signed char: -128 to 127
 Void Types:
 Has no values
 Used to specify the type of functions.
 Void applied to function indicates it does not return any value to the
calling function.
◦ A variable is a data name that may be used to store a data
value.
◦ Variable names correspond to locations in the computer's
memory
◦ Every variable has a name, a type, a size and a value
◦ A variable name can be chosen so as to reflect its nature in the
program.
◦ Examples :
 Distance, average_number, x1  are all valid
 group one, 123, int_type  are invalid
 Before using variables, you must give the compiler some
information about the variable; i.e., you must declare it.
 Declaration does 2 things:
◦ It tells the compiler what the variable name is
◦ It specifies what type of data the variable will hold.
 It must be done before they are used in the program and
before any executable statement.
 Primary type declaration:
 Syntax:
Data_type v1,v2,…,vn;

int sum;
 Example: float area;
 When we declare a variable
◦ Space is set aside in memory to hold a value of the
specified data type
◦ That space is associated with the variable name
◦ That space is associated with a unique address

 Visualization of the declaration :


int sum ;
sum
Address 9000
 Variables may be given initial values, or initialized, when
declared. Examples:

 int length=7; 7 length

 float diameter =5.9;


5.9 diameter

 char initial = ‘A’;


A initial
 Variables may have values assigned to them through the use of
an assignment statement.
 Such a statement uses the assignment operator “=“
 This operator does not denote equality. It assigns the value of
the right-hand side of the statement (the expression) to the
variable on the left-hand side.
 Examples:
◦ diameter = 5.9 ;
◦ area = length * width ;
 Note that only single variables (LValue) may appear on the
left-hand side of the assignment operator.
 C supports rich set of built-in operators.
 An operator tells the computer to perform some mathematical

or logical manipulations.
 C operators can be classified into a number of categories:

Arithmetic
Relational
Logical
Assignment
Increment and decrement
Conditional
Bitwise
Special
Operator Meaning Example
+ Addition x=3+2;
y+z;
x+y+2;
- Subtraction 3−2;
int x=y−z;
y−2−z;
* Multiplication int x=3∗2;
nt x=y∗z;
x∗y∗2;
/ Division float x=3/2; produces x=1
float x=3.0/2 produces x=1.5
int x=3.0/2; produces x=1
% Modulo division int x=3%2; produces x=1
int y=7;int x=y%4; produces 3
int y=7;int x=y%10; produces 7
 If both operands of a division expression are integers, you will get an
integer answer. The fractional portion is thrown away.
 Examples : 17 / 5 = 3
4/3=1
35 / 9 = 3

 Division where at least one operand is a floating point number will


produce a floating point answer.
 Examples : 17.0 / 5 = 3.4
4 / 3.2 = 1.25
35.2 / 9.1 = 3.86813
 What happens? The integer operand is temporarily converted to a
floating point, then the division is performed.
 The expression m % n yields the integer remainder after m is
divided by n.
 Modulus is an integer operation – both operands MUST be
integers.
 Examples : 17 % 5 = 2
6%3=0
9%2=1
5%8=5
 Relational Operators:
 Comparison of 2 quantities can be done with the help of relational
operators.
Operator Meaning Examples
< is less than 3<3; /∗evaluates to 0 ∗/
’A’<’B’/∗evaluates to 1∗/
<= is less than or equal to 3<=3; /∗evaluates to 1 ∗/
3.99<3 /∗evaluates to 0 ∗/
> is greater than 3>2; /∗evaluates to 1 ∗/
2.99>3 /∗evaluates to 0 ∗/
>= Is greater than or equal to 3>=3; /∗evaluates to 1
∗/ 2.99>=3 /∗evaluates to
0 ∗/
== Is equal to 3==3; /∗evaluates to 1
∗/ 2.99==3 /∗evaluates to
0 ∗/
!= Is not equal to 3!=3; /∗evaluates to 0*/
2.99!=3 /∗evaluates to 1 ∗/
 Relational Operators:
 The value of a relational expression is either one or zero.
1- true 0- false
 All of these operators are called binary operators because they take
two expressions as operands.

exp1 relational_operator exp2;


 When arithmetic expressions are used on either side of a
relational operator, expressions are first evaluated and then
the results are compared.
 They are used in decision statements
 Example: -35>=0  false
4.5<= 10  true
 Assignment Operators:
 Used to assign the result of an expression to a variable ‘=‘.
 C has a set of ‘shorthand’ assignment operators of the form

v op=exp; x + = 1;
Equals Equals
to to
v = v op exp; x = x+1;

 Examples:
a+ = 1;  a = a+1;
a- = 1;  a = a-1;
a% = b;  a = a%b;
a* = 2;  a = a*2;
 Logical Operators:
 Sometimes we need to test multiple conditions in order to
make a decision.
 Logical operators are used for combining simple conditions to
make complex conditions.
 It yields either value 1 or 0.

Operator Meaning Examples


&& Logical AND ((9/3)==3) && (2∗3==6); /∗evaluates to 1
(’A’==’a’) && (3==3) /∗evaluates to 0 ∗/

|| Logical OR 2==3 || ’A’==’A’; /∗evaluates to 1 ∗/


2.99>=3 || 0 /∗evaluates to 0 ∗/
! Logical NOT !(3==3); /∗evaluates to 0 ∗/
!(2.99>=3) /∗evaluates to 1 ∗/
 Logical Operators:
 Truth table for && and ||:
Op-1 Op-2 Op-1 && Op-1 || op2
op2
Non-zero Non-zero 1 1
Non-zero 0 0 1
0 Non-zero 0 1
0 0 0 0
 Truth table for !:
Op-1 ! Op-1
1 0
0 1
 Logical Operators:

 Example:
(a>b) && (x==10)
number<0 || number>100
 Increment and Decrement Operators:
 Both the operators add 1 or subtract 1 from the operand.
 Both are unary operators of the form:
++m or m++
--m or m - -
 Consider m=5;y=m++;
◦ The value of y=5 and m=6.

◦ Consider m=5;y=++m;
◦ The value of y and m would be 6
Increment and decrement operators can only be applied to variables,
not to constants or expressions.
 The position of the ++ determines when the value is
incremented.
 If the ++ is after the variable, then the incrementing is done
last (a postincrement).
int amount, count ;
count = 3 ;
amount = 2 * count++ ;
 amount gets the value of 2 * 3, which is 6, and then 1 gets
added to count.
 So, after executing the last line, amount is 6 and count is 4.
 If the ++ is before the variable, then the incrementing is done
first (a preincrement).
int amount, count ;
count = 3 ;
amount = 2 * ++count ;
 1 gets added to count first, then amount gets the value of 2 *
4, which is 8.
 So, after executing the last line, amount is 8 and count is 4.
 Conditional Operator:
 A ternary operator pair “?:” is used to construct conditional expressions.

exp1 ? exp2: exp3;

 Exp1 is evaluated first.


 If it is nonzero (true), then exp2 is evaluated and become the value of the
expression.
 If it is zero (false), then exp3 is evaluated and become the value of the
expression.
 Only one of the expressions (exp2 ,exp3) is evaluated.
 Example: a=10;
b=15;
x=(a>b)? a: b;  if (a>b) is true then x=a
if (a>b) is false then x=b
 Bitwise Operators:
 Used for manipulation of data at bit level.
 Used for testing the bits or shifting them right or left.
 It may not be applied to float or double.
Operato Meaning
r
& bitwise AND
| bitwise OR
^ Bitwise
exclusive OR
<< Shift left
>> Shift right
For example
i = 14; // Bit pattern 1110
j = i >> 1; // here we have the bit pattern shifted by 1 thus we get 111
 Special Operators:
 It includes comma, sizeof, pointer operators (& and *) and member
selection operators.

 Comma ‘,’ : a comma- linked list of expressions are evaluated left to


right and value of right-most expr is the value of the combined expr.
 Example: value = (x=10,y=5,x+y);

 Sizeof operator:
 It returns the no. of bytes the operand occupies.
 The operand may be a variable, a constant or a data type qualifier,
 Ex: m=sizeof(sum);
n=sizeof(long int);
Normally, used to determine the lengths of arrays and structures.
 Precedence of arithmetic operators:
Operator(s) Precedence &Associativity
() Evaluated first. If nested, innermost
first. If on same level, evaluated
left to right.
*/% Evaluated second. If there are
several, evaluated left to right.
+- Evaluated third. If there are several,
evaluated left to right.
= Evaluated last, right to left.
 Relative precedence of relative and logical operators:

Operator(s)
! Highest
> >= < <=
= = !=
&&
|| Lowest
c is printed, then
incremented

c is incremented, then
printed
 An expression is a sequence of operands and operators that
reduces to a single value.
 Arithmetic expressions: It is a combination of variables,
constants and operators.
 Evaluation of expression:
 Expression are evaluated using an assignment statement of the
form:
variable = expression;
 Ex: x = a*b-c;
z = a-b / c+d;
 Rules for evaluation of expression:
 First, parenthesized sub expression from left to right are
evaluated.
 The precedence rule is applied in determining the order of
application of operators in evaluating sub-expressions
 The associativity rule is applied when two or more operators
of the same precedence level appear in the sub-expression.
 Arithmetic expressions are evaluated from left to right using
the rules of precedence.
 When parenthesis are used, the expressions within parenthesis
assume highest priority.
 Program: main()
{
float a,b,c,x,y,z;
a=9;
b=12;
c=3;
x = a - b / 3 + c * 2 - 1;
y = a - b / (3 + c) * (2 - 1);
z = a - (b / (3 + c) * 2 ) – 1;
printf (“x = %f\n”, x);
printf (“ y = %f\n”, y);
printf (“ z = %f\n”, z);
}
Output:
x = 10.000000
y = 7.000000
z = 4.000000
 Implicit type conversion:
◦ automatic conversion
◦ If the operands are of different types, the lower type is converted
to higher type before the operation proceeds.
◦ The final result of an expr is converted to the type of the variable
on the LHS of assignment operator.
◦ However the foll. changes are introduce before the final
assignment
 Float to int causes truncation of the fractional part.
 Double to float causes rounding of digits
 Long int to int causes dropping of excess higher order bits
 Implicit type conversion:

long double
double
float
Conversion unsigned long int
hierarchy long int
unsigned int
int
short char
 Explicit conversion:
Also known as casting of value.
General syntax:
(type-name) expression

where type-name is any standard C data types, expression can be a


constant, variable or an expression.

Examples:
X = (int)7.5 7.5 is converted to int by truncation
A = (int)21.3 / (int)4.5 evaluated as 21/4 resulting in 5
B = (double)sum/n  division is done in floating point
Y = (int) (a+b)  result is converted to int
z = (int) a + b  a is converted to int and then added to b
 C supports a feature known as type definition that allows
users to define an identifier that would represent an existing
data type.
 This user defined data type identifier can then be used to
declare variables.
 General form:
typedef type identifier;
 Where type refers to an existing data type and identifier refers
to the new name given to the data type.
 Ex: typedef int units;
typedef float marks;
units batch1, batch2;
marks name1,name2;
 Advantage: we can create meaningful data type names for
increasing the readability of program.

 Another user defined data type is enumerated data type


 General form: enum identifier {value1,value2,..,valuen};
 Identifier is used to declare variables that can have one of the
values enclosed within the braces known as enumeration
constants.
 After this definition,

enum identifier v1,v2,…,vn;


 The assignments will be:
 V1= value 2;
 V2 = value1;

 Ex: enum day {Monday, Tuesday,…,Sunday};


enum day week_st, week_end;
week_st = Monday;
week_end = Friday;
The enumeration constants are assigned digits starting from 0.
The definition and declaration can be combined as:
enum day {Monday, Tuesday,…,Sunday} week_st, week_end;
 Reasons:
◦ Modifiability
◦ Understandability

 A constant is defined as follows:


#define symbolic_name value of constant

 Ex: #define PI 3.14159


#define MAX 200
 Rules:
◦ Written in capitals
◦ No blank space between ‘#’ and ‘define’
◦ # must be the first character in the line
◦ A blank space between #define and symbolic name and between
symbolic name and constant.
◦ Must not end with a semicolon
◦ Symbolic names are not declared for data types.
◦ #define is a preprocessor directive.
 Declare the variable with a qualifier ‘const’ at the time of
initialization.

 Ex: const int size = 40;

 This tells the compiler that the value of the ‘int’ variable must
not be modified by the program
 A qualifier ‘volatile ’ can be used to tell explicitly that a
variable’s value may be changed at any time.

 Ex: volatile int date;

 When we declare any variable as volatile, the compiler will


examine the value of the variable each time it is encountered
to see whether an external alternation has changed the value.
 C compilers support basic mathematical functions such as cos,
sqrt, log etc.
 It needs to include <math.h> file .

 Some functions:
◦ Sqrt (x)  square root of x
◦ Pow (x,y)  x to the power of y (x y)
◦ Ceil(x)  x rounded up to the nearest integer
◦ Floor(x)  x rounded down to the nearest integer

You might also like