Introducing programming March 24. Program structure Statements to establish the start of the program...
-
Upload
cynthia-joy-hunt -
Category
Documents
-
view
232 -
download
0
Transcript of Introducing programming March 24. Program structure Statements to establish the start of the program...
Introducing programming
March 24
2
Program structure Statements to establish the start of the program Variable declaration Program statements (block statements)
Operators Arithmetic operators Logic operators Bit operators Comparison operators
Conditional statements Branching statements
Implemented in ALU in CPU
Implemented in Control Unit in CPU
3
Start of the program
beginning
end
4
Hello world in different languages
C language Pascal language
C++ language Java language
5
Flowcharts and C language
Start / stop
#include <stdio.h>int main(){
}
printf(“number %d”, 5);scanf(“%d”, &num);Input / Output
conditiontruefalse
if( condition ){//true
}else{//false
}
Computations int area = pi * r * r;
A Simple program
Use the .2 modifier to the %f specifier to fine-tune the appearance of the output so that it displays two places to the right of the decimal.
To provide keyboard input to the program, use the scanf() function. The %f instructs scanf() to read a real number from the keyboard, and the &weight tells scanf() to assign the input value to the variable named weight.
Interactive program The interactive approach makes programs more flexible; The sample program can be used for any reasonable weight; The scanf() and printf() functions make this interactivity
possible.
8
The largest of two numbers
start
read X, Y
output X
stop
X > Y ?
output Y
stop
yes no
the program starts here
read x,y
the program ends here
9
Variables Variables are place holders for data a program might use or
manipulate. Variables are given names so that we can assign values to them
and refer to them later to read the values. Variables typically store values of a given type.
Integer – to store integer or “whole” numbers: 512, -123 Real – to store real or fractional numbers (also called float to
indicate a floating point number): 3.14, 2.7 Character – A single character such as a letter of the alphabet or
punctuation: ‘a’, ‘!’ String – A collection of characters: “Hello world!” Structure – A compound user defined type: student{name, id}
10
Basic Data TypesMost of data types are formed from one of the four basic arithmetic type specifiers in C
char is used to store characters, generally occupies 1 byte of memory Int is used to store integers, occupies at least 2, but usually 4 bytes float is used to store real values with single precision double is used to store real values with double precision
and optional specifiers signed specifies that negative and positive values can be stored (only for integers) unsigned specifies that only non-negative values can be stored (only for integers) short short signed integers long long signed integersExamples
11
A few rules about naming the variables Characters allowed
Underscore _ Capital letters A-Z Small letters a-z Digits 0 – 9
First character should be alphabet or underscore Blanks, commas and symbols are not allowed Variables name should not be reserved word
num_1NumNum1_NUMNUM_temp2
Valid names:
number_of_valuesInteger_num1Num___
Valid names: Invalid names:
1num1_num365_days@namechar
Some programming languages following these rules are C, C++, Java, Python, PHP
12
Variables C
lang
uage
Variables are declared; Memory will be allocated at the execution time
Variables are initialized
In order to use a variable within a program, the compiler needs to know in advance the type of data that will be stored in it.
13
VariablesJa
va la
ngua
ge
Variables are declared; Memory will be allocated at the execution time
Variables are initialized
Variable declaration consists of giving a new name and a data type for the variable
14
Operators Arithmetic Comparison operators/relational operators Logical operators Bitwise operators Compound operators Member and point operators
15
Basic arithmetic operations In order to use a variable within a program, the compiler needs
to know in advance the type of data that will be stored in it.Operator name Syntax Example
Basic assignment a = b x = 5;
Addition a + b x = x + 5;
Subtraction a - b x = 4 – y;
Unary plus +a x = +5 ;
Unary minus -a x = -5;
Multiplication a* b x = x * y;
Division a / b x = x / y;
Modulo (integer remainder) a % b x = 10 % 3
Increment Prefix ++a x = ++5; // x will be 6
Postfix a++ y = x++; // y = x; x = x + 1;
Decrement Prefix --a x = --5; // x will be 4Postfix a-- y = x--; // y = x, x = x - 1
16
Examples
Arithmetic operators: remainder In arithmetic, the remainder is the amount "left over" after
the division of two integers which cannot be expressed with an integer quotient.
The general form of a linear equation can be expressed as a = q * d + r.
q is the quotient and d as the divisor, r as the remainder.
r = a - q * d.
For example: a = 810, q = 3, d = 256, r = 42But we only know a and d and we want to find q and r.a / d = 3.1640625 q = [a / d] = 3 and r = 810 – 3 * 256 = 42
Arithmetic operators: Using % op. The program converts a given number of days into months and days
Arithmetic operators: Using % op.
Increment and decrement operators
C allows two very useful operators not generally found in other languages. There are the increment and decrement operators: ++ and --
The operator ++ adds 1 to the operand, while -- subtracts 1.
++m; is equivalent to m = m + 1; (or m+= 1)
--m; is equivalent to m = m -1; (or m-= 1)
m = 5;y = ++m;
m = 5;y = m++;
Prefix operator Postfix operator
m is 6 and y is 6 m is 6 and y is 5
• Example: m = n++ - j + 10; Old value of n is used in evaluation.
21
Basic logical operatorsIn Boolean logic, the operands are statements (that can be proven True or False) and the operators are logical AND, OR and NOT. Example:
I am 6 feet tall AND I am president of the United States While it may be True that he is six feet tall (a fact that can be proven
by measuring my height), it can certainly be shown that he is not the president of the United States. Therefore, according to Boolean logic, this entire sentence is False.
I am 6 feet tall OR I am president of the United States In this case that only one of the parts of the sentence (separated by
OR) need be True in order for the entire sentence to be considered True.
It is True that I am 6 feet tall OR I am the president of the United States.
22
Basic logical operators There are three Boolean operators: AND, OR and NOT. These
operators are written differently depending on the language being used. In mathematics, the logical operators are written as
Operator Name Syntax Math notation
Logical negation (NOT) ! A
Logical AND a && b
Logical OR a || b
Bitwise operatorBitwise operators are used for testing the bits, or shifting them right or left. Bitwise operators are not applied to float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
inputs &
0 & 0 00 & 1 01 & 0 01 & 1 1
inputs |
0 | 0 00 | 1 11 | 0 11 | 1 1
inputs ^
0 ^ 0 00 ^ 1 11 ^ 0 11 ^ 1 0
Digital logic notation:
24
Example of bitwise operators
Checks if bit 3 (corresponds to 4 in decimal system) is on
Remember: 1 1 1 1 1 1 1 1 (binary system)128 64 32 16 8 4 2 1 (decimal system)
Checks if bits 1 and 2 (corresponds to 5 in decimal system) are on
Sets bit 1 (corresponds to 1 in decimal system) to on
Sets all bits that are different to on00000010 ^ 00000101 = 00000111
25
Example of shifting operators
equivalent to multiplication by 2
equivalent to division by 2
26
Comparison operators/ relational operators Boolean expressions often involve comparison operators that
can be evaluated to determine if they are True or False.
Operator name Syntax
Equal to a == b
Not equal to a != b
Greater than a > b
Less than a < b
Greater than or equal to a >= b
Less than or equal to a <= b
Example: Question ExpressionDoes Alice make more than $35,000 per year? Alice_Salary > 35000Did the NY Giants defeat the Dallas Cowboys? Giants_Points > Cowboys_Points
Did anyone get a perfect score on the test? TestScore == 100
27
Comparison operators/ relational operators
A simple relational expression contains only one relational operator:
arithm_expr1 relat_op arithm_expr2 4.5 <= 10 TRUE 4.5 < -10 FALSE -35 >= 0 FALSE 10 < 7+5 TRUE
a + b == c + d TRUE // if a + b is equal to c + d
Relational operators: Example For example you have 1000 Won in your
pocket, then when the question is: Do I have enough money to buy an ice
cream In C this question can be written as follows
YES (TRUE) any non-zero value
NO (FALSE)
29
Combining Boolean and Comparison Operators
The two types of operators are used to form more complex expressions. Ex.: Are there more than 30 students in the class, and are there more
than 30 seats in the room?Number_of_Students > 30 AND Number_of_Seats > 30
Compound expression
30
Conditional Statements Control statements “control” which sections of code in a
program are executed There are three general types of control statements:
Sequential – The default ordering of execution Decision (Conditional) – controls which block of code within
several alternatives is executed. Iterative – controls how many times a block of code is executed.
31
Decision (Conditional) Decision or Conditional statements are a type of Control
statement and are often referred to as IF..THEN..ELSE statements
32
Iterative Constructs (Loops)All programming languages have a facility to allow a section of code to be repeated (iterated or looped). There are several variations:
for loop: for (initialization; condition; increment){…}
while loop: while (condition){statements}
do while loop: do{statements}while (condition)
33
Recall: The largest of two numbers
start
read X, Y
output X
stop
X > Y ?
output Y
stop
yes no
the program starts here
read x,y
the program ends here
34
Larger of three numbers
start
read X, Y, Z
stop
X > Y ?
stop
yes no
max > Z ?
Output max Output z
yes no
Max = X Max = Y
Transform the flowchart below to a C language program.
35
Find whether a number is odd or even Draw a flow chart for the algorithm that checks whether the
number is odd or even. Convert the algorithm into C language program
36
Example of a while loop The program prints out a conversion table from Fahrenheit to
Celsius. Draw a corresponding flowchartProgram Output
37
start
read N
stop
Count > N ?
output sum
no yes
sum = sum + count * count
sum = 0count = 1
count = count + 1
Example of a for loopThe program calculates sum = 12 + 22 + 32 + … + N2
38
start
read N
stop
Count > N ?
output sum
no yes
sum = sum + count * (count + 1)
sum = 0count = 1
count = count + 1
sum = 1 * 2 + 2 * 3 + 3 * 4 + … + N* (N +1)Convert to C program
39
start
read N
stop
count > N ?
output sum
no yes
prod = prod * count
prod = 1count = 1
count = count + 1
Computing factorialConvert to C program
40
start
Read X, N
stop
count > N ?
output sum
noyes
sum = prod * countterm = term * X / count
term = 1prod = 1count = 1
count = count + 1
Computing ex series up to N terms
Use Taylor expansion to represent ex up to N terms.
Convert to C program
41
start
Read X, N
stop
term < .0001 ?
output sum
noyes
sum = prod * countterm = term * X / count
term = 1prod = 1count = 1
count = count + 1
Computing ex series up to 4 decimal places
Use Taylor expansion to represent ex up to 4 decimal places.
Convert to C program