Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 58

U21CSG01-Problem Solving and C Programming

UNIT I

COMPUTATIONAL THINKING

Computational Thinking – Modern Computer -


Information based Problem solving– Real world information
and Computable Data – Data types and data encoding -
Number Systems – Introduction to programming languages -
Basics of C programming – variables- data types – keywords –
C program structure - simple programs in C
Computational
Thinking
 Computational thinking, often referred to
as CT, is a problem-solving technique that
computer programmers use when writing
computer programs and algorithms.
 In the case of programmers, they break
down complex problems into more bite-
sized pieces, which makes it easier to fully
understand them and develop solutions that
work for both computers and humans.
 Computational thinking helps us break
down any given problem in a systematic
manner, which enables us to develop and
describe solutions in simple terms that can
be either executed by a human or computer
Why Computational
With computational thinking skills, students will have: 
Thinking Important?
 Confidence and persistence when  working on complex

problems

 Higher skills in handling the ambiguity in given

problems 

 Ability to deal with open-ended problems 

 Better communication and collaboration skills  


Computational thinking is a fundamental skill in
C T…. computing, engineering, and more in general, education,
that improves the problem-solving and algorithmic
thinking abilities of the learners. 
Computational thinking is a way of thinking about given
problems and processing the stages leading to a solution. 
It is considered a problem-solving method that can be
applied by anyone with different background. 
Computational thinking can help in improving students'
performance in academia in diverse disciplines,
especially in the field of computing. 
In computing, computational thinking entails using core
computer science concepts to solve problems, write
programs and develop systems.
Key Techniques of CT
 Decomposition– breaking down a
complex problem or system into
smaller, more manageable parts.
 Pattern recognition
Looking for similarities among
and within problems.
Identifying patterns makes it easier
to organise data, which in turn can help
with problem solving.  
 Abstraction– focusing on the
important information only, ignoring
irrelevant detail.
 Algorithms– developing a step-by-
step solution to the problem, or the
rules to follow to solve the problem.
Modern Computer
 A modern computer is an electronic device that has
the ability to store, retrieve and process data. Modern
computers can perform tasks such as word
processing, web browsing and database management.
 A modern computer is made of hardware and
software components. Hardware refers to the part of
the computer that has a physical component, such as
a keyboard or a mouse, whereas software is any set
of instructions that tell the hardware how to
accomplish each task.
 Modern computers come in the form of desktop
computers and laptop computers. Desktop computers
are usually used at work, home, school or the library
and are easy to upgrade. Laptop computers, on the
other hand, are battery- or AC-powered computers
that are more portable than desktop computers, but
not as easily upgradeable.
 Other types of modern computers include tablet
computers, mobile phones, game consoles, and TVs.
One characteristic that all computers have is the
ability to share information and files on a network or
server.
Evolution of Modern Computers
 From the 1930s to today, the
computer has changed
dramatically.
 The first modern computer was
created in the 1930s and was called
the Z1, which was followed by
large machinery that took up entire
rooms.
 In the '60s, computers evolved
from professional use to personal
use, as the first personal computer
was introduced to the public.
Information based
Problem Solving(IPS)  Solving these problems requires people that they are
able to define the information problem, search and
select usable and reliable sources and information and
synthesize information into a coherent body of
knowledge. 

 Learners from different levels are required to search,


collect, and understand information from digital
external sources and construct a solution to solve a task.
IPS- Five Step Approach
Real World Information  Real-world data refer to observational data as opposed to
data gathered in an experimental setting

 Any valuable information

 Since computer programs process real-world information,


the first step of computational problem solving is to
encode real-world information as data that can be
processed by a computer.

 Real-world information comes from many sources and in a


variety of forms. Converting information into data that a
computer can store
Data Types
Data can be input to the computer by the user in
many different ways. The main types of data
that can be input into a computer and processed
are 

 Numeric

 Text

 Images

 Sound
Data Encoding
All data that is stored in a computing system is encoded as bit strings.
Text
 Textual characters are usually encoded as integer values using the encoding schemes.
 Each number is arbitrarily associated with the image.
 The associations between numbers and text are known collectively as a character encoding
scheme.

A – 65
a – 97
Color
Pictures
• The most common encoding of a digital image is that of a two-dimensional grid of colors.
• Images are typically encoded as a sequence of pixels where each pixel corresponds to a single
color.
C Programming
 C programming is a general-purpose,
