0% found this document useful (0 votes)
3 views

Programming for Problem Solving_intro_pptx

The document outlines the syllabus for a Programming for Problem Solving course using C language, detailing course outcomes and objectives such as formulating algorithms, implementing programming concepts, and solving mathematical problems. It also covers fundamental concepts of computers, programming languages, memory, variables, constants, and basic C programming syntax. Reference materials and examples of C programs are provided to aid learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Programming for Problem Solving_intro_pptx

The document outlines the syllabus for a Programming for Problem Solving course using C language, detailing course outcomes and objectives such as formulating algorithms, implementing programming concepts, and solving mathematical problems. It also covers fundamental concepts of computers, programming languages, memory, variables, constants, and basic C programming syntax. Reference materials and examples of C programs are provided to aid learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

Programming for Problem Solving

ES CS201
MAKAUT-Syllabus
Course Outcomes
• To formulate simple algorithms for arithmetic and logical
problems.

• To translate the algorithms to programs (in C language).

• To test and execute the programs and correct syntax and


logical errors. To implement conditional branching,
iteration and recursion.

• To decompose a problem into functions and synthesize a


complete program using divide and conquer approach.
• To use arrays, pointers and structures to formulate
algorithms and programs.

• To apply programming to solve matrix addition and


multiplication problems and searching and sorting
problems.

• To apply programming to solve simple numerical


method problems, namely rot finding of function,
differentiation of function and simple integration.
Objective of the Course
• To learn programming
– The logic
– Style
– Method

• C Language is being chosen and used just


as a medium of expression
Reference Books
• Programming With C
– B.S. Gottfried, Schaum’s Outline Series, Tata
McGraw-Hill.
• The C Programming Language,
– B. W. Kernighan & D. M. Ritchie, Prentice Hall
• A Book on C
– Al Kelley & Ira Pohl, 4th Edition, Pearson
Education, Asia
What is a computer ?
• A computer is a machine which can accept
data, process the data and supply results.
In

Out
Computer
A computer

Central
Input Output
Processing
Peripherals Peripherals
Unit (CPU)

Main
Memory

Storage
Peripherals
How does a computer work?
• Stored program
• A program is a coded form of an Algorithm
• A program is a set of instructions for
carrying out a specific task.
• Programs are stored in secondary memory,
when created.
• Programs are in main memory during
execution.
CPU
• Central Processing Unit (CPU) is where
computing takes place in order for a
computer to perform tasks.
• CPU’s have large number of registers
which temporarily store data and programs
(instructions).
• The CPU receives stored instructions,
interprets them and acts upon them.
Computer Program
• A program is ultimately
– a sequence of numeric codes stored in memory which is
converted into simple operations (instructions for the
CPU).
This type of code is known as machine code.
• The instructions are retrieved from
– consecutive (memory) locations
unless the current instruction tells it otherwise (branch /
jump instructions).
Programming Languages
• Machine language
• Assembly Language
– Mnemonics (opcodes)

• Higher level languages


– Compiled languages:
• C, C++, Pascal, Fortran
• Converted to machine code using compilers
Instruction Set Program

¨ Start
¨ Read M 0: Start
¨ Write M 1: Read 10
¨ Load Data, M 2: Read 11
¨ Copy M1, M2 3: Add 10, 11, 12
¨ Add M1, M2, M3 4: Write 12
¨ Sub M1, M2, M3 5: Halt
¨ Compare M1, M2, M3
¨ Jump L
¨ Halt
Programming Languages
• Machine language
– Only the machine understands.
– Varies from one class of computers to another.
– Not portable.
• High-level language
– Easier for the user to understand.
– Fortran, C, C++, Java, Cobol, Lisp, etc.
– Standardization makes these languages portable.
• For example, C is available for DOS, Windows, UNIX, Linux, MAC
platforms.
High-Level Language
• Machine language and assembly language
are called low-level languages.
– They are closer to the machine.
– Difficult to use.
• High-level languages are easier to use.
– They are closer to the programmer.
– Examples:
• Fortran, Cobol, C, C++, Java.
– Requires an elaborate process of translation.
• Using a software called compiler.
To type your C program you need another program called Editor.
Once the program has been typed it needs to be converted to
machine language (0s and 1s) before the machine can execute it.
To carry out this conversion we need another program called
Compiler. Compiler vendors provide an Integrated Development
Environment (IDE) which consists of an Editor as well as the
Compiler.
Executable
code
HLL
Compiler Object code Linker
program

For Linux gcc


