Unit - I Programming in C
Unit - I Programming in C
G College
Narayanaguda –Hyderabad
Programming in C
Name : ________________________________
Roll No : ________________________________
Group : ________________________________
References :
1
Practical : Programming in C Lab
1. Write a program to find the largest two (three) numbers using if and conditional
operator.
2. Write a program to print the reverse of a given number.
3. Write a program to print the prime number from 2 to n where n is given by user.
4. Write a program to find the roots of a quadratic equation using switch statement.
5. Write a program to print a triangle of stars as follows (take number of lines from user):
*
***
*****
*******
*********
6. Write a program to find largest and smallest elements in a given list of numbers.
7. Write a program to find the product of two matrices..
8. Write a program to find the GCD of two numbers using iteration and recursion.
9. Write a program to illustrate use of storage classes.
10. Write a program to demonstrate the call by value and the call by reference concepts.
11. Write a program that prints a table indicating the number of occurrences of each
alphabet in the text entered as command line arguments.
12. Write a program to illustrate use of data type enum.
13. Write a program to demonstrate use of string functions string.h header file.
14. Write a program that opens a file and counts the number of characters in a file.
15. Write a program to create a structure Student containing fields for Roll No., Name, Class,
Year and Total Marks. Create 10 students and store them in a file.
16. Write a program that opens an existing text file and copies it to a new text file with all
lowercase letters changed to capital letters and all other characters unchanged.
2
Unit – I
Chapter – 1
Computer Fundamentals
Here the user interacts with the software, and the software makes the computer hardware
parts to work for the user.
• Charles Babbage is called the "Father of the computer”. The First mechanical computer
designed by Charles Babbage was called Analytical Engine. It includes some features
which is used in today’s computers.
3
Generation Operating Year Of
Technology Specific Computers
Number System introduction
1 Vacuum Tube None 1945 Mark 1
IBM 1401, ICL 1901, B5000,
2 Transistor None 1956
MINSK-2
IBM S/360/370, UNIVAC
3 SSI and MSI Yes 1964 1100,
HP 2100A, HP 9810
ICL 2900, HP 9845A, VAX
4 LSI and VLSI Yes 1971 11/780, ALTAIR 8800,
IBM PC
Artificial Present and
5 Yes –
Intelligence beyond
1.3.1 Hardware :
Hardware is the physical components of a computer that includes all mechincal, electrical,
electronic and magnetic parts attached to it. A computer consists of the following major
hardware components:
• Input and Output Devices
• Central Processing unit (CPU)
• Memory Unit and Storage devices
• Interface Unit
5
1. Input unit – Input unit is a unit that accepts any input device. The input device is used to
input data into the computer system.
Function of input unit:
• It converts the data based on the program into computer acceptable form
through an input interface.
• It supplies the converted instructions and data to the computer system for
further processing
Some examples of input devices include Keyboard, Mouse, Scanner, Touch screen, etc
Keyboard :
The most common input device is the keyboard. Keyboard
is like a type-writer. A keyboard, normally, consists of 104
keys.
These keys are classified into different categories
which are briefly described below.
Control keys : Alt, Ctrl, Shift, are control keys. It change the functionality of other keys . We
can call control keys as modifier keys.
Navigation keys : These include four arrows, Page Up and Page Down, Home and End. These
keys are normally used to navigate around a document or screen.
Toggle keys : Scroll Lock, Num lock, Caps Lock are three toggle keys. The toggle state is
indicated by three LEDs at the right-top side of the keyboard.
Miscellaneous keys : These keys include Insert, delete, escape, print Screen etc.
Mouse :
A mouse is the pointing device attached to a computer. It is used to move the cursor
around the screen and to point to an object (such as icon, menu, command button etc.) on the
computer video screen for the purpose of selecting or activating objects
6
Scanner :
A scanner is a device that captures pictures or documents so that they can be stored
in storage devices.
2. Output unit – The device that receives data from a computer system for display, physical
production, etc., is called output device. It converts digital information into
humanunderstandable form. For example, monitor, projector, headphone, speaker, printer,
etc..
Monitor :
Computer display devices are commonly known as Visual
Display Unit (VDU) or monitor. It operates on a principle
similar to that of a normal television set.
Various technologies have been used for computer monitors.
They are also of different sizes.
CRT (Cathode-ray tube) and LCD (liquid crystal display)
monitors are the two common types which are widely used.
Printer:
The printer is a device that prints any data, report, document,
picture, diagrams, etc.
Printers are categorized based on the physical contact of the
print head with the paper to produce a text or an image.
Ex: Laser Printer , Dot Matrix Printer, etc
7
iii. Memory Unit (MU) –
Memory is used to store data and instructions before and after processing. There are
mainly two types of memory that are used in a computer system.
One is called primary memory and the other secondary memory.
Primary memory is the area where data and programs are stored while the program is being
executed along with the data. This memory accessed directly by the processor. Primary
Memory is also known as internal memory or main memory.
Secondary memory is used to store date permanently, which is also known as auxiliary
memory, stores a huge number of data bytes at a lesser cost than primary memory devices.
Function of CPU-
1. It controls all the parts and software and data flow of computer.
2. It performs all operations.
3. It accepts data from input device and it sends information to output device.
4. Executing programs stored in memory
5. It stores data either temporarily or permanent basis.
6. It performs arithmetical and logical operations.
Registers :
The register is a special, high-speed storage area within the CPU. All data must be
represented in a register before it can be processed.
For example, if two numbers are to be multiplied, both numbers must be in registers, and the
result is also placed in a register. (The register can contain the address of a memory location
where data is stored rather than the actual data itself.)
Unit of memory:
A computer system uses binary numbers to store and process data. The binary digits 0 and 1,
which are the basic units of memory, are called bits. Further, these bits are grouped together to
form words.
A 4-bit word is called a Nibble. Examples of nibble are 1001, 1010, 0010, etc.
A two nibble word, i.e., 8-bit word is called a byte, for example, 01000110, 01111100, 10000001,
etc.
Table 1.1 shows different measurement units for digital data stored in storage devices.
8
1.4 Memory Hierarchy:
The various types of memory used in a computer system differ in speed, cost, size, and volatility
(permanence of storage). They can be organized in a hierarchy.
Above Figure shows that on moving down the hierarchy, the cost per bit of storage decreases
but access times increases (i.e., devices are slow). In other words, from top to bottom, the speed
decreases while the capacity increases and the prices become much lower.
The various memories specified in the hierarchy, those above the secondary memory are volatile
and the rest are non-volatile.
9
1.5 INTRODUCTION TO OPERATING SYSTEMS
Process(or) management :
➔ Program at the execution is called process.
➔ The operating system decides which process gets to run, for how long and
perhaps at what priority or level of importance.
Memory management :
➔ Memory management refers to management of primary memory or main memory
➔ Operating System also Manages the Memory of the Computer System means Provide
the Memory to the Process and Also Deallocate the Memory from the Process.
➔ It allocates the memory when a process requests and deallocates the memory when
a process has been terminated.
Device management :
➔ The operating system allocates the various devices to the processes and initiates the
I/O operation.
➔ It also controls and schedules accesses to the input/output devices among the
processes.
File management :
➔ A file is just a sequence of bytes.
➔ Files are storage areas for programs, source codes, data, documents etc.
10
➔ The file system is an operating system module that allows users and programs to
create, delete, modify, open, close, and apply other operations to various types of
files.
➔ It also allows users to give names to files, to organize the files
Apart from these functions, an operating system must provide the facilities for controlling the
access of programs, processes, memory segments, and other resources.
➔ The kernel is that part of operating system that interacts with the hardware directly.
➔ Kernel is small in size but it provides the essential services require to operating
system and application.
➔ Mostly the kernel is responsible for memory managements, process management
and device management.
1.7 Software
• Software refers to the instructions, or programs, that tell the hardware what to do.
• set of instructions is called a computer program.
• Software guides the computer at every step where to start and stop during a particular
job. The process of software development is called programming.
• Computer software is normally classified into two broad categories.
Application Software & System software
11
Application Software:
System Software:
➔ System software may be defined as a set of one or more programs designed to control
the operation of computer system.
➔ System software are general programs designed for performing tasks such as
controlling all operations required to move data into and out of the computer. It
communicates with printers, card reader, disk, tapes etc.
➔ System Software allows application packages to be run on the computer with less time
and effort. Remember that it is not possible to run application software without system
software.
Ex: Loader , Linker, Operating Systems, etc.
12
Chapter – 2
Program Fundamentals
2.1 Generation and Classification of Programming Languages
➔ Programming Language is a formal language design to communicate and instruction to
the computer.
➔ Every computer programming language contains a set of predefined words and a set of
rules (syntax) that are used to create instructions of a program.
➔ Generations of Programming Languages classified based on the level of interaction with
the machine.
There are five generation of Programming languages. They are:
13
➔ A machine cannot execute an assembly languages program directly as it is not in a binary
form. An assembler is needed in order to translate an assembly language program into
the object code executable by the machine.
A machine cannot execute an assembly languages program directly as it is not in a binary form.
An assembler is needed in order to translate an assembly language program into the object code
executable by the machine.
14
2.2 Compilation Process
The compilation process can be divided into a number of phases
➔ In the first phase of compilation, termed as lexical analysis, each statement of a
program is analyzed and broken into individual lexical units termed tokens and
constructs a symbol table for each identifier.
➔ The second stage of translation is called syntax analysis; tokens are combined into
syntactic units according to the syntax or grammar of the source language.
➔ In the third stage of compilation, the parsed statements are analysed further to
make sure that the operators and operands do not violate source language
specifications
➔ Next, an intermediate representation of the final machine language code is
produced. Optionally, the intermediate code is optimized to produce an optimized
code.
➔ The last phase of translation is code generation whereby the optimized intermediate
code is converted into target code.
15
2.2.1 Translators
A program written in high-level language is called as source code. To convert the source code
into machine code, translators are needed.
A translator takes a program written in source language as input and converts it into a program
in target language as output.
It also detects and reports the error during translation.
16
Differences between compiler and interpreter
Linker: It is the program which links the object code with some additional library files (header
files) and creates executable file with .exe extension.
17
2.4 Software Development
• Software development is more than programming. A large number of people are involved
in software development.
• Programming is one of the activities of software development.
• Other activities include requirement analysis, design, testing, deployment, maintenance,
etc.
Requirement Analysis
• Requirement analysis is a key part of the software development . Requirement analysis is
the activity is to collect all relevant information of developing software.
Design
• Design involves developing a logical model or basic structure of the new software. It
establishes overall system architecture.
Implementation
• The code for the different modules of the new software is developed according to the
design specifications for each module.
Testing
• Testing is the process of executing a program to find errors. To make
our software perform well it should be error-free.
Deployment
• Software deployment is the process that makes software available for use. Software
documentation is handled over to the users.
Maintenance
• Maintenance is the process of modifying a software product after it has been delivered
to the customer.
18
Chapter – 3
Algorithm
An algorithm is a step by step procedure for solving a problem. An algorithm is very useful for
finding the right answer to a problem or Breaking the difficult problem into simple cases.
For example, algorithm to add two numbers can be simply described in a few steps given below:
1. Start
2. Accept first number as A
3. Accept second number as B
4. Take a number C = A + B
5. Display C
6. End
19
Different ways of stating Algorithms
We can represent algorithm mainly in 3 ways. They are illustrated as follows.
1. Step-form
2. Pseudo Code
3. Flowchart
Step-Form:-
1. Get Book
2. Open Book
3. Find next page
4. If there is no next page go to step7
5. Increment count
6. Go to Step3
7. Finish
Pseudo Code:-
➔ The word pseudo means imitation and code means instructions written some programming
language.
➔ Pseudo code describes the structure of program in simple English language.
➔ Pseudo code describes the complete logic of some program so that implementation become
easy
➔ It does not use any syntax or symbols.
20
FLOWCHARTS:-
Terminator: An oval flow chart shape indicates the start or end of the process, usually
containing the word “Start” or “End”.
or
Process: A rectangular flow chart shape indicates a normal/generic process flow step.
For example, “Add 1 to X”, “M = M*F” or similar
Decision: A diamond flow chart symbol is used when a decision needs to be made,
commonly a Yes/No question or True/False test.
Connector: A small, labeled, circular flow chart shape used to indicate a jump in the
process flow. Connectors are generally used in complex or multi-sheet diagrams
Data: A parallelogram that indicates data input or output (I/O) for a process.
Examples: Get X from the user, Display X.
21
Arrow: used to show the flow of control in a process. An arrow coming from one symbol
and ending at another symbol represents that control passes to the symbol the arrow points
to.
or
6. For a decision symbol, only one flow line can enter it, but multiple lines can leave it to denote
possible answers
Or
7. The terminal symbols can only have one flow line in conjunction with them.
Or
8. It should make use of connector symbol in case of complex flow charts in order to decrease the
number of flow lines.
Although a flowchart is a very useful tool, there are a few limitations in using flowcharts
which are listed below:
❖ Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes
complex and clumsy.
❖ Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely.
❖ Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem
22
Advantages of Using Flowcharts:
❖ Efficient Program Maintenance: The maintenance of operating program becomes easy with the
help of flowchart. It helps the
programmer to put efforts more
efficiently on that part.
Step 1: Start/begin
Step 2: Declare Num1, Num2 and Sum
Step 3: Read Num1 , Num2
Step 4: Sum Num1 + Num2
Step 5: Print or Display Sum
Step 6: Stop/End
23
Example 2: To find Area of Rectangle
Step 1: Start/begin
Step 2: Read A,B
Step 3: if A>B then
Step 4: Print or Display ‘ A’ goto step7
Step 5: else go to step 6
Step 6: Print or Display ‘B’
Step 7: Stop
24
Example 4: Write an algorithm & Flow chart to find the largest among three different numbers entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
.
25
Chapter – 4
Basics of C
4.1 Introduction to C / Overview of C
• C is a structured programming language. It is also known as function orientated
programming language. C programming language was developed in the year
of 1972 by Dennis Ritchie at Bell Laboratories in the USA (AT & T).
• In the year of 1968, research was started by Dennis Ritchie on programming languages
like BCPL, CPL. The main aim of his research was to develop a new language to create an
OS called UNIX. After four years of research, a new programming language was created
with solutions for drawbacks in languages like BCPL & CPL. In the year of 1972, the new
language was introduced with the name “Traditional C”.
• The name 'c' was selected from the sequence of previous language ‘B’ (BCPL) because
most of the features of 'c' were derived from BCPL (B language).
• The first outcome of the c language was the UNIX operating system. The initial UNIX OS
was completely developed using 'c' programming language.
• The founder of the ‘C’ language, Dennis Ritchie is known as “Father of C” and
also “Father of UNIX”.
• The c programming language is very popular because it is reliable, simple and easy to use
and it is the base for almost all the other programming languages.
On a successful compilation of the source file (.c) generates an object file (.obj).The
Object file (.obj) is converted into a (.exe ) file for the execution of “C” Program .
26
4.1 C Program Basics / Structure of C Program
C is a structured programming language. Every c program and its statements must be in a
particular structure. Every c program has the following general structure.
Preprocessing Commands
Preprocessing commands are used to include header files and to define constants. We use
the #include statement to include the header file into our program. We use a #define statement
to define a constant.
Global Declaration
The global declaration is used to define the global variables, which are common for all the
functions after its declaration. We also use the global declaration to declare functions .
main()
Every C program must write this statement. This statement (main) specifies the starting point of
the C program execution.
27
Here, 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.
Open Brace ( { )
The open brace indicates the beginning of the block which belongs to the main method. In C
program, every block begins with a '{' symbol.
Local Declaration
In this section, we declare the variables and functions that are local to the function or block in
which they are declared.
Executable statements
In this section, we write the statements which perform tasks like reading data, displaying the
result, calculations, etc
Closing Brace ( } )
The close brace indicates the end of the block which belongs to the main method. In C program
every block ends with a '}' symbol.
User-defined function()
This is the place where we implement the user-defined functions.
4.2 C Tokens
Every C program is a collection of instructions and every instruction is a collection of some
individual units. Every smallest individual unit of a c program is called token. Every instruction in
a c program is a collection of tokens. Tokens are used to construct c programs and they are said
to the basic building blocks of a c program.
In a c program tokens may contain the following...
28
1. Keywords
2. Identifiers
3. Special Symbols
4. Constants
5. Strings
6. Data values
4.2.1 Keywords
Keywords are the reserved words with predefined meaning which already known to the
compiler.
Properties of Keywords
1. All the keywords in C programming language are defined as lowercase letters so they
must be used only in lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user-defined names like variable, functions, arrays,
pointers, etc...
4. Every keyword in C programming language represents something or specifies some
kind of action to be performed by the compiler.
4.2.2 Identifiers
An identifier is a collection of characters which acts as the name of variable, function, array,
pointer, structure, etc...
In other words, an identifier can be defined as the user-defined name to identify an entity
uniquely in the c programming language that name may be of the variable name, function name,
array name, pointer name, structure name or a label.
29
Example
int marks;
char studentName[30];
30
[Link] Primary Data types
The primary data types in the C programming language are the basic data types. All the primary
data types are already defined in the system. Primary data types are also called as Built-In data
types. The following are the primary data types in c programming language...
1. Integer data type
2. Floating Point data type
3. Double data type
4. Character data type
31
Floating Point data types
Floating-point data types are a set of numbers with the decimal value. Every floating-point value
must contain the decimal value. The floating-point data type has two variants...
• float
• double
We use the keyword "float" to represent floating-point data type and "double" to represent
double data type in c. Both float and double are similar but they differ in the number of decimal
places. The float value contains 6 decimal places whereas double value contains 15 or 19 decimal
places.
The following table provides complete details about floating-point data types.
32
4.2.4 Variables
Variable is a name given to a memory location where we can store different values of the same
datatype during the program execution.
A variable name may contain letters, digits and underscore symbol. The following are the rules
to specify a variable name...
1. Variable name should not start with a digit.
2. Keywords should not be used as variable names.
3. A variable name should not contain any special symbols except underscore(_).
4. A variable name can be of any length but compiler considers only the first 31
characters of the variable name.
Declaration Syntax:
datatype variableName;
Example
int num;
The above declaration tells to the compiler that allocates 4 bytes of memory with the
name num and allows only integer values into that memory location.
4.2.5 Constants
A constant is a named memory location which holds only one value throughout the program
execution. A constant can be of any data type like integer, floating-point, character, string
and double, etc.,
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'.
Example
125 -----> Decimal Integer Constant O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
'A'
'2'
'+'
String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences
that are enclosed in double quotations.
4.3 Operators
An operator is a symbol used to perform arithmetic and logical operations in a program. That
means an operator is a special symbol that tells the compiler to perform mathematical or logical
operations. C programming language supports a rich set of operators that are classified as
follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
34
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
< Returns TRUE if the first value is smaller than second value 10 < 5 is
otherwise returns FALSE FALSE
> Returns TRUE if the first value is larger than second value otherwise 10 > 5 is
returns FALSE TRUE
<= Returns TRUE if the first value is smaller than or equal to second 10 <= 5 is
value otherwise returns FALSE FALSE
>= Returns TRUE if the first value is larger than or equal to second 10 >= 5 is
value otherwise returns FALSE TRUE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is
TRUE
Logical Operators (&&, ||, !)
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.
35
Operator Meaning Example
&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10
otherwise returns FALSE is FALSE
! Logical NOT - Returns TRUE if condition is FLASE and !(10 < 5 && 12 >
returns FALSE if it is TRUE 10) is TRUE
+= Add both left and right-hand side values and store the result into A += 10
left-hand side variable ⇒A = A+10
36
In this operator, first we verify a condition, then we perform one operation out of the two
operations based on the condition result. If the condition is TRUE the first option is performed,
if the condition is FALSE the second option is performed.
The conditional operator is used with the following syntax.
#include <stdio.h>
int main()
{
int age;
printf("Enter your age : ");
scanf("%d",&age);
(age>=18)?(printf("Eligible for voting")):(printf("Not eligible
for voting"));
return 0;
}
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This
operator is used with the following syntax.
sizeof(variableName);
37
Example Program on sizeof Operator
#include <stdio.h>
int main()
{
printf("Character size :%d Byte", sizeof(char));
printf("\nInteger size :%d Bytes", sizeof(int));
printf("\nFloat size :%d Bytes", sizeof(float));
printf("\n Double size :%d Bytes", sizeof(double));
return 0;
}
One’s Compliment: - The ones complement operator is used to convert the bit from 1 to 0 and
0 to 1. The operator is used to represent ones compliment is called tilde (~) (takes only one’s
value).
e.g.: - A = 10100101 = (165)10
~A = 01011010 = (90)10
Bit-wise AND (&): - This operator is used to perform the AND operation between the bits. It is
representing with single ampersand (&).
Example: - if a=5 b=7
38
c= a & b
𝑎 = 0000 0101 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 5}
𝑏 = 0000 0111 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 7}
𝑐 = 0000 0101 {𝑏𝑖𝑛𝑎𝑟𝑦 𝑓𝑜𝑟𝑚 𝑜𝑓 5}
c=5
Bit-wise OR (|):
This operator is used to perform the OR operation between two bits. The operator used here is a single
pipe (|).
Syntax: - operand1 | operand2
In the above definition, an 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. Here operand can be a direct
value or variable or address of memory location.
Expression Types in C
In the C programming language, expressions are divided into THREE types. They are as follows...
40
What is Operator Associativity?
Operator associativity is used to determine the order of operators with equal precedence
evaluated in an expression.
In the c programming language, when an expression contains multiple operators with equal
precedence, we use associativity to determine the order of evaluation of those operators.
In c programming language the operator precedence and associativity are as shown in the following table.
() function call
[] array reference
1 Left to Right
-> structure member access
. structure member access
! negation
~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
2 Right to Left
-- decrement operator
& address of operator
* pointer
sizeof returns size of a variable
(type) type conversion
* multiplication
3 / division Left to Right
% remainder
+ addition
4 Left to Right
- subtraction
== equal to
7 Left to Right
!= not equal to
41
Precedence Operator Operator Meaning Associativity
= assignment
*= assign multiplication
/= assign division
%= assign remainder
+= assign addition
14 -= assign subtraction Right to Left
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift
#include <stdio.h>
int main ()
{
int x;
x = 10*20+110/5;
printf ("The Value of x = %d", x);
return 0;
}
42
4.5 Expression Evaluation
An expression is evaluated based on the precedence and associativity of the operators in that
expression.
To understand expression evaluation in c, let us consider the following simple example
expression...
10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these three operators,
both multiplication and division have the same higher precedence and addition has
lower precedence.
It is evaluated as follows...
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
Example Program on Expression Evaluation
#include <stdio.h>
int main()
{
printf("%d",10+4*3/2);
}
1. Type Conversion
2. Type Casting
43
Type Conversion
The type conversion is the process of converting a data value from one data type to another data
type automatically by the compiler.
Sometimes type conversion is also called implicit type conversion. The implicit type conversion
is automatically performed by the compiler.
Typecasting
Typecasting is also called an explicit type conversion. Compiler converts data from one data type
to another data type implicitly. When compiler converts implicitly, there may be a data loss.
The general syntax of typecasting is as follows.
(TargetDatatype) DataValue
Example
int totalMarks = 450, maxMarks = 600 ;
float average ;
44
Example 2 Program on Implicit Type Conversion
#include<stdio.h>
int main()
{
int num=10;
printf("Integer Value: %d\n", num);
float f=num;
printf("Float Value: %f", f);
return 0;
}
45
Unit-I Questions
1. Computer ? Classification of Computers
2. Major Hardware Components of a computer / Anatomy of a computer.
3. Memory Hierarchy and Software and it types.
4. Operating System and Operations of CPU
5. Define Algorithm and explain in detail about different ways of
stating an algorithm
6. Write about “C” tokens and operators in detail
7. Structure of C Program
8. Expression , Operator precedence and Operator associativity
9. Datatypes with examples
10. Type Casting and Type Conversions in C with an example program.
11. Explain Flowchart in detail (Flowchart guidelines and
limitations).
12. Translators
13. Generations and Classifications of Programming Languages.
46