procedural, imperative computer
programming language developed in
1972 by Dennis M. Ritchie at the Bell
Telephone Laboratories to develop the
UNIX operating system.

 C is the most widely used computer


language.
Facts about C
 C was invented to write an operating system called UNIX

 C is a successor of B language which was introduced around


the early 1970s

 The language was formalized in 1988 by the American


National Standard Institute (ANSI)

 The UNIX OS was totally written in C

 Today C is the most widely used and popular System


Programming Language

 Most of the state-of-the-art software have been implemented


using C
Application of C
Programming Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
Environment for C programming language
(a) Text Editor
 This will be used to type your program. Examples of few a editors include Windows
Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For
example, Notepad will be used on Windows, and vim or vi can be used on windows as
well as on Linux or UNIX.
The files you create with your editor are called the source files and they contain the
program source codes. The source files for C programs are typically named with the
extension ".c".
(b) C Compiler()
The source code written in source file is the human readable source for your program. It
needs to be "compiled", into machine language so that your CPU can actually execute the
program as per the instructions given.
The compiler compiles the source codes into final executable programs. The most
frequently used and free available compiler is the GNU C/C++ compiler, otherwise you
can have compilers either from HP or Solaris if you have the respective operating systems.
Basic Structure of C Program
Components of C Structure
Documentation Section
This section consists of comment lines which include the name of programmer,
the author and other details like time and date of writing the program.
Documentation section helps anyone to get an overview of the program.
Link Section
The link section consists of the header files of the functions that are used in the
program.
It provides instructions to the compiler to link functions from the system library.
Definition Section
All the symbolic constants are written in definition section.
Macros are known as symbolic constants.
Components of C Structure
Global Declaration Section
The global variables that can be used anywhere in the program are declared in global declaration
section. This section also declares the user defined functions.
main() Function Section
It is necessary have one main() function section in every C program.
This section contains two parts, declaration and executable part. The declaration part declares all the
variables that are used in executable part.
These two parts must be written in between the opening and closing braces. Each statement in the
declaration and executable part must end with a semicolon (;). The execution of program starts at
opening braces and ends at closing braces.
Subprogram Section
The subprogram section contains all the user defined functions that are used to perform a specific
task.
These user defined functions are called in the main() function.
Source Code Vs
Object Code Source Code refers to file which is a text based document that is
written by the programmer.

The programmer writes the code for performing some task in the
human readable language, almost English every time, and saves
the file into a prescribed format. For Example – ‘.java’ for JAVA
code, ‘.cs’ for C# code, etc. 

Object Code is the machine executable file having instructions


for the machine in the form of binary digits, generated by the
compiler.

Object Code is generated through a process called compilation,


carried out by compiler to convert Source Code into the machine
executable code.
Basic Syntax
Identifiers (A to Z, a to z, '_' and digits (0 to 9))
Ex:sum,abc,a23,b_23
C does not allow punctuation characters such as @, $, and %
Semicolons
printf(“Hello CSE”);
Comments
/*sum of two numbers*/
C Keywords
 Keywords are predefined,
reserved words used in
programming that have special
meanings to the compiler.
 Keywords are part of the syntax
and they cannot be used as an
identifier. 
 As C is a case sensitive
language, all keywords must be
written in lowercase.
 32 keywords
Identifier
Rules for naming identifiers
1.A valid identifier can have letters (both uppercase
Identifier is one of the tokens which are used in
and lowercase letters), digits and underscores.
C programming language. It is a name which is
2.The first letter of an identifier should be either a
used to identify the variables, constants,
letter or an underscore.
functions, arrays, and also user-defined data.
3.You cannot use keywords like int, while etc. as
We cannot use keywords as identifiers because identifiers.
keywords are reserved for special use. Once 4.There is no rule on how long an identifier can be.
declared, we can use the identifier in later However, you may run into problems in some
program statements which refers to the compilers if the identifier is longer than 31 characters
associated value.
Data Types
In the C programming language, data types
are declarations for memory locations or
variables that determine the characteristics of
the data that may be stored. 
Variables in C
A variable is nothing but a name given to a storage area that our programs can manipulate.

Each variable in C has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the set
of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character.

It must begin with either a letter or an underscore.

Upper and lowercase letters are distinct because C is case-sensitive.


Variable Declaration