compiler
is used. Library
Number System Basics
Number System :: The Basics
• We are accustomed to using the so-called
decimal number system.
– Ten digits :: 0,1,2,3,4,5,6,7,8,9
– Every digit position has a weight which is a power
of 10.
• Example:
234 = 2 x 102 + 3 x 101 + 4 x 100
250.67 = 2 x 102 + 5 x 101 + 0 x 100 +
6 x 10-1+ 7 x 10-2
• A digital computer is built out of tiny
electronic switches.
– From the viewpoint of ease of manufacturing
and reliability, such switches can be in one of
two states, ON and OFF.
– A switch can represent a digit in the so-called
binary number system, 0 and 1.
• A computer works based on the binary
number system.
Digital Information
• Computers store all information digitally:
– Numbers
– Text
– Graphics and images
– Audio
– Video
– Program instructions
• In some way, all information is digitized – broken
down into pieces and represented as numbers
Binary Numbers
• Once information is digitized, it is represented and
stored in memory using the binary number system
• A single binary digit (0 or 1) is called a bit.
• A collection of 8 bits is called a byte.
– 00110010
• Word: Depends on the computer
– 4 bytes
– 8 bytes
Memory
• How does memory look like ?
– A list of storage locations, each having a unique
address
– Variables and constants are stored in these
storage locations.
– A variable is like a house. The name of the
variable is the address of the house.
Address and Values
Memory Map
0000
Every variable is 0001
mapped to a
particular 8000
memory address 8001
8002 32

C
Variables in Memory
Instruction executed Memory location allocated
to a variable X
X = 10
T
i X = 20 10
m
e X = X +1

X = X*5
Variables in Memory
Memory location allocated
Instruction executed to a variable X

X = 10
T
i X = 20 20
m
e X = X +1

X = X*5
Variables in Memory
Memory location allocated
Instruction executed to a variable X

X = 10
T
i X = 20 21
m
e X = X +1

X = X*5
Variables in Memory
Memory location allocated
Instruction executed to a variable X

X = 10
T
i X = 20 105
m
e X = X +1

X = X*5
Variables (contd.)

X = 20

20 X
Y=15

X = Y+3 ? Y

Y=x/6
Variables (contd.)

X = 20

20 X
Y=15

X = Y+3 15 Y

Y=x/6
Variables (contd.)

X = 20

18 X
Y=15

X = Y+3 15 Y

Y=x/6
Variables (contd.)

X = 20

18 X
Y=15

X = Y+3 3 Y

Y=X/6
The C Programming Language
Why learn C ?
• C was originally developed in the 1970s, by Dennis Ritchie
at Bell Telephone Laboratories, Inc.
• C is a High level , general –purpose structured
programming language. Instructions of C consists of terms
that are very closely same to algebraic expressions,
consisting of certain English keywords such as if, else,
for ,do and while
• C contains certain additional features that allows it to be
used at a lower level , acting as bridge between machine
language and the high level languages.
• This allows C to be used for system programming as well
as for applications programming
The first C program
#include <stdio.h>
void main ()
{
printf ("Hello, World! \n") ;
}
All programs run from the main function
printf is a function in the library stdio.h
To include any library use #include (called
preprocessor directive)
Description
• stdio.h - a header file is a special type file which
contains information that must be included in the
program when it is compiled. The inclusion of this
required information will be handled automatically
by the compiler.
• The function main with empty parentheses, ()
following the name of the function indicate that
this function does not include any arguments.
Comments
• Any string of symbols placed between the
delimiters /* and */.
• Can span multiple lines
• Can not be nested! Be careful.
• /* /* /* Hi */ is an example of a comment.
• /* Hi */ */ is going to generate a parse error
Second C program
#include <stdio.h>
void main()
{
int x = 1, y;
int sum;
y = 3;
sum = x + y; /* adds x to y, places
value in variable sum */
printf( “%d plus %d is %d\n”, x, y, sum );
}
format
specifier
Different types of token are used in C

1) Identifiers 2)Keywords 3)Constants

4) Operators 5)Punctuation Symbols


Keywords
• Keywords are nothing but auto double int struct
system defined identifiers.
break else long switch
• Keywords are reserved words
of the language. case enum register typedef
• They have specific meaning in
the language and cannot be char extern return union
used by the programmer as
variable or constant names const float short unsigned
• C is case senitive, it means
continue for signed void
these must be used as it is
• 32 Keywords in C default goto sizeof volatile
Programming
do if static while
Identifiers
• An identifier is a word used by a programmer to name a
variable , function, or label.
• identifiers consist of letters and digits, in any order, except
that the first character or label.
• Identifiers consist of letters and digits if any order, except
that the first character must be letter.
• Both Upper and lowercase letters can be used Identifiers
such as printf normally would not be redefined; be careful
• Used to give names to variables, functions, etc.
• Only the first 31 characters matter
Variables
• 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. There are following
basic variable types −

Type Description
.

char Typically, a single octet(one byte). This is an


integer type.
int The most natural size of integer for the machine.
float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type
Constants

