0% found this document useful (0 votes)
86 views49 pages

CTP Unit-1 Final

Uploaded by

K.saimadhuri
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)
86 views49 pages

CTP Unit-1 Final

Uploaded by

K.saimadhuri
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/ 49

Computational Thinking and Programming

UNIT-I
Syllabus:
Introduction to Computational Thinking- Definition, objectives, how is computational
thinking used? Logical and algorithmic thinking.
Problem-solving elements- - Algorithms, Definition and characteristics; Flowchart,
flowchart symbols, Pseudo code solution to problems, Basic Structures of C Language,
Creating and Running Programs, variables and data types, input and output statements,
types of operators, precedence of operators, type conversion.

Computational Thinking:
 Computational thinking is the thought processes involved in formulating a
problem and expressing its solution(s) in such a way that a computer—human or
machine—can effectively carry out. (Wing 2014)
 The mental activity for abstracting problems and formulating solutions that can
be automated.

How is Computational Thinking used:


 CT can be applied by anyone who is attempting to solve a problem and have a
computer play a role in the solution. To give us some idea of how CT is used, not
just in computer science but in a range of subject areas, we can look at examples.
 For example, what could algorithmic thinking mean in different situations? To a
computer scientist, it means the study of algorithms and their application to
different problems. To a mathematician, it might mean carrying out long division
factoring or doing carries in addition or subtraction. A scientist might think of it
as the process of doing an experimental procedure.
Some Specific Examples:
Pipelining a graduation ceremony:
 Each person could receive his or her Graduation, then get a handshake from
Principal, and then get his or her picture taken. This pipeline allowed a steady
stream of students to march across the stage (though a pipeline stall occurred
whenever the graduate’s cap would topple while getting handshake from
Principal).

Department of Computer Science & Engineering Page: 1


Computational Thinking and Programming

Predicting climate change:


 Predicting global climate change is only possible because of advanced computer
models. According to the UK Met Office, ‘The only way to predict the day-to-day
weather and changes to the climate over longer timescales is to use computer
models.
Objectives of Computational Thinking:
 To make understood the concept of Computational Thinking and its application
for problem solving.
 To make students develop ideas into flowcharts, algorithms, pseudo code and
convert them into programming language.
Logical Thinking:
Logic:
 logic is a system used for distinguishing between correct and incorrect arguments.
Here the idea of an argument is a chain of reasoning that ends up in a conclusion.
 Logic includes a set of principles that, when applied to arguments, allow us to
demonstrate what is true. Sometimes we wont carry out the logic correctly which
lead us to form wrong conclusions. Since we use computers essentially to
automate our reasoning, we must learn to perform logic correctly before writing
a computer solution.
 In a logical argument, each individual thing you already know (or assume) is called
a premise. A premise is like any ordinary statement you or I might make, except
that it can be evaluated to obtain an answer of ‘true’ or ‘false’. A premise, therefore,
has a truth value.
 Once all the premises are stated, the next step is to analyse them and react
accordingly with a conclusion.
Inductive vs deductive arguments:
 We can categorize arguments based on their certainty. The 2 best known
categories are inductive and deductive.
 A deductive argument is the strongest form of reasoning because its conclusion
necessarily follows from its premises (so long as it has been constructed properly
and the premises are incontrovertibly true).
 A deductive argument can fail in one of two ways.

Department of Computer Science & Engineering Page: 2


Computational Thinking and Programming

 First, one of its premises could turn out to be false. For example:
 Missie is a dog
 All dogs are brown.
 Therefore, Missie is brown.
 Premise 2 is false: not all dogs are brown. Even though the argument
follows it fails because at least one of its premises is false. Any argument
with false premises fails. ‘A is a B; All Bs are C; therefore A is C.
 The second way a deductive argument fails is when the conclusion doesn’t
necessarily follow from the premises. For example:
 All tennis balls are round.
 The Earth is round.
 Therefore, the Earth is a tennis ball.
 This argument fails because of faulty logic. Yes, all tennis balls are round, but so
are lots of other things. In symbolic terms, this argument follows the form, ‘All As
are B; C is B; Therefore C is an A’, but since this is in an invalid form, the argument
is automatically invalid too.
 Inductive Reasoning which deals with Probabilities. The premises in an inductive
argument are not unquestionably true. Rather, we have some level of confidence
in them. The form of the argument doesn’t guarantee that the conclusion is true,
but it probably results in a trustworthy conclusion. For example:
 A bag contains 99 red balls and one black ball.
 100 people each drew one ball from the bag.
 Sarah is one of those 100 people.
 Therefore, Sarah probably drew a red ball.
 This is a perfectly fine inductive argument, so long as you acknowledge the aspect
of probability involved.
 The answer a computer gives is only as reliable as its reasoning, and since a
computer is automating your reasoning, we should make sure:
 that reasoning is valid;
 you give the computer reliable input;
 you know how to interpret what conclusion the computer reports, that is,
is the result unquestionably true (the reasoning was deductive) or
probably true (the reasoning was inductive)?

Department of Computer Science & Engineering Page: 3


Computational Thinking and Programming

Problem-Solving Elements:
Algorithm:
An algorithm is a sequence of clearly defined steps that describe a process to follow a
finite set of unambiguous instructions with clear start and end points.
Characteristics/Properties of an Algorithm:
Donald Ervin Knuth has given a list of five properties for an algorithm, these properties
are:
1. Finiteness:
 An algorithm must always terminate after a finite number of steps.
 It means after every step one reach closer to solution of the problem and after
a finite number of steps algorithm reaches to an end point.
2. Definiteness:
 Each step of an algorithm must be precisely defined. It is done by well thought
actions to be performed at each step of the algorithm.
 Also, the actions are defined unambiguously for each activity in the algorithm.
3. Input:
 Any operation you perform need some beginning value/quantities associated
with different activities in the operation.
 So, the value/quantities are given to the algorithm before it begins.
4. Output:
 One always expects output/result (expected value/quantities) in terms of
output from an algorithm.
 The result may be obtained at different stages of the algorithm.
 If some result is from the intermediate stage of the operation, then it is known
as an intermediate result and the result obtained at the end of the algorithm
is known as the end result.
 The output is expected value/quantities always have a specified relation to
the inputs.