A variable definition tells the compiler where and how much storage to
create for the variable.
Syntax
Datatype variable_list;
Example
int i, j, k;
char ch, c;
float price, salary;
Assigning Value to the variable

Variables can be initialized (assigned an initial value) in their


declaration
Syntax
Datatype variable_name = value;
Example
int c = 6, d = 4;
char a = ‘A’
float sum = 44.6
Constant
Constants refer to fixed values that the program may

Syntax not alter during its execution. These fixed values are

const datatype variablename = value; also called literals.

Constants can be of any of the basic data types


Example like an integer constant, a floating constant, a
const int length = 10;
character constant, or a string literal.
const float sum = 12.50
Constants are treated just like regular variables
except that their values cannot be modified after
their definition.

const is the keyword


Input and Output Functions
Unformatted I/O Statements Formatted I/O statements

Input Input
getc();
scanf();
getchar();
gets(); fscanf();
Output
putc(); Output
putchar();
printf();
puts();
fprint();
Simple C Programs

#include <stdio.h> #include <stdio.h>


int main( ) int main( )
{ {
int c; char str[100];
printf( "Enter a value :"); printf( "Enter a value :");
c = getchar( ); gets( str );
printf( "\nYou entered: "); printf( "\nYou entered: ");
putchar( c ); puts( str );
return 0; return 0;
} }
Output Output
Enter a value : this is test Enter a value : this is test
You entered: t You entered: this is test
Algorithm
Algorithm is a step-wise representation of a solution to a given problem. In Algorithm the problem is
broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an
actual program.
Flowchart
A flowchart is a picture of the separate steps of a process in sequential order. It is a generic tool that can
be adapted for a wide variety of purposes, and can be used to describe various processes

Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the
result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Addition of Two
Numbers #include <stdio.h>
int main()
{
  int x, y, z;
  printf("Enter two numbers to add\n");
  scanf("%d%d", &x, &y);
  z = x + y;
  printf("Sum of the numbers = %d\n", z);
  return 0;
}
#include <stdio.h>
Addition for Decimal
Values int main()
{
  double a, b, c;
 
Enter two numbers   printf("Enter two numbers\n");
3.21
7.47
  scanf("%lf%lf", &a, &b);
10.680000   c = a + b;
  printf("%lf\n", c);
 
  return 0;
}
Decimal Places #include <stdio.h>
int main()
{
  double a, b, c;
  printf("Enter two numbers\n");
  scanf("%lf%lf", &a, &b);
c = a + b;
  printf("%.1lf\n", c);
  printf("%.2lf\n", c);
  printf("%.3lf\n", c);
  printf("%.4lf\n", c);
  printf("%.5lf\n", c);
  printf("%.6lf\n", c);
  printf("%.7lf\n", c);
  printf("%.8lf\n", c);
  return 0;
}
Operators in C

Arithmetic Operators

Relational Operators

Logical Operators

Bitwise Operators

Assignment Operators

Misc Operators
Arithmetic Operators Relational Operators
Assignment Operator Logical Operator

Operato Name Description Example


Operator Example Same as
r

= a=b a=b
&&  Logica Returns true if both x < 5 &&  x
l and statements are true < 10
+= a += b a = a+b
||  Logica Returns true if one x < 5 || x < 4
-= a -= b a = a-b l or of the statements is
true
*= a *= b a = a*b
! Logica Reverse the result, !(x < 5 &&
/= a /= b a = a/b l not returns false if the x < 10)
result is true
%= a %= b a = a%b
Bitwise Operators
Operator Description

& Bitwise AND

p q p&q p|q p^q


| Bitwise OR

0 0 0 0 0 ^ Bitwise XOR

~
0 1 0 1 1 Bitwise Complement

<< Left Shift


1 1 1 1 0

>> Right Shift


1 0 0 1 1
Bitwise AND Operator &

12 = 00001100 (In Binary) #include <stdio.h>


25 = 00011001 (In Binary) int main()
{
Bit Operation of 12 and 25 int a = 12, b = 25;
00001100 printf("Output = %d", a & b);
& 00011001 return 0;
________ }
00001000 = 8 (In decimal)
Output = 8
Bitwise OR

12 = 00001100 (In Binary) #include <stdio.h>