• A constant is a value or an identifier whose value cannot be altered


in a program. For example: 1, 2.5,
• As mentioned, an identifier also can be defined as a constant. eg.
const double PI = 3.14
• Here, PI is a constant. Basically what it means is that, PI and 3.14 is
same for this program.

Integer constants
• A integer constant is a numeric constant (associated with number)
without any fractional or exponential part. There are three types of
integer constants in C programming:

• decimal constant(base 10)


• octal constant(base 8)
• hexadecimal constant(base 16)
Constants

Floating-point constants
• A floating-point constant is a numeric constant that has either
a fractional form or an exponent form. For example:
2.0,0.0000234,-0.22E-5

Character constants
• A character constant is a constant which uses single quotation
around characters. For example: 'a', 'l', 'm', 'F'

String constants
• String constants are the constants which are enclosed in a pair
of double-quote marks. For example: "good" ,"x","Earth is
round\n"
Escape Sequences
• Sometimes, it is necessary to use characters which cannot be typed or has
special meaning in C programming. For example: newline(enter), tab, question
mark etc. To use these characters, escape sequence is used.
Escape Sequences Character

\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
Input and Output

printf : performs output to the standard output
device (typically defined to be the monitor)
– It requires a format string to which we can provide
• The text to print out
• Specifications on how to print the values
printf ("The number is %d.\n", num) ;
The format specification %d causes the value listed
after the format string to be embedded in the
output as a decimal number in place of %d.
Input

scanf : performs input from the standard input
device, which is the keyboard by default.
– It requires a format string and a list of
variables into which the value received
from the input device will be stored.

scanf ("%d", &size) ;

scanf ("%c", &nextchar) ;

scanf ("%f", &length) ;
C Program # 3
• #include <stdio.h>
main ()
{
int num_of_students ;
scanf ("%d", &num_of_students) ;
printf ("%d \n", num_of_students) ;
}
• &-address of operator
C Instructions
• There are three types of instructions in C:
(a) Type Declaration Instruction
(b) Arithmetic Instruction
(c) Control Instruction
Type Declaration Instruction
• This instruction is used to declare the type
of variables being used in the program.
• The type declaration statement is written at
the beginning of main( ) function.
Ex.: int bas ;
float rs=2.5; initialization

char name, code ;


Sample C program #4
#include <stdio.h> float myfunc (float r)
#define PI 3.1415926 {
float a;
/* Compute the area of a circle */ a = PI * r * r;
main() /* return result */
{ return (a);
float radius, area; }
float myfunc (float radius);

scanf (“%f”, &radius);


area = myfunc (radius);
printf (“\n Area is %f \n”,
area);
}
Operators and Expressions
Operators in C
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Operators in C
An operator is a symbol which operates on a value or a variable.
For example: + is an operator to perform addition.

C programming has wide range of operators to perform various


operations. For better understanding of operators, these operators
can be classified as:
• Arithmetic Operators
• Increment and Decrement Operators
• Assignment Operators
• Relational Operators
• Logical Operators
• Conditional Operators
• Bitwise Operators
• Special Operators
Expressions and statements
• Expressions : combine constants and variables with
operators
– x*y
• Expressions can be grouped to form statements
– z=x*y;
Semicolons terminate statements
• One or more simple sentences can be grouped to
form a compound sentence or a block by enclosing
within { }
Arithmetic Operator

Operator Meaning of Operator


+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after modulo division
Integer and Float Conversions
Conversion of floating point and integer values in C.

A. An arithmetic operation between an integer and integer


always yields an integer result.

B. An operation between a real and real always yields a real


result.

C. An operation between an integer and real always yields a real


result. In this operation the integer is first promoted to a real
and then the operation is performed. Hence the result is real.
Examples:
Operation Result Operation Result

5/2 2 2/5 0

5.0 / 2 2.5 2.0 / 5 0.4


5 / 2.0 2.5 2 / 5.0 0.4
5.0 / 2.0 2.5 2.0 / 5.0 0.4
Type Conversion in Assignments
• If the type of the expression and the type of the variable on the left-hand side of
the assignment operator may not be same then the value of the expression is
promoted or demoted depending on the type of the variable on left-hand side of
=.
consider the following program fragment.
float a, b, c ;
int s ;
s = a * b * c / 100 + 32 / 4 - 3 * 1.1 ;
- During evaluation of the expression the ints would be promoted to floats and the
result of the expression would be a float.
- But when this float value is assigned to s it is again demoted to an int and then
stored in s.
Examples:
Assumed that k is an integer variable and a is a real variable.
Arithmetic Result Arithmetic Result
Instruction Instruction
k=2/9 0 a=2/9 0.0
k = 2.0 / 9 0 a = 2.0 / 9 0.2222
k = 2 / 9.0 0 a = 2 / 9.0 0.2222
k = 2.0 / 9.0 0 a = 2.0 / 9.0 0.2222
k=9/2 4 a=9/2 4.0
k = 9.0 / 2 4 a = 9.0 / 2 4.5
k = 9 / 2.0 4 a = 9 / 2.0 4.5
k = 9.0 / 2.0 4 a = 9.0 / 2.0 4.5