Department of Computer Science & Engineering Page: 4


Computational Thinking and Programming

5. Effectiveness:
 Algorithms to be developed/written using basic operations. Actually,
operations should be basic, so that even they can in principle be done exactly
and in a finite amount of time by a person, by using paper and pencil only.

Advantages of the algorithm:


 It is a step-wise representation of a solution to a given problem, which makes
it easy to understand.
 An algorithm uses a definite procedure.
 It is not dependent on any programming language, so it is easy to understand
for anyone even without programming knowledge.
 Every step in an algorithm has its own logical sequence so it is easy to debug.
 By using an algorithm, the problem is broken down into smaller pieces or
steps hence, it is easier for a programmer to convert it into an actual program

Disadvantages of the algorithm:


 Writing the algorithm takes a long time.
 An Algorithm is not a computer program, it is rather a concept of how a
program should be.

Department of Computer Science & Engineering Page: 5


Computational Thinking and Programming

Flowcharts:
 A graphical tool that diagrammatically depicts the steps and structure of an
algorithm or program.
Flowchart Symbols/Notations:
The following are the basic Notations:

Department of Computer Science & Engineering Page: 6


Computational Thinking and Programming

General Rules for flowcharting:


1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other
entry points. The exit point for all flowchart symbols is on the bottom except
for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the
bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow
can be shown as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
a. From one page to another page
b. From the bottom of the page to the top of the same page.
c. An upward flow of more than 3 symbols
6. Subroutines and Interrupt programs have their own and independent
flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt
programs or subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop

Advantages:
 Conveys better meaning
 Analyses the problem effectively
 Good tool for documentation
 Provide a guide for coding
 Systematic debugging
 Systematic testing

Disadvantages:
 Takes more time to draw. Imagine developing a detailed flowchart for a
program containing more number of lines or statements of instructions
 Difficult to make changes
 Non-standardization – No standards to determine amount of details should be
included in a flowchart

Department of Computer Science & Engineering Page: 7


Computational Thinking and Programming

Example:
1. Draw a flowchart for finding the maximum among two numbers

Department of Computer Science & Engineering Page: 8


Computational Thinking and Programming

Pseudocode:
 Pseudocode is an informal way of programming description that does not require
any strict programming language syntax or underlying technology considerations.
 It is used for creating an outline or a rough draft of a program.
 Pseudocode summarizes a program’s flow but excludes underlying details.
 System designers write pseudocode to ensure that programmers understand a
software project's requirements and align code accordingly.

How to Write Pseudocode Statements:?


1. A computer can receive the information
i. Read (information from a file)
ii. Get (information from the keyboard)
2. A computer can put out information
3. A computer can perform arithmetic Use actual mathematical symbols or the
words for the symbols
4. A computer can assign a value to a piece of data
i. to give data an initial value Initialize, Set
ii. to assign a value as a result of some processing „=‟ *x=5+y
iii. to keep a piece of information for later use Save, Store
5. A computer can compare two piece of information and select one of two
alternative actions
i. IF condition THEN
ii. some action
iii. ELSE
iv. alternative action
v. ENDIF
6. A computer can repeat a group of actions
i. WHILE condition (is true)
 some action
ii. ENDWHILE
iii. FOR a number of times
 some action
iv. ENDFOR

Department of Computer Science & Engineering Page: 9


Computational Thinking and Programming

Example for Pseudo code:


 Pseudo code to Calculate Area and Perimeter of Square
1. BEGIN
2. int side, area, perimeter;
3. read side;
4. area=side*side;
5. perimeter=4*side;
6. print area;
7. print perimeter;
8. END
 Pseudocode for finding Greatest among 3 Numbers
1. BEGIN
2. READ a, b, c
3. IF (a>b) THEN
4. IF(a>c) THEN
5. DISPLAY a is greater
6. ELSE
7. DISPLAY c is greater
8. END IF
9. ELSE
10. IF(b>c) THEN
11. DISPLAY b is greater
12. ELSE
13. DISPLAY c is greater
14. END IF
15. END IF
16. END

Department of Computer Science & Engineering Page: 10


Computational Thinking and Programming

Basic Structure of C Language:


1. Documentation Section:
a. It consists of a set of comment lines.
b. This comment lines contains the Name of the program, the author and
other related information.
2. Link Section:
a. It provides instructions to the compiler to link functions from the system
library.
3. Definition Section:
a. Definition section will define all symbolic constants.
4. Global Declaration Section:
a. In this section we define some variables of functions so that these variables
and functions can be used throughout the program anywhere.
5. Main Function Section: -
a. This section is present in any C Program.
b. Main function section is very important because the program execution
begins from here.
c. It contains two parts
i. Declaration Part
ii. Executable Part.
1. Declaration Part: Here we declare variables that will be used
in executable part
2. Executable Part: Contains statements which do some
processing.
d. The Declaration part and executable part should appear between the
opening and closing braces.
e. All the statements in the declaration and executable parts end with a
semicolon.
6. Sub Program Section: -
a. This section contains all the user defined functions that are called in the
main function.
b. User- defined functions are generally placed immediately after the main
function, although they may appear in any order.

Department of Computer Science & Engineering Page: 11


Computational Thinking and Programming

Note:
 In every C Program main function section is Mandatory.
 Remaining sections are optional sections. If you have to use, then declare them
otherwise no need to use these sections.
Creating and Running Programs:
You can use an IDE to write and run the C program by following these steps:
 Step 1: Open turbo C IDE (Integrated Development Environment), click on File
and then click on New.

 Step 2: Write the C program code.

Department of Computer Science & Engineering Page: 12


Computational Thinking and Programming

 Step 3: Click on Compile or press Alt + F9 to compile the code.

 Step 4: Click on Run or press Ctrl + F9 to run the code.

 Step 5: And turbo C will open the console to show you the output of the program.

Department of Computer Science & Engineering Page: 13


Computational Thinking and Programming

Step 1: Creating a Source Code


 Source code is a file with C programming instructions in a high-level language. To
