0% found this document useful (0 votes)
2 views20 pages

cp unit-1 notes

The document outlines the process of creating and running C programs, detailing the steps from writing source code to executing the program and checking results. It also explains how integers and real numbers are stored in memory, including binary addition and subtraction methods, and discusses the structure of a C program, its character set, tokens, keywords, and variables. Additionally, it highlights the characteristics and uses of the C programming language.

Uploaded by

Jyothi Yadla
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)
2 views20 pages

cp unit-1 notes

The document outlines the process of creating and running C programs, detailing the steps from writing source code to executing the program and checking results. It also explains how integers and real numbers are stored in memory, including binary addition and subtraction methods, and discusses the structure of a C program, its character set, tokens, keywords, and variables. Additionally, it highlights the characteristics and uses of the C programming language.

Uploaded by

Jyothi Yadla
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/ 20

Faculty: Ch.

Lavanya Susanna, dept of cse


Unit-1
Creating and running c programs:
Creating running C programs involves 4 steps as follows:

Step1: Create Source code


Program is a set of instructions created using programming languages like C, C++, Java, etc., are
written using a high-level language like English. The C program or source code contains set of
instructions written in C language and it is saved as ‗filename.c‘. The file extension of c program is ‗.c‘

Step2: Compile Source code


The computer cannot understand the high-level language. It can understand only low-level
language (binary system). So, the program written in the high-level language needs to be converted into
the low-level language to make it understandable for the computer. This conversion is performed-by-a-
translator-called-compiler.
A compiler is a program that converts high-level language instructions into low-level
language instructions. Generally, the compiler performs two things, first it verifies the program errors,
if errors are found, it returns a list of errors otherwise it converts the complete code into the
object code which contain compact binary code with ‗.o‘ file extension
Then the object code is given to the Linker. The Linker combines both the object code and
specified header file code and generates an Executable file with .exe extension.

Step 3: Executing / Running Executable File


After completing compilation successfully, an executable file is created with a .exe extension. The
processor can understand this .exe file. On receiving .exe file, CPU performs the task according to the

1
Faculty: Ch.Lavanya Susanna, dept of cse
instruction written in the file. The result generated from the execution is placed in a window called User
Screen.
Step 4: Check Result
After running the program, the result is placed into User Screen. Just we need to open the User Screen
to check the result of the program execution.

Important Points to remember


 C program file (Source file) must save with .c extension.
 The compiler converts complete program at a time from high-level language to low-level
language
 Input to the compiler is .c file and output from the compiler is .exe file, but it also
generates .obj file in this process.
 The compiler converts the file only if there are no errors in the source code.
 CPU places the result in User Screen window.

Overall Process in Turbo C


 Type the program in C editor and save with .c extension (Press F2 to save).
 Press Alt + F9 to compile the program.
 If there are errors, correct the errors and recompile the program.
 If there are no errors, then press Ctrl + F9 to execute/run the program.
 Press Alt + F5 to open User Screen and check the result

Storing integers:

Integers are whole numbers (no fractional part) or An integer is a number with no fractional part;
it can be positive, negative or zero which will be stored in computer memory using 2 bytes (16 bits) or 4
bytes (32 bits) depending on machine.

Integer types can be:


n
 Unsigned(positive number): that can store values from 0 to 2 -1, as simple binary numbers where
n is number of bits
n-1 n
 Signed: that can store values from - 2 to 2 -1, as two‘s complement binary format where n is
number of bits

The MSB (most significant bit) bit is used to indicate whether the number is positive or negative.
2
Faculty: Ch.Lavanya Susanna, dept of cse
 For positive numbers MSB will be 0.
 For negative numbers MSB will be 1.
Storing unsigned values: First, compiler converts decimal number system to binary number system
(100010110) internally and then takes into consideration only the first 16 bits or 32 bits (depending on
machine)from the right of that number represented in binary and stores it because the size of integer is 2
or 4 bytes
Storing signed values: Compiler first takes its 2 complement and then displays the number with
negative sign.
Computer uses special mechanism to store negative numbers which is 2‘s complement format.
For this the compiler does ones complement to the binary number and then add 1 to the ones
complement
1’s complement of a number
1‘s compliment of number is just inverting binary bits of an actual number.
Example:
10
Binary representation will be (1 0 1 0) 2
1‘s compliment of 10 is, 0 1 0 1 (switching 0 to 1 and 1 to 0).
2’s complement of a number
To get 2‘s complement of a number, just add 1 to 1‘s complement of an actual number.

