Lecture 2 - Intro To Computer and Algorithm
Lecture 2 - Intro To Computer and Algorithm
Lecture 2 - Intro To Computer and Algorithm
ALGORITHM
C has a concept of 'data types' which are used to define a variable
before its use
Data types determine the following:
• Type of data stored
• Number of bytes it occupies in memory
• Range of data
• Operations that can be performed on the data
C has the following basic built-in data types
• int
• float
• double
• char
2
Modifiers alter the meaning of the base type to more
precisely fit a specific need
C supports the following modifiers along with data types:
• short
• long
• signed
• unsigned
3
int is used to define integer numbers (whole numbers, both
positive and negative)
An example of an integer value is 5, 6, 100, 2500.
An example of declaring an integer variable called age is
int age;
4
long int - allowing an integer to be stored in more memory
locations thereby increasing its effective range so that very large
integers can be stored
short int - may or may not have a smaller range than normal int
variables, however will not take up more bytes than int
5
float is used to define floating point numbers, both positive
and negative
6
double is used to define BIG floating point numbers, both
positive and negative, which have a higher precision than float
variables.
7
The three C floating point types are:
float
double
long double
8
A constant is a named or unnamed value, which does not
change during the program execution.
Example:
const double PI = 3.14159
const int degrees = 360
const char Quit = “q”
9
A constant is a named or unnamed value, which does not change
during the program execution
The C language supports two types of constants
declared constants
const double dPi=3.141592
const int iDegrees=360;
const char cQuit=„q‟;
10
char defines characters
„c‟ a single character in single quotes are stored as char
Example of characters:
Numeric digits: 0 - 9
Lowercase/uppercase letters: a - z and A - Z
Space (blank)
Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
11
Data Types
int *, float *, char * Used to denote a pointer type which is memory address type
12
Processor works with finite-sized data
All data implemented as a sequence of bits
Bit = 0 or 1
Type Bytes
Byte = 8 bits Char 1
Int 4
Short int 2
Long int 4
Float 4
Double 8
Long Double 10
13
Type Bits Bytes Range
Char or Signed Char 8 1 -128 to +127
Unsigned Char 8 1 0 to +255
Int or Signed int 32 4 -2,147,483,648 to +2,147,483,647
Unsigned int 32 4 0 to +4,294,967,295
Short int or Signed short int 16 2 -32,768 to + +32,767
Unsigned short int 16 2 0 to +65,535
Long int or signed long int 32 4 -2,147,483,648 to +2,147,483,647
Unsigned long int 32 4 0 to +4,294,967,295
Float 32 4 3.4 e-38 to 3.4 e+38
Double 64 8 1.7e-308 to 1.7e+308
Long Double 64 8 1.7e-308 to 1.7e+308
14
15
16
Variables: locations in memory where a value can be
stored
A quantity that can change during program execution
Hold the data in your program
All variables in C must be declared before use
If an executable statement references and undeclared
variable it will produce a syntax (compiler) error
17
/*Program 2.1 What is a variable*/
#include <stdio.h> Allocate a piece of memory called
„salary‟
19
May only consist of letters, digits and underscore
May be as long as you like, but only the first 31 characters are
significant
May not begin with a number
May not be a C reserved work (keyword)
We must declare the type of every variable we use in C
Declaration of types should always be together at the top of main or a
function
20
Reserved words / Keywords are reserved identifiers that have
strict meaning to the C compiler.
21
Variable names(identifiers) should use Hungarian notation
Begin variable names with lowercase letters
Start with an appropriate prefix that indicates the data type
After the prefix, the name of variable should have one or more
words
The first letter of each word should be in upper case
The rest of the letter should be in lower case
The name of variable should clearly convey the purpose of the
variable
22
Prefix Data Type Example
i int and unsigned int iTotalScore
f float fAverageScore
d double dHeight
l long and unsigned long lFactorial
c signed char and unsigned char cProductCode
ai Array of integer aiStudentId
af Array of float afWeight
ad Array of double adAmount
al Array of long integer alSample
ac Array of characters acMaterial
23
float fIncome;
float fNet_income; float income, net_income;
24
Must tell compiler about variable by declaring it and telling
the compiler about what its „type‟ is:
To declare variable used this syntax:
25
Variables may be given initial values, or initialized, when declared.
Examples:
length
int length = 7 ; 7
diameter
float diameter = 5.9 ; 5.9
initial
char initial = ‘A’ ; „A‟
26
C programmers generally agree on the following conventions for naming
variables.
Begin variable names with lowercase letters
Use meaningful identifiers
Separate “words” within identifiers with underscores or mixed upper and lower case.
Example: surfaceArea, surface_Area surface_area
Permissible to declare multiple variable of the same type on the same lie; each should
be separate with a coma. Example: int a, b, c, d;
Can‟t have multiple variable with same name
Can‟t have variables and functions with the same name
Variable declaration must come before other types of statements in the given { }.
Must declare your variables before you do anything else.
Be consistent!
27
Do not “hide” the initialization
put initialized variables on a separate line
a comment is always a good idea
Example:
int height ; /* rectangle height */
int width = 6 ; /* rectangle width */
int area ; /* rectangle area */
NOT int height, width = 6, area ;
28
int main (void)
{
int Total_Pets;
int Cats;
int Dogs;
int Ponies;
int Others;
29
#include <stdio.h>
int main ()
{
int inches, feet, fathoms;
fathoms = 7;
feet = 6 * fathoms;
inches = 12 * feet;
printf (Its depth at sea:\n”)
printf (“ %d fathoms \n”, fathoms);
printf (“ %d feet\n”, feet);
printf (“ %d inches \n”, inches);
return 0;
}
30
Formatted Input and Output
Statement
31
Example of printf() statement
printf(“Sum is %d\n",dSum);
Output:
Sum is 66
When the printf is executed, it starts printing the until it
encounters a % character (conversion specifier)
The %d means decimal integer will be printed
dSum specifies what integer will be printed
32
scanf is a function in C which allows the programmer to accept
input from user usually from a keyboard.
scanf(“ %d“ , &dA );
This scanf statement has two arguments
%d - indicates data should be a decimal integer
&dA - location in memory to store variable
& - have to be included with the variable name in scanf
statements
When executing the program the user responds to the scanf
statement by typing in a number, then pressing the enter
(return) key
33
Common Conversion Identifier used in printf and scanf
functions.
printf scanf
int %d %d
float %f %f
double %f %lf
char %c %c
string %s %s
34
#include<stdio.h>
Output for the source code:
int main()
{ 7
int a=7; 7
printf("%d\n”,a); 007
printf("%3d\n”,a);
printf("%03d\n”,a);
return 0;
}
35
#include<stdio.h>
Output for the source code:
int main()
{ 7
int a=7; 7
printf("%d\n”,a); 0 0 7
printf("%3d\n”,a);
printf("%03d\n”,a); %d : Print as decimal integer
%3d : Print three digits (positions)
return 0;
%03d : Print the output with a width of three
} digits, but fill the space with 0
36
#include<stdio.h> Output for the source code:
int main() 15.350000
{ 15.3500
float a=15.35; 15.35
printf("%f\n”,a);
printf("%.4f\n”,a);
printf("%4.2f\n”,a); %f print as a floating point
%.4f print as a floating point with a precision of
return 0; four characters after the decimal point
%4.2f print as a floating point at least 4 wide and a
} precision of 2
37
Basic Operators
38
Types of operators are:
Arithmetic operators : unary and binary
(+ , - , * , / , %)
Relational operators
(> , < , == , >= , <=, !=)
Logical operators
(AND - && , OR - ||)
Compound assignment operators
(+=, -=, *=, /=, %=)
39
Used to execute mathematical equations
The result is usually assigned to a data storage (variable) using
assignment operator ( = )
E.g. sum = marks1 + marks2;
40
2 types of arithmetic operators in C:
Unary operators are operators that require only one operand.
Example:
second = + first;
Binary operators are operators that require two operands.
Example:
third = first + second;
41
Prefix/Postfix Increment
a++ : return the current value of a and then increment the value of
a. (a = a + 1)
++a : increment the value of a before returning the value a.
Example: Example:
int a=9; int a=9;
printf(“%d\n”, a++); printf(“%d\n”, ++a);
printf(“%d”, a); printf(“%d”, a);
Output: Output:
9 10
10 10
42
a b
Before: int a=2, b; 2 ?
b = ++a; b = a++;
increments a by 1 and assign value of variable a
assign value of variable a to variable b and
to variable b. increments a by 1.
a b a b
After: 3 3 3 2
43
Before i m
5 ?
Increments m = ++ i m = i ++
prefix: increment i postfix: Use I and then increment
and then use it it
After
After i m i m
6 6 6 5
Assume x = 10 and a = 4
1. a = a + 1
/*increment a by 1*/
x = ++a
2. x = a
/*value of a after increment*/
1. x = a
/*value of a before increment*/
x = a++
2. a = a + 1
/*increment a by 1*/
val = 5;
printf (“%d”, val++); output = ?
val = 5;
printf (“%d”, --val); output = ?
val = 5;
printf (“%d”, val--); output = ?
48
Given a = 2, b = 4, c = 5
1. a = b++ + (b++)
2. --a * (4 + b) / 2 – c++ * b
49
Operator precedence
Some arithmetic operators act before others (i.e.,
multiplication before addition)
Use parenthesis when needed
Example: Find the average of three variables a, b and c
Do not use: a + b + c / 3
Use: (a + b + c ) / 3
50
Arithmetic operators – used to execute mathematical equations
The results usually assigned to a data storage (instance/variable) using assignment
operator ( = ). Example [ sum = marks1 + marks2 ]
( +, - , *, / , %)
+ and – have the same precedence and associate left to right
For example
3 – 5 + 7 = (3-5) + 7
3 + 7 – 5 + 2 = ??
53
Pseudo Code Flow Chart
Begin
• Begin
• Input A and B Input A,B
• Calculate A + B
• Print result of SUM Calculate A + B
• End
Print SUM
End
54
1 #include<stdio.h>
2
3 int main(void) Flow Chart
4 {
5 int dA,dB,dSum;
6 Begin
7 printf(“Input first integer \n”);
8 scanf(“ %d”, &dA); Input A,B
9
10 printf(“Input second integer \n”);
11 scanf(“ %d”, &dB);
12 Calculate A + B
13 dSum= dA + dB;
14 Print SUM
15 printf(“Sum is %d \n”, dSum);
16 End
55
17 return 0;
1 #include<stdio.h>
2
Data Types
3 int main(void)
4 {
5 int dA,dB,dSum; Variables
6
7 printf(“Input first integer \n”);
8 scanf(“ %d”, &dA);
Read input
9
10 printf(“Input second integer \n”);
11 scanf(“ %d”, &dB);
12 Addition operation
13 dSum= dA + dB;
14 Display Output
15 printf(“Sum is %d \n”, dSum);
16
56
17 return 0;
1 #include<stdio.h>
2
3 int main(void)
4 {
5 int dA,dB,dSum;
6
7 printf(“Input first integer \n”);
8 scanf(“ %d”, &dA); OUTPUT
9 Input first integer
10 printf(“Input second integer \n”); 39
11 scanf(“ %d”, &dB); Input second integer
12 27
13 dSum= dA + dB; Sum is 66
14
15 printf(“Sum is %d \n”, dSum);
16
57
17 return 0;
Logic and Comparison
58
To perform decisions
Example : Printing "pass" or "fail" given the
value of a test grade
Relational operator:
>, < >=, <=, == , !=
Used to control the flow of a program
59
Standard C relational Example of C Meaning of C condition
algebraic operator condition
relational
operator
= == x == y x is equal to y
≠ != x != y x is not equal to y
> > x>y x is greater than y
< < x<y x is less than y
x is greater than or equal to
>= >= x >= y
y
<= <= x <= y x is less than or equal to y
60
Relational operators use mathematical comparison
(operation) on two data, but give logical output
A B A && B A || B !A
T T T T F
T F F T F
F T F T T
F F F F T
Precedence of Logical Operators
Precedence Operator
1 NOT
2 AND
3 OR
66
Consider the following expression:
67
To calculate value from expression and store it in
variable, we use assignment operator (=)
Compound assignment operator combines binary
operator with assignment operator
E.g. val +=one; is equivalent to val = val + one;
E.g. count = count -1; is equivalent to
count -=1;
count--;
--count;
68
a=a+b can be written as a += b
a=a*b can be written as a *= b
a=a/b can be written as a /= b
a=a–b can be written as a -= b
69
Operators Precedence
! + - (unary operators) first
* / % second
+ - (binary operators) third
< <= >= > fourth
== != fifth
&& sixth
|| seventh
= last
70
Precedence Among Operators
When an equation uses more than one type of operator then
the order of precedence has to be established with the
different types of operators
2 Comparison
3 Logical
Consider the following expression:
72
Common Programming Errors
73
Debugging Process removing errors from a
program
74
Syntax error
Mistakes caused by violating “grammar” of C
C compiler can easily diagnose during compilation
statement cannot be translated and program cannot be
executed
75
Syntax error
#include<stdio.h>
int main(void)
{
No semicolon ;
printf(“Hello World! \n”)
return 0;
}
76
Run-time error
C compiler cannot recognize during compilation
An attempt to perform an invalid operation, detected
during program execution.
Occurs when the program directs the computer to
perform an illegal operation, such as dividing a number
by zero.
The computer will stop executing the program, and
displays a diagnostic message indicates the line where the
error was detected
77
Run-time error
#include<stdio.h>
int main(void)
{
int salary, full_salary;
printf(“Welcome to Unimap \nEnter Salary :\n”);
scanf(“%d”,&salary);
Run-time error
full_salary=salary/0;
return 0;
}
78
Logic Error
Most difficult error to recognize and correct - it does not
cause run-time error and does not display message errors.
Program compiled and executed successfully but answer
wrong
79
Logic Error
#include<stdio.h>
int main(void)
{
int salary, nett_salary;
printf(“Welcome to Unimap \nEnter Salary :\n”);
scanf(“%d”,&salary);
Printing the wrong
printf(“Net_salary is : %d\n”,nett_salary); variables
return 0;
}
80
END
81