create source code, we use any text editor to write the program instructions. The
instructions written in the source code must follow the C programming language
rules. The following steps are used to create a source code file in Windows OS…
• Click on the Start button
• Select Run
• Type cmd and press Enter
• Type cd c:\TC\bin in the command prompt and press Enter
• Type TC press Enter
• Click on File -> New in C Editor window
• Type the program
• Save it as FileName.c (Use shortcut key F2 to save)
Step 2: Compile Source Code (Alt + F9)
 The compilation is the process of converting high-level language instructions into
low-level language instructions. We use the shortcut key Alt + F9 to compile a C
program in Turbo C.
 The compilation is the process of converting high-level language instructions into
low-level language instructions.
 Whenever we press Alt + F9, the source file is going to be submitted to the
Compiler. On receiving a source file, the compiler first checks for the Errors. If
there are any Errors then compiler returns List of Errors, if there are no errors
then the source code is converted into object code and stores it as a file with .obj
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 a .exe extension.
Step 3: Executing / Running Executable File (Ctrl + F9)
 After completing compilation successfully, an executable file is created with a .exe
extension. The processor can understand this .exe file content so that it can
perform the task specified in the source file.
 We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9,
the .exe file is submitted to the CPU. On receiving .exe file, CPU performs the task

Department of Computer Science & Engineering Page: 14


Computational Thinking and Programming

according to the instruction written in the file. The result generated from the
execution is placed in a window called User Screen.
Step 4: Check Result (Alt + F5)
 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. We use the
shortcut key Alt + F5 to open the User Screen and check the result.

Execution Process of a C Program


When we execute a C program it undergoes with the following process…
 The file which contains c program instructions in a high-level language is said to
be source code. Every c program source file is saved with .c extension, for example,
Sample.c.
 Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler
checks for the errors, if there are any errors, it returns a list of errors otherwise
generates object code in a file with name Sample.obj and submit it to the linker.
The linker combines the code from specified header file into an object file and
generates executable file as Sample.exe. With this compilation process completes.
 Now, we need to run the executable file (Sample.exe). To run a program we press
Ctrl + F9. When we press Ctrl + F9 the executable file is submitted to the CPU. Then
CPU performs the task according to the instructions written in that program and
place the result into User Screen.
 Then we press Alt + F5 to open User Screen and check the result of the program.

Execution process of a C Program

Department of Computer Science & Engineering Page: 15


Computational Thinking and Programming

Variables:
 A data name which is used to store a Data value is a Variable.
 A Variable takes different values at different times during program execution.
 A Variable name should be chosen by the programmer in a meaningful way so as
to reflect its function in the program.
 Rules to Name a Variable: -
 Variable names may consists of letters, digits, and the underscore (_ )
symbol.
 They must begin with a letter or underscore (_ ) as the first character.
 ANSI standard recognizes a length of 31 characters.
 But, many compilers treat the first eight characters as significant.
 Uppercase and lowercase are significant.
 Name should not be a KEYWORD OF C.
 White space is not allowed.
 Example:
 int total; // is a valid name to variable
 total = 100;
 total is Data name , 10 is Data value
Data Types in C:
 A data type in C refers to the type of data used to store the information. For
example, the name of a person would be an array of characters, while the age will
be in integers. Whereas, the marks of a student would require a data type that can
store decimal values.
Type Data types
Basic data types int, char, float, & double
Derived data types array, pointer, structure, & union, enum, typedef
Void data type void

Basic Data Types


 In C language, basic data types are used to store values in integer and decimal
forms. It supports both signed and unsigned literals. There are four basic data
types, in both signed and unsigned forms:
 Int

Department of Computer Science & Engineering Page: 16


Computational Thinking and Programming

 Float
 Double
 Char
 The memory size of these data types can change depending on the operating
system (32-bit or 64-bit). Here is the table showing the data types commonly used
in C programming with their storage size and value range, according to the 32-bit
architecture.
Storage
Type Value Range
Size
Int (or signed int) 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
Short int(or signed short
2 bytes -32,768 to 32,767
int)
Long(or singed short int) 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
float 4 bytes 1.2E-38 to 3.4E+38 (6 decimal places)
double 8 bytes 2.3E-308 to 1.7E+308 (15 decimal places)
3.4E-4932 to 1.1E+4932 (19 decimal
Long double 10 bytes
places)
char(or signed char) 1 byte -128 to 127
unsigned char 1 byte 0 to 255

Integer Data Type


 An integer type variable can store zero, positive, and negative values without any
decimal. In C language, the integer data type is represented by the ‘int’ keyword,
and it can be both signed or unsigned. By default, the value assigned to an integer
variable is considered positive if it is unsigned.
 The integer data type is further divided into short, int, and long data types. The
short data type takes 2 bytes of storage space; int takes 2 or 4 bytes, and long takes
8 bytes in 64-bit and 4 bytes in the 32-bit operating system.
 If you try to assign a decimal value to the integer variable, the value after the
decimal will be truncated, and only the whole number gets assigned to the
variable. Here is an example that will help you understand more about the
concept.

Department of Computer Science & Engineering Page: 17


Computational Thinking and Programming