25 = 00011001 (In Binary) int main()
{
Bitwise OR Operation of 12 and int a = 12, b = 25;
25 printf("Output = %d", a | b);
00001100 return 0;
| 00011001 }
________
00011101 = 29 (In decimal) Output = 29
Bitwise XOR (exclusive OR) Operator ^
The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite

12 = 00001100 (In Binary) #include <stdio.h>


25 = 00011001 (In Binary) int main()
{
Bitwise XOR Operation of 12 and int a = 12, b = 25;
25 printf("Output = %d", a ^ b);
00001100 return 0;
^ 00011001 }
________
00010101 = 21 (In decimal) Output = 21
Right Shift Operator
Right shift operator shifts all bits towards right by certain
Complement and Shift operators number of specified bits
Example
212 = 11010100 (In binary)
35 = 00100011 (In Binary) 212 >> 2 = 00110101 (In binary) [Right shift by two bits]
Bitwise complement Operation of 212 >> 7 = 00000001 (In binary)
35 Left Shift Operator
~ 00100011 Left shift operator shifts all bits towards left by a certain
number of specified bits
________ Example
11011100 = 220 (In decimal) 212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 = 11010100 (Shift by 0)
212<<4 = 110101000000 (In binary)
Misc Operators

Operator Description Example

sizeof() sizeof(a), where a is integer, will


Returns the size of a variable. return 4.

& Returns the address of a &a; returns the actual address of


variable. the variable.

* Pointer to a variable. *a;

?: If Condition is true ? then value