3
Faculty: Ch.Lavanya Susanna, dept of cse
Performing addition and subtraction by computer:

Binary addition:

The method of addition, there are four cases or steps to remember before proceeding through the
operation. These are

As there no numbers other than 0 and 1 in the binary number system these four steps include all the
possible operations of addition.

A= 149 B=134

Suppose A = 10010101 and B = 10000110

To add A+B the process is

Binary subtraction:

Computers though, don‘t perform subtraction; they don‘t have the circuits built in that support it. Instead
they take another approach
C = A + (-B)
“Computers actually perform subtraction by adding”.
The steps are as follows.
Step 1: Calculate the Two‘s Complement of our number B.
Step 2: Add the Two‘s Complement of B to A to Get Our Result (C)

Suppose A = 10010101 and B = 10000110

C=A – B i.e C = A + (-B)

4
Faculty: Ch.Lavanya Susanna, dept of cse

The signed number of B is performed by 2‘s complement

Storing real numbers:


Real numbers are numbers that include fractions/values after the decimal point.
For example, 123.75 is a real number.
There are two major approaches to store real numbers. These are
1. Fixed Point Notation: In fixed point notation, there are a fixed number of digits after the decimal
point

2. Floating Point Notation: Floating point number allows for a varying number of digits after the
decimal point. This representation does not reserve a specific number of bits for the integer part or the
fractional part.

5
Faculty: Ch.Lavanya Susanna, dept of cse

The floating number representation of a number has two parts:


1) Mantissa.
2) Exponent.
All floating point numbers are stored by a computer system using a mantissa and an exponent.
Mantissa: A mantissa is the part of a number located after a decimal point.
An example of mantissa is 75 in the number 123.75.
Exponent: This specifies the position of the decimal (or binary) point
2
An example 123.75 this can be written as 1.2375 x10
e
Floating -point is always interpreted to represent a number in the following form: M x r .
Where M is mantissa, r is radix (base) and e is exponent.

Consider the following example:


The number 123.75 can be represented as 1111011.11 in binary but the computer will not
e
store the binary number in the same way as above. It stores in the form M x r .
Represent the number 123.75 as:
6 5 4 3 2 1 0 0.5 0.25
2 2 2 2 2 2 2

1 1 1 1 0 1 1 1 1

64 + 32 + 16 + 8 + 2 + 1 + 0.5 + 0.25 = 123.75


The number created in binary is the mantissa:
111101111
To understand the exponent, place the decimal point after the most significant bit of the mantissa. The
most significant bit is the left most bit i.e 1.11101111

To calculate the exponent, it is necessary to determine how many places the decimal point would need to
move to give the correct number. In this case the decimal point would need to move six places to the
right i.e 1111011.11
So the exponent for our number is 6. In binary, the number six is i.e 110 in binary
In order to represent 123.75 the mantissa would be 111101111 and the exponent would be 110. This can
be thought of as:M X 2E (where M represents the mantissa and E represents the exponent)
1.11101111 x 2110

6
Faculty: Ch.Lavanya Susanna, dept of cse
Background of c:

C is a general-purpose, high-level language that was originally developed by Dennis Ritchie to develop
the UNIX operating system at Bell Labs.

Taxonomy of C:

Characteristics of C language

 Programs Written in C are efficient and fast. This is due to its variety of data type and powerful
operators
 C is super fast. The compilation and execution of programs is much faster on C than with most
other language
 C is highly portable this means that programs once written can be run on another machines with
little or no modification.
 C program is basically a collection of functions that are supported by C library. We can also
create our own function and add it to C library.
 C is modular, which means C programs can be divided into small modules, which are much
easier to understand.
 C is a structured programming language which emphasis on writing set of instructions step by