Program:
#include<stdio.h>
int main()
{
short int a=10000;
int b=11252486;
long num1=499962313469;
long long num2=51454456154585454;
printf("a is %hd\n b is %d\n num1 is %ld\n num2 is
%lld\n",a,b,num1,num2);
return 0;
}
Output:
a is 10000
b is 11252486
num1 is 1746107133
num2 is 51454456154585454
 While doing an arithmetic operation, if the result comes out to be a decimal value,
the variable will only accept the whole number and discard the numbers after the
decimal point. For short int, an incorrect value will be displayed if the number is
bigger than 10000.
Float-pointing Data Types
 The floating-point data type allows a user to store decimal values in a variable. It
is of two types:
 Float
 Double
Float
 Float variables store decimal values with up to 6 digits after the decimal place. The
storage size of the float variable is 4 bytes, but the size may vary for different
processors, the same as the ‘int’ data type.
 In C language, the float values are represented by the ‘%f’ format specifier. A
variable containing integer value will also be printed in the floating type with
redundant zeroes. It will be clear for you from the example given below:

Department of Computer Science & Engineering Page: 18


Computational Thinking and Programming

Program:
#include<stdio.h>
int main() {
float sum=9664.35;
float num=67;
float average=(sum/num);
printf("Average is %f \n", average);
printf("Value of num is %f \n",num);
printf("Value of num presented as an integer %d \n",num);
}
Output:
Average is 144.244019
Value of num is 67.000000
Value of num presented as an integer 0
 If you assign an integer value to a float variable, the result will always be a float
value with zeroes after the decimal place. As mentioned, float values are
represented by the ‘%f’ format specifier. However, if you try to print float values
with ‘%d’, then the output will not be 67 in the above case. Instead, you will see a
garbage value on the output screen.
Double:
 The double data type is similar to float, but here, you can have up to 10 digits after the
decimal place. It is represented by the ‘double’ keyword and is mainly used in scientific
programs where extreme precision is required.

 In the example below, the double variable prints the exact value ‘349999999.454’,
while the float variable messes up with the number and prints a round-off value.
Program:
#include<stdio.h>
int main()
{
float score=349999999.454;
double average=349999999.454;

Department of Computer Science & Engineering Page: 19


Computational Thinking and Programming

printf("Score in %f \n",score);
printf("Average is %lf",average);
return 0;
}
Output:
Score in 350000000.000000
Average is 349999999.454000
Char:

 Char is used to storing single character values, including numerical values. If you
create an array of the character data type, it becomes a string that can store values
such as name, subject, and more.

#include<stdio.h>
int main()
{
char group='A';
// to store a string of characters in C programming, we use the array of the
characters
char name[30]="student";
printf("The group is %c \n",group);
printf("The name is %s",name);
return 0;
}
Output:
The group is A
The name is student

Derived Data Types:


 The primitive or basic data types are used to store single values of different forms,
but what if you need to store more values of the same data type? Here, derived
data types allow you to combine the basic data types and store multiple values in
a single variable.

Department of Computer Science & Engineering Page: 20


Computational Thinking and Programming

 Derived data types are defined by the user itself, which means that you can
aggregate as many elements of similar data types as required. There are four types
of derived data types:
 Array
 Pointer
 Structure
 Union
Array
 An array is a collection of similar data-type elements stored in a contiguous
memory location. For example, you can store float values like the marks of a
student, integer values like the roll number, and so on.
Program:
#include<stdio.h>
int main()
{
int ar[]={7,5,3,8,9};
int i,j;
float sum=0,average=0;
printf("The array elements are: \n");
for(i=0;i<5;i++){
printf("%d \t",ar[i]);
}
int marks[5];
printf("\nEnter Marks: \n");
for(j=0;j<5;j++)
{
scanf("%d",&marks[i]);
sum =sum + marks[i];
}
average=(sum/5);
printf("The average is %f",average);
return 0;
}

Department of Computer Science & Engineering Page: 21


Computational Thinking and Programming

Output:
The array elements are:
7 5 3 8 9
Enter Marks:
1
2
3
4
5
The average is 3.000000
 In the above example, the array either needs to be initialized or have the size while
declaring it. The size of the array will depend on the data type you are using. Also,
the default value of an integer array will be zero.
 For accessing or changing specific elements in the program, marks[i] is used
where ‘marks’ is the array name, in which ‘[i]’ denotes the position of the element.

Pointer
 Pointer is a variable used to store the address of another variable. To store the
address of a variable, the pointer variable should be of the same data type.
 Pointer enables a user to perform dynamic memory allocation in C language and
also pass variables by reference, which means that the user can pass the pointer
having the address of the variable.
 A pointer with no address is known as the null pointer, while a pointer with no
data type is called a void or general-purpose pointer.

Program:
#include<stdio.h>
int main()
{
int *ptr1;
int *ptr2;
int x=5,y=10;

Department of Computer Science & Engineering Page: 22


Computational Thinking and Programming

ptr1=&x; //Address of x assigned to ptr1


ptr2=&y; //address of y assigned to ptr2
printf(" Value of ptr1 %d", *ptr1);
printf("\n Value of ptr2 %d", *ptr2);
printf("\n Address of variable x %d",ptr1);
printf("\n Address of variable y %d",ptr2);
int add=(*ptr1 + *ptr2);
printf("\n Addition of x and y using ptr1 and ptr2 %d",add);
return 0;
}
Output:
Value of ptr1 5
Value of ptr2 10
Address of variable x 6487560
Address of variable y 6487556
Addition of x and y using ptr1 and ptr2 15
 In C language, the difference operator ‘&’ is used to assign the address of a variable
to the pointer. To access the value stored in the address that the pointer is
referring to, you should use the ‘*’ operator.
Structure:
 In C language, a structure is a user-defined data type, which is a group of items
used to store the values of similar or different data types. For example, structures
can be used to store information about a student, including the name, the roll
number, marks, and more. The record of each student will be represented by an
object of the structure.
 A structure can be created inside as well as outside the main method. To define a
structure, the keyword ‘struct’ is used as shown in the below program. The size of
the structure would be the sum of the storage size required by every variable.
Program:
#include<stdio.h>
struct student{
char *name;
int roll_no;

Department of Computer Science & Engineering Page: 23


Computational Thinking and Programming

float avg_marks;
};
int main()
{
struct student obj;
obj.name="Steve";
obj.roll_no=25;
obj.avg_marks=85.32;
printf("Student name is %s",obj.name);
printf("\nStudent Roll No is %d",obj.roll_no);
printf("\nStudent Average marks are %f",obj.avg_marks);
return 0;
}
Output:
Student name is Steve
Student Roll No is 25
Student Average marks are 85.320000

Union:
 Union is also a collection of elements with similar or different data types, but the
memory location is the same for all the elements. It is a special kind of data type
in C language, where you can declare many variables, but only one variable can
store the value at a given time.
 Union is defined by the ‘union’ keyword, where each object will represent a single
record. The size of a union will be equal to the memory needed for the largest
variable inside it.

Program:
 Union is also a collection of elements with similar or different data types, but the
memory location is the same for all the elements. It is a special kind of data type
in C language, where you can declare many variables, but only one variable can
store the value at a given time.

Department of Computer Science & Engineering Page: 24


Computational Thinking and Programming

 Union is defined by the ‘union’ keyword, where each object will represent a single
record. The size of a union will be equal to the memory needed for the largest
variable inside it.
#include<stdio.h>
union Data{
char *name;
int roll_no;
float avg_marks;
};
int main() {
union Data ob;
ob.name="George";
printf("Student name = %s",ob.name);
ob.roll_no=5;
printf("\nRoll No = %d",ob.roll_no);
ob.avg_marks=82.5;
printf("\nAverage Marks = %f",ob.avg_marks);

printf("\nRoll Number = %d",ob.roll_no);


return 0;
}
Output:
Student name = George
Roll No = 5
Average Marks = 82.500000
Roll Number = 1118109696

 In the above example, the union student has three variables, name, roll no, and
marks. The variable name can have a maximum of 25 characters, which means that
the size would be 25 bytes. Similarly, roll no will have 4 bytes, and the average
marks will also have 4 bytes.
 Since the variable with maximum storage size here is ‘name’, the size of the union
student will be 25 bytes. If the variable ‘name’ has some value in it and you assign

Department of Computer Science & Engineering Page: 25


Computational Thinking and Programming

a value to the roll no, the value in the ‘name’ will be replaced by the ‘roll no’ in the
memory.

Enumeration Data Type:


 Enumeration is a user-defined data type used to assign names to the integral
constants and enhance the readability of your program. The keyword used for
enumeration is ‘enum’ with a syntax similar to structure:
enum flag{const1, const2, const3……...};
 There are two main reasons why enumerations are better than '#define':
 Enum constants get default values by the compiler
 They can be declared in the local scope
Program:
#include<stdio.h>
enum week{Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,Sunday};
int main(){
int i;
printf("Value of Wednesday %d",Wednesday);
enum week day;
day=Saturday;
printf("\n Value stored in the variable day %d",day);
printf("\n The value of each enum constant: \n");
for(i=Monday;i<=Sunday;i++)
{
printf("%d \t",i);
}
return 0;
}

Output:
Value of Wednesday 2
Value stored in the variable day 5
The value of each enum constant:
0 1 2 3 4 5 6

Department of Computer Science & Engineering Page: 26


Computational Thinking and Programming

 In the above example, the flag ‘week’ is now a data type with Monday, Tuesday,
Wednesday, and so on as the integral constants. If you do not assign any value to
the enum constant, then const1 will be 0, const2 will be 1, and so on. You can also
define other variables with this enum data type as mentioned in the program.

Void Data Type


 Void is a data type in C language that does not refer to any value of any type. It is
mostly used as the return type in functions. You can declare the void pointers to
take the address of variables from any data type. These pointers are often called
‘generic pointers.’
Program:
#include<stdio.h>
void addition(int a, int b);
int main(){
int x=10;
int y=20;
addition(x,y);
void *ptr;
ptr=&x;
printf("\n Value stored in pointer(ptr) after dereferencing %d",*((int
*)ptr));
return 0;
}
void addition(int a,int b){
int sum=a+b;
printf("The sum of x and y is %d",sum);
}

Output:
The sum of x and y is 30
Value stored in pointer(ptr) after dereferencing 10

Department of Computer Science & Engineering Page: 27


Computational Thinking and Programming

 In this example, the function named ‘addition’ has void as the return type, which
means that it will not return any value to the main method. So, the user has to print
the message inside the function body or write a different return type.
 In the main method, the void pointer ‘ptr’ acts as a generic pointer used to store
the address of a variable of any data type. The output clearly shows that the ptr
value changes from some garbage value to the value stored in the address it is
pointing to (in this case, the value of the variable x).

Input / Output Statements:


 In C Language input and output function are available as C compiler functions or
C libraries provided with each C compiler implementation. These all functions are
collectively known as Standard I/O Library function.
 Here I/O stands for Input and Output used for different inputting and outputting
statements. These I/O functions are categorized into three processing functions.
 Console input/output function (deals with keyboard and monitor),
 disk input/output function (deals with floppy or hard disk), and
 port input/output function (deals with a serial or parallel port).
 As all the input/output statements deals with the console, so these are also
Console Input/Output functions. Console Input/Output function access the three
major files before the execution of a C Program. These are as follows:

 stdin: This file is used to receive the input (usually is keyborad file, but can also
take input from the disk file).
 stdout: This file is used to send or direct the output (usually is a monitor file, but
can also send the output to a disk file or any other device).
 stderr: This file is used to display or store error messages.

Department of Computer Science & Engineering Page: 28


Computational Thinking and Programming

Input Output Statement


 Input and Output statement are used to read and write the data in C programming.
These are embedded in stdio.h (standard Input/output header file).
 Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.C
programming language provides many built-in functions to read any given input
and to display data on screen when there is a need to output the result.
 There are mainly two of Input/output functions are used for this purpose. These
are discussed as:
 Unformatted I/O functions
 Formatted I/O functions

Unformatted I/O functions:


 There are mainly six unformatted I/O functions discussed as follows:
 getchar()
 putchar()
 gets()
 puts()
 getch()
 getche()

 getchar()
 This function is an Input function. It is used for reading a single character
from the keyboard. It is a buffered function. Buffered functions get the
input from the keyboard and store it in the memory buffer temporally until
you press the Enter key.
 The general syntax is as:
 v = getchar();
 where v is the variable of character type. For example:
 char n;
 n = getchar();

Department of Computer Science & Engineering Page: 29


Computational Thinking and Programming

Example:
/*To read a single character from the keyboard using the getchar()
function*/
#include <stdio.h>
main()
{
char n;
n = getchar();
}
 putchar()
 This function is an output function. It is used to display a single character
on the screen. The general syntax is as:
 putchar(v);
 where v is the variable of character type. For example:
 char n;
 putchar(n);
Example:
/*Program illustrate the use of getchar() and putchar() functions*/
#include <stdio.h>
main()
{
char n;
n = getchar();
putchar(n);
}
 gets ()
 This function is an input function. It is used to read a string from the
keyboard. It is also a buffered function. It will read a string when you type
the string from the keyboard and press the Enter key from the keyboard. It
will mark null character (‘\0’) in the memory at the end of the string when
you press the enter key. The general syntax is as:
 gets(v);
 where v is the variable of character type. For example:

Department of Computer Science & Engineering Page: 30


Computational Thinking and Programming

 char n[20];
 gets(n);

Example:
/*Program to explain the use of gets() function*/
#include <stdio.h>
main()
{
char n[20];
gets(n);
}
 puts()
 This is an output function. It is used to display a string inputted by gets()
function. It is also used to display a text (message) on the screen for
program simplicity. This function appends a newline (“\n”) character to
the output.
 The general syntax is as:
 puts(v);
or
 puts("text line");
 where v is the variable of character type.
Example:
/*Program to illustrate the concept of puts() with gets() functions*/
#include <stdio.h>
main()
{
char name[20];
puts("Enter the Name");
gets(name);
puts("Name is :");
puts(name);
}

Department of Computer Science & Engineering Page: 31


Computational Thinking and Programming

 getch()
 This is also an input function. This is used to read a single character from
the keyboard like getchar() function. But getchar() function is a buffered is
function, getchar() function is a non-buffered function. The character data
read by this function is directly assigned to a variable rather it goes to the
memory buffer, the character data is directly assigned to a variable without
the need to press the Enter key.
 Another use of this function is to maintain the output on the screen till you
have not press the Enter Key. The general syntax is as:
 v = getch();
 where v is the variable of character type.
 Example:
/*Program to explain the use of getch() function*/
#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getch();
puts("Char is :");
putchar(n);
getch();
}
 getche()
 All are same as getch(0 function execpt it is an echoed function. It means
when you type the character data from the keyboard it will visible on the
screen. The general syntax is as:
 v = getche();
 where v is the variable of character type.
/*Program to explain the use of getch() function*/
#include <stdio.h>
main()
{
char n;
puts("Enter the Char");
n = getche();
puts("Char is :");

Department of Computer Science & Engineering Page: 32


Computational Thinking and Programming

putchar(n);
getche();
}
 Formatted I/O functions:
 Formatted I/O functions which refers to an Input or Ouput data that has
been arranged in a particular format. There are mainly two formatted I/O
functions discussed as follows:
 scanf()
 printf()
 scanf()
 The scanf() function is an input function. It used to read the mixed type of
data from keyboard. You can read integer, float and character data by using
its control codes or format codes. The general syntax is as:
 scanf("control strings",arg1,arg2,..............argn);
or
 scanf("control strings",&v1,&v2,&v3,................&vn);
 Where arg1,arg2,……….argn are the arguments for reading and
v1,v2,v3,……..vn all are the variables.
 The scanf() format code (spedifier) is as shown in the below table:
Format Code Meaning
%c To read a single character
%d To read a signed decimal integer (short)
%ld To read a signed long decimal integer
%e To read a float value exponential
%f To read a float (short0 or a single precision value
%lf To read a double precision float value
%g To read double float value
%h To read short integer
%i To read an integer (decimal, octal, hexadecimal)
%o To read an octal integer only
%x To read a hexadecimal integer only
%u To read unsigned decimal integer (used in pointer)
%s To read a string
%[..] To read a string of words from the defined range
%[^] To read string of words which are not from the defined range

Department of Computer Science & Engineering Page: 33


Computational Thinking and Programming

Operators in C:
Operator: An operator is simply a symbol that is used to perform operations on
Operands.

Operand: An operand is a Data value on which any operator works.

Types of Operators:

C supports 8 types of Operators. The following are the operators

1. ARITHMETIC OPERATORS:
 The purpose of this operator is to perform mathematical operations like
addition, subtraction, division, multiplication etc.

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

Modulus Operator and remainder of after an integer


% B%A=0
division.

2. ASSIGNMENT OPERATORS:
 Assignment operators are used to assign the result of an Expression to a
variable.
 The Symbol of this operator is =.
 C has set of short hand assignment operators of the form V OP = EXP;

V --Variable
OP -C Binary Arithmetic Operator
EXP-- Expression

Department of Computer Science & Engineering Page: 34


Computational Thinking and Programming

Example :- x = x+(y+1);
 The above expression can be written in short form as x += y+1.
 The following are some of the short hand assignment operators in C:-
+=,-=,*=,/=,%= Etc….
Advantages of Assignment Operators: -
 What appears on the left hand side need not be repeated and therefore, it
becomes easier to write.
 The statement is more concise and easy to read.
 The statement is more efficient.

Operator Description Example

= Simple assignment operator.


C = A + B will assign the value of A
Assigns values from right side
+ B to C
operands to left side operand

+= Add AND assignment operator. It


adds the right operand to the left
C += A is equivalent to C = C + A
operand and assign the result to the
left operand.

-= Subtract AND assignment operator.


It subtracts the right operand from
C -= A is equivalent to C = C - A
the left operand and assigns the
result to the left operand.

*= Multiply AND assignment operator.


It multiplies the right operand with
C *= A is equivalent to C = C * A
the left operand and assigns the
result to the left operand.

/= Divide AND assignment operator. It


divides the left operand with the
C /= A is equivalent to C = C / A
right operand and assigns the result
to the left operand.

Department of Computer Science & Engineering Page: 35


Computational Thinking and Programming

%= Modulus AND assignment operator.


It takes modulus using two
C %= A is equivalent to C = C % A
operands and assigns the result to
the left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment C >>= 2 is same as C = C >> 2


operator.

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and C ^= 2 is same as C = C ^ 2


assignment operator.

|= Bitwise inclusive OR and C |= 2 is same as C = C | 2


assignment operator.

3. BITWISE OPERATORS:
 C uses an operator (s) for manipulation of data at bit-level know as
Bitwise Operators.
 These Operators are used for testing the bits, or shifting them right to left.
 These cannot be applied to float or double.
 The following are the bitwise operators used in C language.

Department of Computer Science & Engineering Page: 36


Computational Thinking and Programming

1. Bitwise AND (&):


 This operator takes two bits as I/P and generate O/P.
 The bits may be 0 or 1.
 If both I/P bits are 1(TRUE) Then it Generate 1(TRUE) as O/P.
If any one I/P bit is 0 then it generates 0(FALSE) as O/p.
 The following is the table which shows how bitwise AND
works.
X(Input) Y(Input) X&Y (O/P)

0 0 0
0 1 0
1 0 0
1 1 1

EXAMPLE: - What is the Result of 5&3?


 5 when converted to binary form the result is 101
 3 when converted into binary form the result is 011
 Now apply bitwise AND for 101 & 011
1 0 1
&0 1 1
---------
0 0 1
Equals to decimal number 1
2. Bitwise OR (|):
 It takes two bits as I/P and generate O/P.
 The bits may be 0 or 1.
 If any I/P bit is 1(TRUE) Then it Generate 1(TRUE) as O/P.

EXAMPLE :- What is the Result of 5|3?

 5 when converted to binary form the result is 101


 3 when converted into binary form the result is 011
 Now apply bitwise AND for 101 & 011
1 0 1
|0 1 1
---------
1 1 1 ---- Equals to decimal number 7

Department of Computer Science & Engineering Page: 37


Computational Thinking and Programming

 The following is the table which shows how bitwise OR works.


X(Input) Y(Input) X|Y(Output)
0 0 0
0 1 1
1 0 1
1 1 1

3. Bitwise XOR (^):


 The operator takes two bits as Input and generate output. If both
the bits are same then it generates 0(False) output otherwise it
generates 1(True) as output.
 The following is the table which shows how this operator works: -
X(Input) Y(Input) X^Y(Output)
0 0 0
0 1 1
1 0 1
1 1 0

Example: What is the Result Of 5^ 3


 5 Binary equivalent is 101.
 3 Binary Equivalent is 011.
Now 101
^011
-------
1 1 0 ---- which is equal to 6
--------
4. Bitwise left-shift (<<):
 when we apply left shift on a binary number then the bits will
be moved towards left side.
 When bits are moved towards left side then we find empty
positions towards right, that positions should be filled with
0(Zero) bit(s).
 Example how this operator works: -
Suppose assume that 10101(21 is decimal equivalent)
should be left-shifted by one time. Then the bits will be
moved one position left. First write the binary number like
this.

Department of Computer Science & Engineering Page: 38


Computational Thinking and Programming

In the above table the second row indicates position


numbers. Now if we move bits one time left then we see the
following change. The empty position should be filled by 0.
in the below table last position gets empty fill that position
with 0.

 Now we got 101010 which is equivalent to 42. So, given


value will be doubled if we left shift bits one time.
5. Bitwise right-shift (>>):
 when we apply right-shift on a binary number then the bits
will be moved towards right side.
 When bits are moved towards right side then we find empty
positions towards left, that positions should be filled with
0(Zero) bit(s).
 Example how this operator works: -
Suppose assume that 10101(21 is decimal equivalent)
should be right-shifted by one time. Then the bits will be
moved one position right. First write the binary number like
this.

In the above table the second row indicates position


numbers. Now if we move bits one time right then we see the
following change. The empty position should be filled by 0.

Department of Computer Science & Engineering Page: 39


Computational Thinking and Programming

in the below table right position gets empty fill that position
with 0.

 Now we got 01010 which is equivalent to 10. So, given value


will be halfed if we Right-shift bits one time.
6. ones complement (~):
 This operator takes one bit and do complement of it.
 Complement means if the bit given is 0(false) it converts
that bit into 1(true).
 Example: What is the result of ~ (101010).
The decimal equivalent is 42
The complement of 101010(42) is 010101(21).
~ 101010
-------------------
010101
4. Conditional Operator:

Syntax: - condition ? Exp1: Exp2

Working of Conditional operator: -

 It will first evaluate the condition.


 Based on the return value of the condition the second or third operand is
evaluated.
 if the condition is evaluated to true (1) then, only second operand
i.e. Exp1 is evaluated. Then, the operator returns the value of the
Exp1.
 if the condition is evaluated to false (0) then, only the third operand
Exp2 is evaluated and the operator returns the value of the Exp2.
 Example: - Assume that x = 20, y = 10 now evaluate the following
Z = (x>y) ? x : y; [(20>10) ? x : y]

Department of Computer Science & Engineering Page: 40


Computational Thinking and Programming

The result is Z = 20 because the condition is true Exp1 is evaluated


and its value is returned.

“? :” is a ternary operator pair. So, conditional operator is also called


ternary operator.

 Note: Ternary operator is a shorthand of combination of the if-else and


return statement.
5. Decrement/Increment Operators
 This operator is used for incrementing and decrementing the value of
variables by 1.
 Increment operator (++) adds 1 to its operand. Decrement operator (--)
subtract 1 from its operand.
 We can use the operators either as prefix or postfix operators.
 Note:-
 A prefix operator first adds 1 to the operand and then the result is assigned
to the variable on the left.
 A postfix operator first assigns the value to the variable on left and then
increments or decrements the operand.
Example:-
assume that X = 6;
now evaluate Y = ++x and see what is the value of x and y;
X value will be 7 and y value will be 7. because of prefix incrementation.
assume that X = 6;
now evaluate Y = x++ and see what is the value of x and y;
X value will be 7 and Y value will be 6. because of postfix incrementation.

6. Logical operators:
 Logical operators are used to test more than one condition and make
decisions.
 Combining two or more relational expressions is termed as a logical or a
compound relational expression.
 Logical expressions always return an integer.
 if Logical expression is true it returns value 1.

Department of Computer Science & Engineering Page: 41


Computational Thinking and Programming

 if Logical expression is false it returns value 0.


 The following are the Logical Operators used in C language.

1. LOGICAL AND (&&):


 This operator takes two operands as input and decide the
output.
 The operand values may be T(true) or F(false). If both the
operand values are T(true) then the output will be T(true)
otherwise the output becomes F(false).
 The following table shows how the Logical AND works: -
X Y X&&Y
T T T
T F F
F T F
F F F

2. LOGICAL OR (||):
 This operator takes two operands as input and decide the
output.
 The operand values may be T(true) or F(false). If any one
operand value isT(true) then the output will be T(true).
 The following table shows how the Logical OR works: -
X Y X||Y
T T T
T F T
F T T
F F F

Department of Computer Science & Engineering Page: 42


Computational Thinking and Programming

3. LOGICAL NOT (!):


 This operator takes one operand value as input and it negates
the value and returns as output.
 The following table shows how this operator works: -
X !X
T F
F T

7. RELATIONAL OPERATORS:
 We use Relational operators to compare data.
 It is used to check whether two variables (or) Expressions are Equal, not
equal, greater than, less than, less than equal to, greater than equals to.
 These operators are used in boolean conditions (or) expressions to return 0
or 1.
 The following figure shows different relational operators of C.

Operator Description Example

Checks whether the two given operands are equal or


Equal To == x==y
not. If yes, it returns true else false

Not Equal To Checks whether the two given operands are equal or
x!=y
!= not. If not, it returns true else false.

Greater Than Checks whether the first operand is greater than the
x>y
> second operand or not.

Department of Computer Science & Engineering Page: 43


Computational Thinking and Programming

Less Than Checks whether the first operand is lesser than the
x<y
< second operand.

Greater than or Checks whether the first operand is greater than or


x>=y
equal to equal to the second operand.
>=
Less than or Checks whether the first operand is less than or equal
x<=y
equal to to the second operand.
<=

8. SPECIAL OPERATORS:
The following are the different special operators we use in C
1) The Comma Operator
2) Type cast Operator
3) Reference operator or Address Operater ("&")
4) Dereference operator ("*") or Pointer Operater
5) Double Pointer operator ("**")
6) sizeof operator