X : otherwise value Y
Conditional Expression.
Sample Script
int main()
Following are the Arithmetic operators in C {
The value of a + b is 15       int a = 10, b = 5;
    printf("Following are the Arithmetic operators in C\n");
The value of a - b is 5     printf("The value of a + b is %d\n", a + b);
The value of a * b is 50     printf("The value of a - b is %d\n", a - b);
    printf("The value of a * b is %d\n", a * b);
The value of a / b is 2
    printf("The value of a / b is %d\n", a / b);
The value of a % b is 0     printf("The value of a % b is %d\n", a % b);
    printf("\nFollowing are the comparison operators in C\n");
Following are the comparison operators in C
    printf("The value of a == b is %d\n", (a == b));
The value of a == b is 0     printf("The value of a != b is %d\n", (a != b));
    printf("The value of a >= b is %d\n", (a >= b));
The value of a != b is 1
    printf("The value of a <= b is %d\n", (a <= b));
The value of a >= b is 1     printf("The value of a > b is %d\n", (a > b));
The value of a <= b is 0     printf("The value of a < b is %d\n", (a < b));
    printf("\nFollowing are the logical operators in C\n");
The value of a > b is 1     printf("The value of this logical and operator ((a==b) && (a<b)) is:%d\n",
The value of a < b is 0            ((a == b) && (a < b)));
    printf("The value of this logical or operator ((a==b) || (a<b)) is:%d\n",
Following are the logical operators in C            ((a == b) || (a < b)));
The value of this logical and operator ((a==b) &&     printf("The value of this logical not operator (!(a==b)) is:%d\n",
(a<b)) is:0            (!(a == b)));
  
The value of this logical or operator ((a==b) || (a<b))     return 0;
is:0 }
The value of this logical not operator (!(a==b)) is:1
Control Structure
Branching Statements
If statement
if…..else statement
Nested if…..else statement
Elseif ladder statement
Switch statement
Looping Statements
While loop
do..while loop
for loop
Sample Script
#include <stdio.h>
If statement
int main ()
{
int x = 40;
Syntax
if( x> 20 )
{
if (condition) printf("x is greater than 20\n" );
{ }
printf("value of x is : %d\n", x);
Block of statements;
return 0;
} }
Output
x is greater than 20
value of x is: 40
Sample Script
if else statement #include <stdio.h>
int main ()
{
Syntax int x = 7;
if (condition) if( x> 10)
{
{
printf("x is greater than 5" );
Block of statements; }
} else
{
else printf(\n"x is less than 5" );
{ }
printf("The value of x is: %d", x);
Block of statements;
return 0;
} }
Output
x is less than 5
The value of x is: 7
Sample script
else if Statement #include<stdio.h>
int main()
Syntax {
if (condition1) int time = 22;
{ if (time < 10)
  // block of code to be executed if condition1 {
is true printf("Good morning.");

} else if (time < 20)
else if (condition2) {
{ printf("Good day.");
  // block of code to be executed if the
} else
condition1 is false and condition2 is true
}  {
else printf("Good evening.");
}
 {
  // block of code to be executed if the return 0;
condition1 is false and condition2 is false }
} Output
Good evening
nested if statement #include <stdio.h>
Syntax int main( )
{
if (condition)
int a, b, c;
{ printf("Please enter three numbers: ");
if (expression) scanf("%d %d %d",&a, &b, &c);
if(a > b)
{
{
Block of statements; if(a > c)
} {
printf("a is the greatest among the three");
else }
{ else
Block of statements; {
printf("c is the greatest among the three");}
} }
} else
{
else
if(b > c)
{ {
Block of statements; printf("b is the greatest among the three");
}
}
else
{
printf("c is the greatest among the three");
else-if ladder statement Sample script
#include <stdio.h>
Syntax void main( )
{
if (condition1)
int x;
{ printf("Please enter a number: ");
Block of statements; scanf("%d", &x);
if(x%2 == 0 && x%3 == 0)
}
{
else if (condition2) printf("The entered number is divisible by both 2 and 3");
{ }
Block of statements; else if(x%2 == 0)
{
}
printf("The entered number is divisible by 2");
else if (condition3) }
{ else if(x%3 == 0)
{
Block of statements;
printf("The entered number is divisible by 3");
} }
else else
{
{
printf("The entered number is divisible by neither 2 nor 3");
default statement }
} }
Sample Script
#include<stdio.h>
 Switch Statement int main()
Instead of writing many if..else statements, {
int day = 4;
you can use the switch statement.
switch (day) {
case 1:
Syntax printf("Monday");

switch(expression) { break;
case 2:
case x: printf("Tuesday");
break;
// code block case 3:
printf("Wednesday");
break; break;
case 4:
case y: printf("Thursday");
break;
// code block case 5:
printf("Friday");
break; break;
case 6:
default: printf("Saturday");
break;
// code block default:
printf("Sunday");
} break;
}
}
Output
Thursday
Loop in C
 Looping Statements in C execute the sequence of
statements many times until the stated condition
becomes false.
 A loop in C consists of two parts, a body of a loop
and a control statement.
 A loop statement allows us to execute a statement
or group of statements multiple times.
 The purpose of the C loop is to repeat the same
code a number of times.
Types of Loops in C
 Entry controlled loop
 Exit controlled loop
In an entry control loop in C, a condition is checked
before executing the body of a loop. It is also called as
a pre-checking loop.
In an exit controlled loop, a condition is checked after
executing the body of a loop. It is also called as a post-
checking loop.
Loop and Control Statements

Sr.N Loop Type & Description


o.
1 while loop Sr.No. Control Statement & Description
Repeats a statement or group of statements while
1 break statement
a given condition is true. It tests the condition Terminates the loop or switch statement and
before executing the loop body. transfers execution to the statement immediately
following the loop or switch.
2 for loop
Executes a sequence of statements multiple times
and abbreviates the code that manages the loop 2 continue statement
variable. Causes the loop to skip the remainder of its body
and immediately retest its condition prior to
3 do...while loop reiterating.
It is more like a while statement, except that it
tests the condition at the end of the loop body. 3 goto statement
Transfers control to the labeled statement.

4 nested loops
You can use one or more loops inside any other
while, for, or do..while loop.
While Loop in C
Sample Script
Syntax
while (condition)
#include<stdio.h>
{ #include<conio.h>
statements; int main()
} {
Output int num=1; //initializing the variable
1 while(num<=10) //while loop with condition
2 {
3 printf("%d\n",num);
4
num++; //incrementing operation
5
}
6
return 0;
7
}
8
9
10
do-while loop in C

Syntax Sample Script


do #include<stdio.h>
{ #include<conio.h>
statements int main()
} while (expression); {
Output int num=1;//initializing the variable
2
do //do-while loop
4
{
6
printf("%d\n",2*num);
8
num++; //incrementing operation
10
12
}while(num<=10);
14 return 0;
16 }
18
20
For loop in C
Syntax
for (initial value; condition; incrementation Sample Script
or decrementation )
{ #include<stdio.h>
statements; int main()
} {
Output
int number;
1
2
for(number=1;number<=10;number++) //for
loop to print 1-10 numbers
3
4 {
5 printf("%d\n",number); //to print the
6 number
7 }
8 return 0;
9
}
10

You might also like