Lecture 2 - Intro To Computer and Algorithm

Download as pdf or txt
Download as pdf or txt
You are on page 1of 81

WEEK 2 – INTRO TO COMPUTER AND

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

 unsigned (positive values only) - negative integers cannot be


assigned to unsigned integers, only a range of positive values

5
 float is used to define floating point numbers, both positive
and negative

 Typical floating point values are 1.73 and 1.932e5


(1.932 x 105).

 An example of declaring a float variable called x is


float x;

6
 double is used to define BIG floating point numbers, both
positive and negative, which have a higher precision than float
variables.

 An example of declaring a double variable called voltage :


double voltage;

7
 The three C floating point types are:
 float
 double
 long double

 In general, the accuracy of the stored real values increases as


you move down the list.

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‟;

 defined constants :You may also associate constant using #define


preprocessor directive
 #define N 3000
 #define FALSE 0
 #define PI 3.14159

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

 An example of declaring a character variable called letter:


char letter = „U‟; The declared character must be enclosed
within a single quote!

11
Data Types

Void Used to denote the type with no values

Int Used to denote to store integers (numbers without decimal


places)

Char Used to denote a character type. Stores a single character

Float Store numbers with decimal places. Approximately precision


of 6 decimal digits.

Double Approximately precision of 14 decimal digits

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‟

int main (void)


{
int salary
printf (“Please enter your salary amount\n”);
scanf (“%f ”, &salary)
printf (“Your salary is = %0.2f%”, salary);
return 0;
}
18
 Identifiers: Variable names
 Valid : dA, dB, dSum, Root, _getchar, __sin, x1, x2, x_1
 Invalid: 324, short, price$, My Name
 case sensitive (a1 and A1 is different!)
 can consist of capital letters[A..Z], small letters[a..z],
digit[0..9], and underscore character (_) that does not begin
with a digit
 First character MUST be a letter or an underscore
 No blanks
 Reserved words cannot be identifiers

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;

 double dBase, dHeight, dArea;


 int iIndex =0, iCount =0;
 char cCh=„a‟, cCh2; Declare and initialize
 const float fEpf = 0.1, fTax = 0.05;

Named constant declared and initialized

24
 Must tell compiler about variable by declaring it and telling
the compiler about what its „type‟ is:
 To declare variable used this syntax:

<variable type><name of variable>

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;

/*Set the number of each kind of pet*/


Cats = 2;
Dogs = 1;
Ponies = 1;
Others = 46;
}

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

 Calculations can be performed inside printf statements


printf( "Sum is %d\n", integer1 + integer2 );

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;

C operation Arithmetic Algebraic C expression


operator expression
Addition + f+7 f + 7
Subtraction - p–c p - c
Multiplication * bm b * m
Division / x/y x / y
Modulus % r mod s r % s

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*/

Prefix operator has higher precedence than assignment.


After execution: x has a value of 5; a has value of 5.
Side effect: value of a is incremented
 Consider a = 4 and x = 10

1. x = a
/*value of a before increment*/

x = a++

2. a = a + 1
/*increment a by 1*/

AFTER execution, x = 4, and a = 5


Marked contrast to almost all other expression
Side effect is that a is incremented by 1.
int i, j=10;
++ Or --
Equivalent Statements i value j value
Statement
i = j;
i = j++; 10 11
j = j + 1;
j = j + 1;
i = ++j; 11 11
i = j ;
i = j ;
i = j--; 10 9
j = j – 1;
j = j – 1;
i = --j; 9 9
i = j ;
47
val = 5;
printf (“%d”, ++val); output = ?

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 = ??

 * / % have the same precedence and associate left to right


 The + and – groups has the lower precedence than the * / % group.
 For example
 3–5*7/8+6/2
 3 – 35 / 8 + 6 / 2
 3 – 4.375 + 6 / 2
 3 – 4.375 + 3
 -1.375 + 3
 1.625
Arithmetic Operators

C Operation Arithmetic Algebraic C Expression


Operator Expression
Addition + f+7 f+7
Subtraction - p–c p-c
Multiplication * bm b*m
Division / x/y x/y
Remainder % r mod s r%s
(Modulus)‫‏‬
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same
level” (i.e., not nested), they are evaluated left to
right.
*, /, or % Multiplication,Di Evaluated second. If there are several, they are
vision, Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.

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

Example 1 : if b is greater than 10,


if (b > 10)‫‏‬
Example 2 : while b is not equal to 10,
while (b != 10)‫‏‬
Example 3 : if mark is equal to 60, print “Pass”,
if (mark == 60)
print (“Pass”);

DO NOT confuse == (relational operator)


with = (assignment operator)‫‏‬
61
 Logical operator:
AND &&
OR ||
 Logical operators are manipulation of logic
 Example:

i. if ((midterm > 60) && (finalexam>50))‫‏‬


printf(“Pass\n”);

ii. if ((midterm < 60) || (finalexam < 50))


printf(“Fail\n”);
62
Expression Expression Expression 1
1 2 && Expression
2
True True True
True False False
False True False
False False False
63
Truth Table for &&, || and !
VARIABLE EXPRESSION

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

When multiple instances of a logical operator are used in a


condition, they are evaluated from right to left
 Consider the following expression:

False OR True AND NOT False AND True

66
 Consider the following expression:

2 * 3 + 4/2 > 3 AND 3 < 5 OR 10 < 9

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

Precedence Type of Operator


1 Arithmetic

2 Comparison

3 Logical
 Consider the following expression:

5+9*3^2-4 > 10 AND (2+2^4-8/4 > 6 OR (2<6 AND 10>11))

72
Common Programming Errors

73
 Debugging  Process removing errors from a
program

 Three (3) kinds of errors:


 Syntax error
 Run-time errors
 Logic Error/Design Error

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

You might also like