step to get the output rather than concentrating on data or code

Uses of C language

 C programming language can be used to design the system software like operating system and
Compiler.
 To develop application software like database and spread sheets.
 For Develop Graphical related application like computer and mobile games.
 To evaluate any kind of mathematical equation use c language.
 C programming language can be used to design the compilers.
 UNIX Kernal is completely developed in C Language.
7
Faculty: Ch.Lavanya Susanna, dept of cse
 For Creating Compilers of different Languages which can take input from other language and
convert it into lower level machine dependent language.
 C programming language can be used to design Operating System.
 C programming language can be used to design Network Devices.
 To design GUI Applications. Adobe Photoshop, one of the most popularly used photo editors
since olden times, was created with the help of C.
C is best used for
 Systems that require fast and direct access to hardware
 Systems with limited resources (like memory)
 Systems where performance is the most important attribute
 Some examples are BIOSes, Operating Systems, Embedded Systems, Real-time systems

Files used to construct the C program


Four types of files are used to construct the C program. They are

1. Source file: Program is a set of instructions created using programming languages like C, C++, Java,
etc., are written using a high-level language like English. The C program or source code contains set of
instructions written in C language and it is saved as ‗filename. c‘. The file extension of c program is ‗.c‘

2. Header file: Header files are helping file of C program which holds the definitions of various
functions/Subroutines. The entire header file have a '.h' an extension which are included into C program
using preprocessor directive ―#include ―.Including a header file means that using the content of header
file in the source program. When header files are included in C program using “#include <filename.h>”
command, all C code of the header files are included in C program. Missing the inclusion of appropriate
header file will generate an error. Some of the header files are
• Stdio.h - for standard input and output functions
• String.h - for string handling functions
• Math.h - for mathematical functions
• Conio.h - for clearing the screen

3. Object file: An object file is the real output from the compilation phase which contains mostly
machine code i.e. binary representation of the instructions of the source code. Linker uses object file to
produce executable file. Object files have ‗.o‘ file extension.

4. Executable file: After completing compilation successfully, an executable file is created with
a .exe extension. The processor can understand this .exe file. On receiving .exe file, CPU performs the
task according to the instruction written in the file. The result generated from the execution is placed in a
window called User Screen.

8
Faculty: Ch.Lavanya Susanna, dept of cse
Structure of c program: A C program contains more sections as shown below

1. Documentation section: this section contains


comment lines. The comments describe what
the program does. There are two types of
comments lines.
a) Single comment line: This
comment begins with \\ followed by single line
comment.
b) Block comment: If there are
more comment lines then they are places
between /* */ .
2. Link section: This section contains header
files or preprocessor directives which tells
compiler to include all the functions from
library into source code. This section also
contains symbolic constants.
3. Definition section: All the
function/subprogram definitions are placed in
this section.
4. Global declaration section: Some variables
which are used by all subprograms/functions are
declared I this section.

5. Main () section: Every C program must have one main() section. This contains two parts:
a) Declaration part: This part contains all variables which are used in executable part.
b)Executable part: This part contains the statements/instructions of the program.
6. Subprogram section: This section contains all the subprograms which are placed immediately after
main ().

Character set:
A character set is a set of alphabets, letters and some special characters that are valid in C language.
• Alphabets
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
C language is case sensitive i.e. uppercase letters and lowercase letters are not same
• Digits
0123456789
• Special Characters
, < ,>, ., _ , ( , ) , ; , $ , : , % , [ , ] , # , ? , ‗ , & , { , } , ― , ^ , ! , * , / , | , - , \ , ~ , +
• White space Characters
Blank space, newline, horizontal tab etc…

9
Faculty: Ch.Lavanya Susanna, dept of cse
C Tokens: Tokens are smallest individual unit Identifiers: Identifier refers to name given to
of program program elements such as variables, functions
etc.