In the first statement, since both 2 and 9 are integers, the result is
an integer, i.e. 0. This 0 is then assigned to k.
In the second statement 9 is promoted to 9.0 and then the division
is performed. Division yields 0.222222. However, this cannot be
stored in k, as k being an int. Hence it gets demoted to 0 and then
stored in k.
Hierarchy of Operations
The hierarchy of commonly used operators

Prob. Determine the hierarchy of operations and evaluate the


following expression:

i= 3 / 2 * 4 + 3 / 8 + 3
Follow BODMAS that tells algebra students in which order
does an expression evaluate
Assignment operator
int x = 4 ;
x=x+9;
1. The right hand side is evaluated.
2. The left hand side is set to the value of the right
hand side.
All expressions evaluate to a value of a particular
type.
x + 9 evaluates to the integer value of 13.
How does C handle any complex expression?
• Let check with some examples
Associativity of Operators
• Associativity can be of two types—Left to Right
or Right to Left.
• Consider expression
a = 3 / 2 * 5; - between / and * which will
execute first? Or
a = b = 3 ; - the second = is performed earlier.
Why?
Exercise
What would be the output of the following programs:
1. If the marks obtained by a student in five different subjects are input through
the keyboard, find out the aggregate marks and percentage marks obtained by
the student. Assume that the maximum marks that can be obtained by a
student in each subject is 100.
2. Temperature of a city in Fahrenheit degrees is input through the keyboard.
Write a program to convert this temperature into Centigrade degrees.
3. The length & breadth of a rectangle and radius of a circle are input through
the keyboard. Write a program to calculate the area & perimeter of the
rectangle, and the area & circumference of the circle.
4. If a four-digit number is input through the keyboard, write a program to obtain
the sum of the first and last digit of this number.
5. If a five-digit number is input through the keyboard, write a program to print a
new number by adding one to each of its digits. For example if the number that
is input is 12391 then the output should be displayed as 23402.
Increment and Decrement Operators

C programming has two operators increment ++ and


decrement -- to change the value of an operand (constant
or variable) by 1.
Increment ++ increases the value by 1 whereas decrement
-- decreases the value by 1.
These two operators are unary operators, meaning they only
operate on a single operand.
eg. int a=10, b=100
++a = 11
--b = 99
C Relational Operators
• A relational operator checks the relationship between two
operands. If the relation is true, it returns 1; if the relation is
false, it returns value 0.
• Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0
C Assignment Operators

• An assignment operator is used for assigning a value


to a variable. The most common assignment operator
is =
• Operator Example Same as
• = a=b a=b
• += a += b a = a+b
• -= a -= b a = a-b
• *= a *= b a = a*b
• /= a /= b a = a/b
• %= a %= b a = a%b
Logical Operators
• Logical operators act upon logical
expressions
– && : and (true if both operands are true)
– || : or (true if either or both operands true
– ! : negates the value of the logical expression
• Example
– (n >= lo_bound) && (n <= upper_bound)
– ! (num > 100)
Example: Logical Operators
int main ()
{
int i, j;
for (i=0; i<2; i++)
{
for (j=0; j<2; j++)
printf (“%d AND %d = %d,
%d OR %d=%d\n”,
i,j,i&&j, i,j, i||j) ;
}
}
$ ./a.out
0 AND 0 = 0 0 OR 0 = 0
0 AND 1 = 0 0 OR 1 = 1
1 AND 0 = 0 1 OR 0 = 1
1 AND 1 = 1 1 OR 1 = 1
$
C Program # 5
/* FIND THE LARGEST OF THREE NUMBERS */
main()
{
int a, b, c;
scanf (“%d %d %d”, &a, &b, &c);
if ((a>b) && (a>c)) /* Composite condition
check*/
printf (“\n Largest is %d”, a);
else
if (b>c) /* return result */

printf (“\n Largest is %d”, b);


else
printf (“\n Largest is %d”, c);
}
Values of Data Types
• 2 byte int :
– -32768 to +32767 (-215 to 215-1)
• 4 byte int :
– -2147483648 to +2147483647
• 2 byte unsigned int :
– 0 to 65535 (216-1) E or e means “10 to
• char : 0 to 255 the power of”
– ‘a’, ‘A’, ‘+’, ‘=‘, ......
• float : -2.34, 0.0037, 23.0, 1.234e-5

You might also like