1. Comma Operator:
 The Comma operator can be used to link the related expressions
together.
Example: int a,b,c;
 Comma Operator In for Loops
for(i=0,j=1;i>10:i++,j++)

2. Type cast Operator (type):


 converts a to the specified type.
 Note that the use of a parenthesized type in a method declaration or
definition is not an example of the use of the type cast operator.
 Example:

float s= 12.5; int a;


a = (int) s;
now a value is 12.
3. Reference operator or Address Operator ("&"):

Department of Computer Science & Engineering Page: 44


Computational Thinking and Programming

The reference operator noted by ampersand ("&"), is also a unary operator in


c languages that uses for assign address of the variables. It returns the pointer
address of the variable. This is called "referencing" operator.
Syntax:
data_type x;
data_type *pt;
pt = &x

Precedence of operators:
 In programming we use Expressions which are evaluated using an assignment
statement of the form:

Variable = Expression;

 The combination of operands and operators is known as Expression.


 The following are the rules for evaluation of Expression.
 First, parenthesized sub-expression from left to right are
evaluated.
 If parantheses are nested, the evaluation begins with the
innermost sub-expression.
 The precedence rule is applied in determining the order of
application of operators in evaluating sub-expression.
 The associativity rule is applied when two or more operators of
the same precedence level appear in a sub-expression.
 Arithmetic expressions are evaluated from left to right using the
