CTP Unit-1 Final
CTP Unit-1 Final
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.
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)?
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.
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.
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:
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
Example:
1. Draw a flowchart for finding the maximum among two numbers
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.
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 5: And turbo C will open the console to show you the output of the program.
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.
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
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
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:
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;
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 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;
}
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;
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.
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);
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
a value to the roll no, the value in the ‘name’ will be replaced by the ‘roll no’ in the
memory.
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
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.
Output:
The sum of x and y is 30
Value stored in pointer(ptr) after dereferencing 10
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).
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.
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();
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:
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);
}
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 :");
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
Operators in C:
Operator: An operator is simply a symbol that is used to perform operations on
Operands.
Types of Operators:
1. ARITHMETIC OPERATORS:
The purpose of this operator is to perform mathematical operations like
addition, subtraction, division, multiplication etc.
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
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.
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.
0 0 0
0 1 0
1 0 0
1 1 1
in the below table right position gets empty fill that position
with 0.
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.
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
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.
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.
Less Than Checks whether the first operand is lesser than the
x<y
< 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++)
Precedence of operators:
In programming we use Expressions which are evaluated using an assignment
statement of the form:
Variable = Expression;
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.
() 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)
== Equal to
Left to right
!= Not equal to
= 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
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.