Rules
• An identifier can only have
alphanumeric characters (a-z , A-Z , 0-9)
(i.e. letters & digits) and underscore( _ )
symbol.
• Identifier names must be unique
• The first character must be an alphabet
or underscore.
• Keywords cannot be used as identifiers.
• Only first thirty-one (31) characters are
Keywords: Keywords are predefined; reserved significant.
words used in programming that have special • Must not contain white spaces.
meanings to the compiler. • Identifiers are case-sensitive i.e
uppercase and lowercase letters are
different

Examples:

Valid invalid

NUMBER , number $NUMBER ,

_NUMBER1 ,number1 1number , 2number

Count , num_1 , Num 1 , num 2


num_2

Variables: A variable is a name of the Declaration of variables must be done before


memory location. It is used to store data. Its they are used in the program i.e it must be the
value can be changed, and it can be reused first statement after main() . Declaration does
many times. the following things.
Rules for defining variables  It tells the compiler what the variable
name is.
o A variable can have alphabets, digits,  It specifies what type of data the
and underscore. variable will hold and amount of
o A variable name can start with the memory to be allocated.
alphabet, and underscore only. It can't Syntax: Datatype variablelist ;
start with a digit. Variable list contains variables separated by
o No whitespace is allowed within the commas.
variable name. Examples:
o A variable name must not be any int a;//integer variable
reserved word or keyword, e.g. int, float b;//float variable
float, etc. char c;//character variable
int num1,num2,num3;
10
Faculty: Ch.Lavanya Susanna, dept of cse
Initializing a variable means to provide it scanf("%f%lf%Lf",&f,&d,&ld);
with a value. This can be done in two ways. printf("Enter a character : ");
1. at variable declaration scanf(" %c",&c);
Syntax: int variable = value ; printf("Given int value : %d\n",i);
Example: int a = 10; printf("Given short int value : %hd\n",si);
2. Any where in program before it is printf("Given long int value : %ld\n",li);
used i.e after declaration of variable printf("Given float value : %f\n",f);
Syntax : variable = value ; printf("Given double value : %lf\n",d);
Example: int a ; printf("Given long double value : %Lf\n",ld);
a = 10 ; printf("Given character : %c\n",c);
C program to compute the perimeter and return 0;
area of a rectangle with a height of 7 inches }
and width of 5 inches. OUTPUT:
SOURCE CODE: Enter int, short int and long int values : 12345
#include<stdio.h> 123 1234567
int main() Enter float, double and long double values : 1.2
{ 3.14 9.334
int length, width, area, perimeter; Enter a character : G
printf("Enter the length and width of the Given int value : 12345
rectangle :\n "); Given short int value : 123
scanf("%d%d",&length,&width); Given long int value : 1234567
area = length*width; Given float value : 1.200000
perimeter = 2*(length+width); Given double value : 3.140000
printf("Area of rectangle : %d square Given long double value : 9.334000
inches\n",area); Given character : G
printf("Perimeter of rectangle : %d
inches\n",perimeter); Types of Variables in C:
return 0; There are many types of variables in c:
} local variable
OUTPUT: global variable
Enter the length and width of the rectangle : 7 5 1. Local variable: A variable that is declared
Area of rectangle : 35 square inches inside block is called a local variable.
Perimeter of rectangle : 24 inches The block start with ‗{ ‗ and ends with ‗}‘.The
C program to display multiple variables. local variables are accessed only within the
SOURCE CODE: block in which it is declared.
#include<stdio.h> Block Syntax:
int main(){ {
int i; Statements;
short int si; }
long int li; Example
float f; #include<stdio.h>
double d; Void main()
long double ld; {
char c; int x=10;
printf("Enter int, short int and long int values : printf(―the value of x is %d\n‖,x);
"); }
scanf("%d%hd%ld",&i,&si,&li); Here x is a local variable which is declare
printf("Enter float, double and long double inside main block.it cannot be acceses outside
values : "); main block.
11
Faculty: Ch.Lavanya Susanna, dept of cse
Output: Program2:
the value of x is 10 #include<stdio.h>
int x=20;
2. Global variable: Variable that is declared void main()
outside the function or block is called a global {
variable. Global variables are declared before x=10;
main().They are accessible by all subprograms printf("the value of x is %d\n",x);
and can be modified by any subprogram }
C Program to demonstrate global variable Output:
Program1:
#include<stdio.h> the value of x is 20
int x=20;
void main() In the above program in main() function global
{ variable is modified so x variable contains
printf("the value of x is %d\n",x); value 10.the same value 10 is accessed outside
} the block by other subprograms also
Output:

the value of x is 20

Constants: Following rules must be observed while


constructing real constants expressed in
Constants in C are the fixed values which fractional form:
cannot be modified during the execution of the  A real constant must have at least one
program. Primary Constants are Integer, Real digit.
and Character constants.  It must have a decimal point.
1) Integer Constants  It could be either positive or negative.
Rules for Constructing Integer Constants  Default sign is positive.
 An integer constant must have at least  No commas or blanks are allowed within a
one digit. real constant.
 It must not have a decimal point.
 It can be either positive or negative. Examples.: +325.34
 If no sign precedes an integer constant it 426.0
is assumed to be positive. -32.76
 No commas or blanks are allowed within -48.5792
an integer constant. The exponential form of representation of real
constants is usually used if the value of the
 The allowable range for integer
constant is either too small or too large
constants is -2n-1 to 2n-1 where n is no: of
Following rules must be observed while
bits required to store an integer . constructing real constants expressed in
Examples.: 426 exponential form:
+782  The mantissa part and the exponential part
- 8000 should be separated by a letter e.
- 7605  The mantissa part may have a positive or
2) Real constants: negative sign. Default sign of mantissa
Real constants are often called Floating Point part is positive.
constants. The real constants could be written in
two forms—Fractional form and Exponential
form.
12
Faculty: Ch.Lavanya Susanna, dept of cse
 The exponent must have at least one digit, Example ‗5‘,‘X‘ –here 5 is not an integer number
which must be a positive or negative treated as character constant
integer. Default sign is positive. C supports some special backslash character
 Range of real constants expressed in constants that are used in output functions.
exponential form is -3.4e38 to 3.4e38. Some of them are:
3) Character constants:  \t -Inserts a tab in the text at this point.
Rules for Constructing Character Constants:  \b -Inserts a backspace in the text at this
 A single character constant contains a point.
single character enclosed with a pair of  \n -Inserts a newline in the text at this
single quotes. point.
 Character constants have Integers values  \’ -Inserts a single quote character in the
known as ASCII values. text at this point.
 It is not possible to perform arithmetic  \” -Inserts a double quote character in the
operations on character constants. text at this point.
 The maximum length of a character  \\ -Inserts a backslash character in the
constant is 1 character. text at this point.
 \0 - null
4) String constants:

 A sequence of characters enclosed in double quotes.


 A string constant can be any length
 A single string constant occupies two bytes.
 Every string constant ends up with a NULL character which is automatically
assigned (before the closing double quotation mark) by the compiler
Examples: ―A‖, ―Hello‖
C program to print a block F using hash (#)F has height of six characters and width of five and
four characters

#include <stdio.h> output:


void main()
{
printf("######\n");
printf("#\n");
printf("#\n");
printf("#####\n");
printf("#\n");
printf(―#\n‖);
printf("#\n");
}

13
Faculty: Ch.Lavanya Susanna, dept of cse

How To Use Constants In A C Program? printf("\n The area of the circle with radius %f
We can define constants in a C program in the is: %f\n", radius, area);
following ways. }
1. By ―const‖ keyword
Syntax: const datatype variable = value ; Output:
Enter the radius of the circle:3
2. By ―#define‖ preprocessor directive
The area of the circle with radius 3.000000
Syntax: #define name value is:29.608951
Rules: 1.symbolic name must be in uppercase Basic data types:
2. No semicolon at the end of statement
3. No symbols used between name and
value
Trying to change constant values after defining
in C program, it will through error.

Example Program Using Const Keyword In


C:
#include <stdio.h>
void main()
{
const int height = 100;
const float number = 3.14;
const char letter = 'A';
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
}
OUTPUT:

value of height : 100


value of number : 3.140000
value of letter : A

Example Program Using #Define


Preprocessor Directive
/* A program to compute the area of a circle */
#include<stdio.h>
#define PI 3.1416
void main()
{
float area, radius;
printf("Enter the radius of the circle\n");
scanf("%f", &radius);
area = PI * radius * radius;
14
Faculty: Ch.Lavanya Susanna, dept of cse

Evaluating expressions
 An expression is a collection of operators and
operands.
 operator is a symbol that performs tasks like
arithmetic operations, logical operations, and
conditional operations, etc.
 Operands are the values on which the
operators perform the task

Example
A+B
Here operator is + and operands are A and B

 Operator precedence is used to determine


the order of operators evaluated in an The operator ‗ ( )‘ will have highest precedence than
expression. In c programming language every any other operators.
operator has precedence (priority). When
there is more than one operator in an In the C programming language, an expression is
expression the operator with higher evaluated based on the operator precedence and
precedence is evaluated first and the operator associativity. When there are multiple operators in an
with the least precedence is evaluated last. expression, they are evaluated according to their
 Operator associativity is used to determine precedence and associativity.
the order of operators with equal precedence
evaluated in an expression. In the c
programming language, when an expression Examples:
contains multiple operators with equal
precedence, we use associativity to determine 1) 34 + 12 / 4 – 45
the order of evaluation of those operators.

15
Faculty: Ch.Lavanya Susanna, dept of cse
Step1: calculate the value of operator / which has Syntax: operator operand1 operand2;
higher precedence over + and – Example: a b +;

Side effects:

Changing the value of left side variable of an


Expression is 34 + 3 – 45 expression is a side effect.
Consider the following example:
Step2: the expression contains same precedence a=10 ;
operators + and - .they are evaluated using here variable x contain value 10
associatively i.e left to right

Expression is 37 - 45 Assigning new value to a


Step3: calculate the subtraction of the expression a=6;

Ans is -8

Example 2: Pre increment operator: The pre increment


operator is ‗++‘ .This operator is placed before
the operand which adds 1 to its operand before it
is used.

Examples:
int x = 10;
y = ++x
This statement is similar to x = x + 1
y=x
first x value gets incremented i.e 1 is added to
value x and second the value which is
incremented of x is assigned to y.

Ans- 41
x = x+1 = 10 + 1 = 11
Types of expressions:
y =11
1. Infix expression: An expression in which an
operator is placed in-between operands is called as
Infix expression
Syntax: operand1 operator operand2;
Example: a + b ;
2. Prefix expression: An expression in which an
operator is placed before operands is called as Prefix Here the variable x has a side effect as its value
expression. is changed from 10 to 11.
Syntax: operator operand1 operand2; Pre decrement operator: The pre decrement
Example: + a b ; operator is ‗--‘ .This operator is placed before the
3. Postfix expression: An expression in which an operand which subtracts 1 from its operand
operator is placed after operands is called as Postfix before it is used.
expression.
16
Faculty: Ch.Lavanya Susanna, dept of cse
Consider the following example: In a programming language, the
int x = 10; expression contains data values of the same
y = ++x datatype or different data types. When the
This statement is similar to x = x - 1 expression contains similar datatype values then
y=x it is evaluated without any problem. But if the
first x value gets decremented i.e 1 is subtracted expression contains two or more different
from value x and second the value which is datatype values then they must be converted to
decremented of x is assigned to y. the single datatype.
Type conversion refers to changing an
variable of one data type into another type.
Type conversion in c can be classified
x = x-1 = 10 - 1 = 9 into the following two types:
y =9 1. Implicit Type Conversion
2. Explicit Type Conversion

1. Implicit Type Conversion: compiler will


automatically change one type of data into
Here the variable x has a side effect as its value
another without programmers intervention, such
is changed from 10 to 9.
type of conversion is known as implicit type
Post increment operator: The post increment conversion or type promotion.
operator is ‗++‘ .This operator is placed after the
operand which adds 1 to its operand after it is
used.

Examples:
int x = 10;
y = x ++
This statement is similar to y = x
x=x+1
first the value of x is assigned to y and then the
value of x is incremented.
All lower datatype values are automatically
converted to higher datatype values
#include <stdio.h>
y = 10
void main()
x = 10 + 1 = 11
{
float x = 90 ;
float f = 'A' ;
printf("x value is %f\n",x);
printf("f value is %f\n",f);
Here the variable x has a side effect as its value }
is changed from 10 to 11. Output:
(Similarly post decrement also) x value is 90.000000
Evaluate the following expression with d value is 65.000000
sideeffect: --3 * ( 3 + 4) / 2 – 5 * 4 ans = - 13

Type conversion:

17
Faculty: Ch.Lavanya Susanna, dept of cse
Program to demonstrate implicit type The following rules have to be followed while
conversion of higher datatype value to lower converting the expression from one type to
datatype value another to avoid the loss of information:
#include <stdio.h>
void main()  All integer types to be converted to float.
{  All float types to be converted to double.
int i = 95.3 ;  All character types to be converted to
float x = 90.9945678934567 ; integer.
printf("i value is %d\n",i);
printf("x value is %f\n",x); C program to find average of two numbers:
} #include <stdio.h>
Output: void main()
i value is 95 x {
value is 90.994568 int a,b;
float avg;
If higher datatype value is assigned to lower printf("enter a and b values\n");
datatype value then the data will be lost. scanf("%d%d",&a,&b);
We cannot perform implicit type casting on avg=(float)a/(float)b;
the data types which are not compatible with printf("the average of two numbers is
each other such as: %f\n",avg);
1. Converting float to an int will truncate the }
fraction part hence losing the meaning of Output:
the value. enter a and b values
2. Converting double to float will round up 3 2
the digits. the average of two numbers is 1.500000
3. Converting long int to int will cause
dropping of excess high order bits. Input and output streams: A stream is
sequence of bytes.
2. Explicit Type Conversion (type casting):
Explicit type conversion is also known as type
casting. The type conversion performed by the
programmer by posing the data type of the
expression of specific type is known as explicit
type conversion.
Type casting in c is done in the following form:

SYNTAX: (Datatype) Expression the input streams provides data to the program
and output stream receives data from the
Example: program.
int a =3 , b= 2 C language supports two functions:
float c; 1.prinf()
c=a/b 2.scanf()
ans is c =1
c = (float) a / (float) b ; 1.prinf():this function is used to print the
ans is c= 1.5 information on the user screen.
Here integer value is explicitly converted to float syntax: printf("control string", variable list);
value so correct result displayed without data here control string contains two parts
lost.
18
Faculty: Ch.Lavanya Susanna, dept of cse
a)sequence of characters to be displayed on 2)Real numbers:
the screen float a=10.123456;
b)format specifiers
variable list contains variables, separated by
commas
example:
int a=10;
printf("the a value is %d\n",a);
output:The a value is 10.
The format specifier has following
specification
% W.V typespecifier
% - indicates conversion
fieldwidth(W.V) - W specifies the total no:of
columns for output. Rules for printf():
- V specifies no:of digits to 1.characters that are specified in control string
be printed. are displayed as it is
type specifiers 2.escape sequences linke \n,\t are not displaed on
c - character screen
d - integer 3.for each format specifier in control string there
f - float must be a vaiable
lf - double 2)scanf():used to read the data from the
s - string keyboard according the format specified.
u - unsigned int syntax: scanf("control string",&var1,....,&var n);
h - short int the control string contains two parts:
o - octal a)precent sign
x - hexa decimal b)followed by typespecifier
examples:1)integers variables contains & symbol before them which
int a= 4567 ; indicates address.
example:
int a,b;
scanf("%d%d",&a,&b);
The format specifier has following
specification:
% wd
% - indicates conversion
w - no:of digits to be read
d - typespeifier
Examples inputting integers:
Data entered by user is 50 314268

19
Faculty: Ch.Lavanya Susanna, dept of cse

Data entered by user is 3245 175

The value175 is left in input stream and will be


read by next scanf().

Rules for scanf():


1.each format specifier in control string must
have variable with & operator before variable.
2. Data entered by user must match format
specifer in control string.
3. In control string no symbols are allowed other
than white spaces.

20

You might also like