rules of precedence.
 When parantheses are used, the expressions within parantheses
assume highest priority.
What do you mean by Precedence?
 PRECEDENCE is a process used to determine how an expression involving more
than one operator is evaluated.

 There are distinct levels of precedence and an operator may belong to one
of these levels.
 The operators at the higher level of precedence are evaluated first.
 The operators of the same precedence are evaluated either from Left to
Right or from Right to Left depending on the level.

Department of Computer Science & Engineering Page: 45


Computational Thinking and Programming

What do you mean by Associativity?


 ASSOCIATIVITY is a process used to define the order in which the operators of
the same precedence will be evaluated in an expression. Also, associativity can
occur from either right to left or left to right.

Operators Precedence & Associativity Table

Operator Meaning of operator Associativity

() Functional call
[] Array element reference
Left to right
-> Indirect member selection
. Direct member selection

! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
Right to left
-- Decrement
& Dereference (Address)
* Pointer reference
sizeof Returns the size of an object
(type) Typecast (conversion)

* Multiply
/ Divide Left to right
% Remainder

+ Binary plus(Addition)
Left to right
- Binary minus(subtraction)

<< Left shift


Left to right
>> Right shift

< Less than


<= Less than or equal
Left to right
> Greater than
>= Greater than or equal

== Equal to
Left to right
!= Not equal to

