Computational Thinking and Programming Unit-I PDF
Document Details
Uploaded by NavigableMetaphor
Tags
Summary
This document provides an introduction to computational thinking and programming, covering topics such as logical and algorithmic thinking, algorithms, and flowcharting. The document also discusses the basics of the C Programming language, including variables, data types, and fundamental concepts like input and output, operators, and precedence.
Full Transcript
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 characteristic...
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 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 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 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 int main() { char group='A'; // to store a string of characters in C programming, we use the array of the characters char name="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 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;i10) ? 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 equal to equal to the second operand. >= Less than or Checks whether the first operand is less than or equal x 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) > Right shift < Less than 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 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 #include 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 #include 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