Basics of “C”
Objectives
Understand the basic structure of a program in C.
Learn the commands used in UNIX/LINUX and MS-DOS for
compiling and running a program in C.
Obtain a preliminary idea of the keywords in C.
Learn the data types, variables, constants, operators, and
expressions in C.
Understand and grasp the precedence and associativity
rules of operators in C.
Get acquainted with the rules of type conversions in C.
Key Words
ASCII : It is a standard code for representing characters as
numbers that is used on most microcomputers, computer
terminals, and printers. In addition to printable characters,
the ASCII code includes control characters to indicate
carriage return, backspace, etc.
Assembler :The assembler creates the object code.
Associativity :The associativity of operators determines
the order in which operators of equal precedence are
evaluated when they occur in the same expression. Most
operators have a left-to-right associativity, but some have
right-to-left associativity.
Key Words
Compiler: A system software that translates the source code to
assembly code.
Constant :A constant is an entity that doesn’t change.
Data type: The type, or data type, of a variable determines a set of
values that the variable might take and a set of operations that can be
applied to those values.
Debugger: A debugger is a program that enables you to run another
program step-by-step and examine the value of that program’s variables.
Identifier: An identifier is a symbolic name used in a program and
defined by the programmer. Ex : name of variables, arrays, functions etc
like emp_name, total_amount
Key Words
IDE :An Integrated Development Environment or IDE is an
editor which offers a complete environment for writing,
developing, modifying, deploying, testing, and debugging
the programs.
Identifier: An identifier or name is a sequence of
characters invented by the programmer to identify or name
a specific object.
Keyword: Keywords are explicitly reserved words that
have a strict meaning as individual tokens to the compiler.
They cannot be redefined or used in other contexts.
Key Words
Linker: If a source file references library functions or
functions defined in other source files, the linker combines
these functions to create an executable file.
Precedence :The precedence of operators determines
the order in which different operators are evaluated when
they occur in the same expression. Operators of higher
precedence are applied before operators of lower
precedence.
Pre processor :The C pre processor is used to modify the
source program before compilation according to the pre
processor directives specified.
Key Words
L-value: An l-value is an expression to which a value can
be assigned.
R-value :An r-value can be defined as an expression that
can be assigned to an l-value.
Token: A token is one or more symbols understood by the
compiler that help it interpret your code.
Word :A word is the natural unit of memory for a given
computer design. The word size is the computer’s preferred
size for moving units of information around; technically it’s
the width of the processor’s registers.
© Oxford University Press 2013. All rights reserved.
Key Words
Whitespace Space, newline, tab character and
comment are collectively known as whitespace.
Variable: A variable is a named memory location. Every
variable has a type, which defines the possible values that
the variable can take, and an identifier, which is the name
by which the variable is referred.
Bug:Any type of error in a program is known as bug. There
are three types of errors that may occur:
Compile errors,
Linking errors,
Runtime errors
© Oxford University Press 2013. All rights reserved.
Why Learn “C” ?
There are a large number of programming languages in
the world today even so, there are several reasons to
learn C, some of which are stated as follows:
a . C is quick.
b . C is a core language : In computing, C is a general
purpose, cross-platform, block structured procedural,
imperative computer programming language.
c . C is a small language: C has only thirty-two
keywords. This makes it relatively easy to learn
compared to bulkier languages.
d . C is portable.
© Oxford University Press 2013. All rights reserved.
Developing Programs in “C”
There are mainly three steps:
1. Writing the C program
2. Compiling the program and
3. Executing it.
For these steps, some software components are required,
namely an operating system, a text editor(integrated
development environment), the C compiler, assembler, and
linker.
C uses a semicolon as a statement terminator; the
semicolon is required as a signal to the compiler to indicate
that a statement is complete.
All program instructions, which are also called statements,
have to be written in lower case characters.
© Oxford University Press 2013. All rights reserved.
Developing Programs in “C”
© Oxford University Press 2013. All rights reserved.
Illustrated Version of a Program
© Oxford University Press 2013. All rights reserved.
Backslash Code
© Oxford University Press 2013. All rights reserved.
Parts of C Program
Header File
The header files, usually incorporate data types, function
declarations and macros, resolves this issue. The file with .h
extension is called header file, because it’s usually included
at the head of a program.
Every C compiler that conforms to the international
standard (ISO/IEC 9899) for the language will have a set of
standard header files supplied with it.
The header files primarily contain declarations relating to
standard library functions and macros that are available
with C.
© Oxford University Press 2013. All rights reserved.
Standard Header Files
During compilation, the compilers perform type checking to
ensure that the calls to the library and other user-defined
functions are correct. This form of checking helps to ensure
the semantic correctness of the program.
© Oxford University Press 2013. All rights reserved.
Philosophy : main()
main() is a user defined function. main() is the first function
in the program which gets called when the program executes.
The start up code c calls main() function. We can’t change
the name of the main() function.
main() is must.
According to ANSI/ISO/IEC 9899:1990 International Standard
for C, the function called at program start up is named main.
The implementation declares no prototype for this function. It
can be defined with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv) :
int main(int argc, char *argv[ ]) { /* ... */ }
© Oxford University Press 2013. All rights reserved.
Structure : C Program
© Oxford University Press 2013. All rights reserved.
Declaration & Definition
Declaration means describing the type of a data object to the
compiler but not allocating any space for it.
A declaration announces the properties of a data object or a function. If
a variable or function is declared and then later make reference to it
with data objects that do not match the types in the declaration, the
compiler will complain.
data_type variable_name_1,
Definition means declaration of a data object and also allocating
space to hold the data object.
A definition, on the other hand, actually sets aside storage
space (in the case of a data object) or indicates the sequence of
statements to be carried out (in the case of a function).
© Oxford University Press 2013. All rights reserved.
Variables : Attributes
All variables have three important
attributes:
A data type that is established when the variable is
defined, e.g., integer, real, character. Once defined , the
type of a C variable cannot be changed.
A name of the variable.
A value that can be changed by assigning a new value
to the variable. The kind of values a variable can assume
depends on its type. For example, an integer variable
can only take integer values, e.g., 2, 100, –12.
© Oxford University Press 2013. All rights reserved.
Classification : Data Types
© Oxford University Press 2013. All rights reserved.
Basic Data Types : Size & Range
16 bit computer:
32 bit computer:
© Oxford University Press 2013. All rights reserved.
printf function
The printf function (the name comes from “print formatted”) prints a string on
the screen using a “format string” that includes the instructions to mix several
strings and produce the final string to be printed on the screen.
printf("The value is %d\n", counter);
printing number
printing float and double
print characters
scanf function
In the C programming language, scanf is a
function that reads formatted data from
stdin (i.e, the standard input stream,
which is usually the keyboard, unless
redirected) and then writes the results into
the arguments given.
It uses the & (address operator) to
store the user entered value into the
declared variable.
scanf
Here, we have used %d format specifier inside the scanf() function to take int
input from the user. When the user enters an integer, it is stored in the
testInteger variable.
Take two numbers
format specifier
Specifiers or Modifiers
In addition, C has four type specifiers or modifiers
and three type qualifiers.
Each of these type modifiers can be applied to
the base type int.
The modifiers signed and unsigned can also be
applied to the base type char.
In addition, long can be applied to double.
When the base type is omitted from a
declaration, int is assumed.
The type void does not have these modifiers.
© Oxford University Press 2013. All rights reserved.
Specifiers : Data Types
The specifiers and qualifiers for the data types can be
broadly classified into three types:
Size specifiers— short and long
Sign specifiers— signed and unsigned
Type qualifiers— const, volatile and restrict
© Oxford University Press 2013. All rights reserved.
Specifiers : Data Types
© Oxford University Press 2013. All rights reserved.
Qualifiers
Modifies the properties of a variable
Controls the way variables may be accessed or modified.
Const – read only variable, will never change by the
program
Const float pi = 3.14
Volatile –unexpectedly change by events outside the
program (directly linked with component)
if global variable’s address is passed to clock routine of
the operating system to store the system time, the value
in this address keep on changing without any assignment
by the program. These variables are named as volatile
variable.
© Oxford University Press 2013. All rights reserved.
2. WAP to perform the addition of
two integers & display the result.
Q1. Declare some int
Program Code variable and store
#include<stdio.h> different values and
int main() display them
{ a = 20, b = ‘A’, c =
2.09
int a, b, c;
printf("\nEnter two numbers to add Q2. Input 2 Integer
:"); values and display
scanf("%d%d",&a,&b); the addition
c = a + b;
Q3.Write programs
printf("\nThe addition of %d and Input 2 int values
%d is %d", a,b,c); and display the
return 0; addition(+),
} subtraction(-),
multiplication(*)
division(/) and
modular division(%)
1. Program 1 - WAP to calculate area and the perimiter of a circle.
2. Program 2 - Calculate the area of a rectangle (take two values
as input = lenth, Width)
Program Statements
A statement is a syntactic constructions that performs
an action when a program is executed. All C program
statements are terminated with a semi-colon (;).
© Oxford University Press 2013. All rights reserved.
Program Statements
Declaration :It is a program statement that serves to
communicate to the language translator information about
the name and type of the data objects needed during
program execution.
int a;
int b;
int c;
Or int a,b,c;
This line informs the C compiler that it needs to allocate
space for 5 integers
Expression statement: It is the simplest kind of statement
which is no more than an expression followed by a semicolon.
An expression is a sequence of operators and operands that
specifies computation of a value . Example :x = 4
Program Statements
Compound statement is a sequence of statements
that may be treated as a single statement in the
construction of larger statements.
A compound statement (also called a "block") typically
appears as the body of another statement, such as the if
statement
if ( i > 0 )
{
line[i] = x;
x++;
i--;
}
Program Statements
Labelled statements can be used to mark
any statement so that control may be
transferred to the statement by switch statement
goto label;
.. .
label: statement;
Program Statements
Control statement is a statement whose execution
results in a choice being made as to which of two or
more paths should be followed. In other words, the
control statements determine the ‘flow of control’ in a
program.
Selection statements allow a program to select a
particular execution path from a set of one or more alternatives.
Various forms of the if..else statement belong to this category.
Iteration statements are used to execute a group of one or
more statements repeatedly. “while, for, and do..while”
statements falls under this group.
Jump statements cause an unconditional jump to some
other place in the program. Goto statement falls in this group
© Oxford University Press 2013. All rights reserved.
Program Statements(control)
if (expression) while ( expression )
{ {
Block of statements; Single statement
or
}
Block of statements;
else if(expression)
}
{
Block of statements; for( expr1; expr2; expr3)
} {
else Single statement
{ or Block of statements;
Block of statements; }
}
© Oxford University Press 2013. All rights reserved.
Program Statements(control)
do
{
Single statement
or Block of statements;
}while(expression);
© Oxford University Press 2013. All rights reserved.
Key Words
Compiler vendors (like Microsoft, Borland ,etc.) provide
their own keywords apart from the ones mentioned below.
These include extended keywords like near, far, asm,
etc.
© Oxford University Press 2013. All rights reserved.
Constants
A constant is an explicit data value written by the
programmer. Thus, it is a value known to the compiler at
compiling time.
In ANSI C, a decimal integer constant is treated as an
unsigned long if its magnitude exceeds that of the signed
long. An octal or hexadecimal integer that exceeds the
limit of int is taken to be unsigned; if it exceeds this limit, it
is taken to be long; and if it exceeds this limit, it is treated
as an unsigned long.
An integer constant is regarded as unsigned if its value is
followed by the letter ‘u’ or ‘U’, e.g.,0x9999u;
© Oxford University Press 2013. All rights reserved.
Specifications of Different
Constants
© Oxford University Press 2013. All rights reserved.
Types of C Constant
KIIT UNIVERSITY
Rules for Constructing Const
Constructing Integer
Const Ex.: 426
Must have at least one digit. +782
Must not have a decimal point. -8000
Can be either positive or negative -7605
If no sign precedes an integer constant it is assumed to be positive.
No commas or blanks are allowed
Constructing Real Const in
fractional
Real form
constants are often called Floating Point constants. The real constants could be
written in two forms—Fractional form and Exponential form. Following rules must be
observed while constructing real constants expressed in fractional form:
Must have at least one digit. Ex.: +325.34
Must have a decimal point. 426.0
Could be either positive or negative. -32.76
Default sign is positive. -48.5792
KIIT UNIVERSITY
No commas or blanks are allowed.
Rules for Constructing Const
Constructing Real Const in exponential
form
The exponential form of representation of real constants is usually used if the value of
the constant is either too small or too large. It however doesn’t restrict us in any way
from using exponential form of representation for other real constants.
In exponential form of representation, the real constant is represented in two parts. The
part appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called
exponent.
Following rules must be observed while constructing real constants expressed in
exponential form:
The mantissa part and the exponential part should be separated by a letter e.
The mantissa part may have a positive or negative sign. Ex.: +3.2e-5
Default sign of mantissa part is positive. 4.1e8
The exponent must have at least one digit, which must be a positive -0.2e+3
KIIT UNIVERSITY
or negative integer. Default sign is positive. -3.2e-5
Rules for Constructing Const
Constructing Character
Const
Is a single alphabet, a single digit or a single special symbol enclosed within single
inverted commas. Both the inverted commas should point to the left. For example, ’A’
is a valid character constant whereas ‘A’ is not.
The maximum length can be 1 character.
Ex.: 'A' Note : 3.2e^-5 = 3.2(10)^-5
'I' 3.14159 /* Legal */
'5' 314159E-5L /* Legal */
'=' 510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent
*/ .e55 /* Illegal: missing integer or
fraction */
KIIT UNIVERSITY
Constant example
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '\?'; /*special char cnst*/
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
© Oxford University Press 2013. All rights reserved.
Classification : Operations in C
© Oxford University Press 2013. All rights reserved.
Different Operators
© Oxford University Press 2013. All rights reserved.
A) Arithmetic Operators
There are three types of arithmetic operators in
C:binary,unary, and ternary.
A-1) Binary operators: C provides five basic
arithmetic binary operators.
The mod operator (%) will carry the sign of the
numerator
© Oxford University Press 2013. All rights reserved.
integer division
type casting
mod operator - check sign
Program 1 : Addition of two float numbers,
taking from user input.
Program 2 : Division of two integers
Program 3 : Division of two floats
Program 4 : Modulus function
A-2) Unary Operators
Unary operators: The unary operators operate on a
single operand and following are the examples of Unary
operators:.
Unary increment and decrement operators ‘++’ and
‘--’ operators increment or decrement the value in a
variable by 1.
Basic rules for using ++ and – – operators:
The operand must be a variable but not a constant or an expression.
The operator ++ and -- may precede or succeed the operand.
© Oxford University Press 2013. All rights reserved.
Postfix
Postfix:
(a) x = a++;
First action: store value of a in memory location for variable x.
Second action: increment value of a by 1 and store result in memory
location for variable a.
(b) y = b––;
First action: put value of b in memory location for variable y.
Second action: decrement value of b by 1 and put
result in memory location for variable b.
© Oxford University Press 2013. All rights reserved.
Prefix
Prefix :
• (a) x = ++a;
First action: increment value of a by 1 and store result in
memory location for variable a.
Second action: store value of a in memory location for variable
x.
• (b) y = ––b;
First action: decrement value of b by 1 and put result in
memory location for variable b.
Second action: put value of b in memory location for variable y.
© Oxford University Press 2013. All rights reserved.
prefix and post fix
B) Relational Operators
C provides six relational operators for comparing numeric
quantities. Relational operators evaluate to 1, representing
the true outcome, or 0, representing the false outcome.
© Oxford University Press 2013. All rights reserved.
C) Logical Operators
C provides three logical operators for forming logical
expressions. Like the relational operators, logical operators
evaluate to 1 or 0.
Logical negation is a unary operator that negates the logical value
of its single operand. If its operand is non-zero, it produces 0, and
if it is 0, it produces 1.
Logical AND produces 0 if one or both its operands evaluate to 0.
Otherwise, it produces 1 (both true in this case of 1).
Logical OR produces 0 if both its operands evaluate to 0.
Otherwise , it produces 1 (if any one is true).
© Oxford University Press 2013. All rights reserved.
Bitwise Operators
C provides six bitwise operators for manipulating the
individual bits in an integer quantity . Bitwise operators
expect their operands to be integer quantities and treat
them as bit sequences.
Bitwise negation is a unary operator that complements the bits
in its operands.
Bitwise AND compares the corresponding bits of its operands
and produces a 1 when both bits are 1, and 0 otherwise.
Bitwise OR compares the corresponding bits of its operands
and produces a 0 when both bits are 0, and 1 otherwise.
Bitwise exclusive or compares the corresponding bits of its
operands and produces a 0 when both bits are 1 or both bits are
0, and 1 otherwise.
© Oxford University Press 2013. All rights reserved.
A = 0011 1100 (60)
Bitwise Operators B = 0000 1101 (13)
OP Description Example
Binary AND Operator copies a bit to the result (A & B) = 12,
&
if it exists in both operands. i.e., 0000 1100
Binary OR Operator copies a bit if it exists in (A | B) = 61, i.e.,
|
either operand. 0011 1101
Binary XOR Operator copies the bit if it is set (A ^ B) = 49,
^
in one operand but not both. i.e., 0011 0001
Binary Ones Complement Operator is unary (~A )
~
and has the effect of 'flipping' bits. 1100 0011
Binary Left Shift Operator. The left operands
A << 2
<< value is moved left by the number of bits
1111 0000
specified by the right operand.
Binary Right Shift Operator. The left operands
A >> 2
>> value is moved right by the number of bits
0000 1111
specified by the right operand.
© Oxford University Press 2013. All rights reserved.
Bitwise Operators
© Oxford University Press 2013. All rights reserved.
D) Assignment Operators
Oper
Description Example
ator
C=A+B
Simple assignment operator. Assigns values from right will assign
=
side operands to left side operand. the value of
A + B to C
Add AND assignment operator. It adds the right operand C += A is
+= to the left operand and assign the result to the left equivalent to
operand. C=C+A
Subtract AND assignment operator. It subtracts the right C −= A is
−= operand from the left operand and assigns the result to equivalent to
the left operand. C=C−A
Multiply AND assignment operator. It multiplies the right C *= A is
*= operand with the left operand and assigns the result to equivalent to
the left operand. C=C*A
Divide AND assignment operator. It divides the left C /= A is
/= operand with the right operand and assigns the result to equivalent to
the
© Oxford left operand.
University Press 2013. All rights reserved. C=C/A
Assignment Operators
Oper
Description Example
ator
Modulus AND assignment operator. It
C %= A is equivalent
%= takes modulus using two operands and
to C = C % A
assigns the result to the left operand.
C <<= 2 is same as
<<= Left shift AND assignment operator.
C = C << 2
C >>= 2 is same as
>>= Right shift AND assignment operator.
C = C >> 2
C &= 2 is same as C
&= Bitwise AND assignment operator.
=C&2
Bitwise exclusive OR and assignment C ^= 2 is same as C
^=
operator. =C^2
Bitwise inclusive OR and assignment C |= 2 is same as C =
|=
operator. C|2
© Oxford University Press 2013. All rights reserved.
Example
#include <stdio.h>
main()
{
int a = 21;
int c ;
c = a; printf("Line 1 - = Operator Example, Value of c = %d\n", c );
c += a; printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a; printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a; printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
c /= a; printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a; printf("Line 6 - %= Operator Example, Value of c = %d\n", c );
}
Line 1 - = Operator Example, Value of c = 21
Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - %= Operator Example, Value of c = 11
© Oxford University Press 2013. All rights reserved.
Conditional Operators
The conditional operator has three expressions (ternary).
It has the general form
expression1 ? expression2 : expression3
First, expression1 is evaluated; it is treated as a logical
condition.
If the result is non-zero, then expression2 is evaluated and its
value is the final result. Otherwise, expression3 is evaluated
and its value is the final result.
For example,int m = 1, n = 2, min;
min = (m < n ? m : n); /* min is assigned a value 1 */
In the above example, because m is less than n, m<n
expression evaluates to be true, therefore, min is assigned
the value m, i.e., 1.
© Oxford University Press 2013. All rights reserved.
Conditional Operators
#include <stdio.h>
main()
{
int a , b;
a = 10;
printf( "Value of b is %d\n", (a == 1) ? 20: 30 );
printf( "Value of b is %d\n", (a == 10) ? 20: 30 );
}
This will produce following result:
Value of b is 30
Value of b is 20
© Oxford University Press 2013. All rights reserved.
Comma Operators
This operator allows the evaluation of multiple expressions,
separated by the comma, from left to right in order and the
evaluated value of the rightmost expression is accepted as
the final result. The general form of an expression using a
comma operator is
Expression M = (expression1, expression2, …,expression
N);
where the expressions are evaluated strictly from left to
right and their values discarded, except for the last one,
whose type and value determine the result of the overall
expression.
void main()
{ int num1 = 1, num2 = 2; /*separator*/
int res; res = (num1, num2); /* operator*/
printf("%d", res); } .... Gives output as num2
Sizeof Operators
C provides a useful operator, sizeof, for calculating the size of any data
item or type. It takes a single operand that may be a type name (e.g., int)
or an expression (e.g.,100) and returns the size of the specified entity in
bytes .The outcome is totally machine-dependent.
For example:
© Oxford University Press 2013. All rights reserved.
Expression Evolution :
Precedence & Associativity
Precedence of operators
If more than one operators are involved in an expression, C
language has a predefined rule of priority for the operators.
This rule of priority of operators is called operator
precedence.
In C, precedence of
Arithmetic operators( *, %, /, +, -)
Relational operators(==, !=, >, <, >=, <=)
high
Logical operators(&&, || and !).
Example of precedence
(1 > 2 + 3 && 4)
This expression is equivalent to: ((1 > (2 + 3)) && 4)
i.e, (2 + 3) executes first resulting into 5 then, first part of
the expression (1 > 5) executes resulting into 0 (false)
then, (0 && 4) executes resulting into 0 (false)
Output - 0
Expression Evolution :
Precedence & Associativity
Associativity of operators
If two operators of same precedence (priority) is present in an
expression, Associativity of operators indicate the order in which
they execute.
Example of associativity
1 == 2 != 3
Here, operators == and != have same precedence.
The associativity of both == and != is left to right, i.e, the expression
on the left is executed first and moves towards the right.
Thus, the expression above is equivalent to :
((1 == 2) != 3)
i.e, (1 == 2) executes first resulting into 0 (false)
then, (0 != 3)
executes resulting into 1 (true)
Expression Evolution :
Precedence & Associativity
Evaluation of an expression in
C is very important to
understand. Unfortunately
there is no ‘BODMAS’ rule in C
language as found in algebra.
The precedence of operators
determines the order in which
different operators are
evaluated when they occur in
the same expression.
Operators of higher
precedence are applied before
operators of lower
precedence.
© Oxford University Press 2013. All rights reserved.
Example : Associativity of Operator
© Oxford University Press 2013. All rights reserved.
L-Values & R-Values
An l- value is an expression to which a value can be assigned.
An r- value can be defined as an expression that can be assigned
to an l- value.
The l- value expression is located on the left side of an assignment
statement, whereas an r- value is located on the right side of an
assignment statement.
The address associated with a program variable in C is called its l-
value; the contents of that location are its r- value, the quantity
that is supposed to be the value of the variable.
The r- value of a variable may change as program execution
proceeds; but never its l- value.
© Oxford University Press 2013. All rights reserved.
L-Values & R-Values
For example :
a = b;
b, on the right-hand side of the
assignment operator, is the
quantity to be found at the
address associated with b, i.e.,
an r- value. a is assigned the
value stored in the address
associated with b. a, on the left-
hand side, is the address at
which the contents are altered
as a result of the assignment. a
is an l- value. The assignment
operation deposits b’s r- value
at a’s l- value.
© Oxford University Press 2013. All rights reserved.
Type Conversion
Though the C compiler performs automatic type conversions, the
programmer should be aware of what is going on so as to
understand how C evaluates expressions.
When a C expression is evaluated, the resulting value has a particular
data type. If all the variables in the expression are of the same type, the
resulting type is of the same type as well. For example, if x and y are
both of int type , the expression x +y is of int type as well .
The smallest to the largest data types conversion with respect to size is
along the arrow as shown below:
© Oxford University Press 2013. All rights reserved.
RULE : Type Conversion
Type casting is a way to convert a variable from one data type to
another data type. For example, if you want to store a 'long' value
into a simple integer then you can type cast 'long' to 'int'. You can
convert the values from one type to another explicitly using the
cast operator
#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}
Output
Value of mean : 3.400000
© Oxford University Press 2013. All rights reserved.
RULE : Type Conversion
The usual arithmetic conversions are
implicitly performed to cast their values to a
common type. The compiler first performs
integer promotion (convert to int); if the
operands still have different types, then they
are converted to the type that appears highest
in the following hierarchy
char or short (signed or unsigned) are
converted to int (signed or unsigned).
float operands are converted to double.
If any one operand is double, the other
operand is also converted to double, and
that is the type of the result;
If any one operand is long, the other
operand is treated as long, and that is the
type of the result;
If any one operand is of type unsigned,
the other operand is converted to
unsigned, and that is also the type of the
result.
© Oxford University Press 2013. All rights reserved.
RULE : Type Conversion
#include <stdio.h>
main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}
When the above code is compiled and executed, it produces the
following result −
Value of sum : 116.000000
© Oxford University Press 2013. All rights reserved.
program : swap two numbers
a=b
b=a ??
SWAP two numbers
RUN-1
Enter two integers a and b : 2 3
After swapping a=3 and b=2
RUN-2
Enter two integers a and b : 10 20
After swapping a=20 and b=10
Program = add two times
s, s1, s2
m, m1, m2
h, h1, h2
day ?
#include<stdio.h>
main() h=h+h1+h2;
{ if(h>24)
int h,m,s,h1,m1,s1,h2,m2,s2,day; {
printf("Enter first hours,minutes and day=1;
seconds\n"); h=h%24;
scanf("%d%d%d",&h1,&m1,&s1); }
printf("Enter second hours,minutes and printf("First time = %d:%d:
seconds\n"); %d",h1,m1,s1);
scanf("%d%d%d",&h2,&m2,&s2); printf("\nSecond time = %d:%d:
s=h=m=day=0; %d",h2,m2,s2);
s=s1+s2; printf("\nAdded time =");
if(s>60) if(day==0)
{ printf("%d:%d:%d\n",h,m,s);
m=s/60; else
s=s%60; {
} printf("%d day",day);
m=m+m1+m2; printf("%d:%d:%d\n",h,m,s);
if(m>60) }
{ }
h=m/60;
m=m%60;
}