& Bitwise AND Left to right

Department of Computer Science & Engineering Page: 46


Computational Thinking and Programming

^ Bitwise exclusive OR Left to right

| Bitwise OR Left to right

&& Logical AND Left to right

|| Logical OR Left to right

?: Conditional Operator Right to left

= Simple assignment
*= Assign product
/= Assign quotient
%= Assign remainder
+= Assign sum
-= Assign difference Right to left
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift

, Separator of expressions Left to right

Type Casting and Conversion in C:


 In a programming language, the expression contains data values of the same
datatype or different data types.
 When the expression contains similar datatype values then it is evaluated without
any problem.
 But if the expression contains two or more different datatype values then they
must be converted to the single datatype of destination datatype. Here, the
destination is the location where the final result of that expression is stored.
 In a c programming language, the data conversion is performed in two different
methods as follows...
 Implicit Type Conversion
 Explicit Type Conversion

Department of Computer Science & Engineering Page: 47


Computational Thinking and Programming

Implicit 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.
 Implicit type conversion is called as type coercion.
 The implicit type conversion is automatically performed by the compiler.
Example:
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
i = x ; ==> x value 15.5 is converted as 15 and assigned to variable i
x = i ; ==> Here i value 10 is converted as 10.000000 and assigned to variable x
i = ch ; ==> Here the ASCII value of A (65) is assigned to i
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;
i=x;
printf("i value is %d\n",i);
x=i;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);
}
Output:
i value is 90
x value is 90.000000
i value is 65

Department of Computer Science & Engineering Page: 48


Computational Thinking and Programming

 In the above program, we assign i = x, i.e., float variable value is assigned to the
integer variable. Here, the compiler automatically converts the float value (90.99)
into integer value (90) by removing the decimal part of the float value (90.99) and
then it is assigned to variable i. Similarly, when we assign x = i, the integer value
(90) gets converted to float value (90.000000) by adding zero as the decimal part.

Explicit Type Conversion:


 Explicit type conversion is called as Type Casting.
 Compiler converts data from one data type to another data type implicitly. When
compiler converts implicitly, there may be a data loss.
 In such a case, we convert the data from one data type to another data type using
explicit type conversion.
 To perform this we use the unary cast operator. To convert data from one type to
another type we specify the target data type in parenthesis as a prefix to the data
value that has to be converted.
 The general syntax of typecasting is as follows
 (TargetDatatype) DataValue
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int a, b, c ;
printf("Enter any three integer values : ");
scanf("%d%d%d",&a,&b,&c);
printf("avg after casting = %f" ,(float)(a + b + c) / 3);
return 0;
}
Output:
Enter any three integer values : 10
20
30
avg after casting = 20.000000

Department of Computer Science & Engineering Page: 49

You might also like