Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introducing programming March 24. Program structure Statements to establish the start of the program Variable declaration Program statements (block statements)

Similar presentations


Presentation on theme: "Introducing programming March 24. Program structure Statements to establish the start of the program Variable declaration Program statements (block statements)"— Presentation transcript:

1 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 2 Implemented in ALU in CPU Implemented in Control Unit in CPU

3 Start of the program 3 beginning end

4 Hello world in different languages 4 C languagePascal language C++ language Java language

5 Flowcharts and C language 5 Start / stop #include int main(){ } #include int main(){ } printf(“number %d”, 5); scanf(“%d”, &num); printf(“number %d”, 5); scanf(“%d”, &num); Input / Output condition truefalse if( condition ){ //true }else{ //false } if( condition ){ //true }else{ //false } Computations int area = pi * r * r; int area = pi * r * r;

6 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.

7 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 8 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} 9

10 Basic Data Types Most 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 Intis used to store integers, occupies at least 2, but usually 4 bytes floatis used to store real values with single precision doubleis used to store real values with double precision and optional specifiers signedspecifies that negative and positive values can be stored (only for integers) unsignedspecifies that only non-negative values can be stored (only for integers) shortshort signed integers long long signed integers 10 Examples

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 11 num_1 Num Num1 _NUM NUM_temp2 num_1 Num Num1 _NUM NUM_temp2 Valid names: number_of_values Integer _num1 Num_ __ number_of_values Integer _num1 Num_ __ Valid names: Invalid names: 1num 1_num 365_days @name char 1num 1_num 365_days @name char Some programming languages following these rules are C, C++, Java, Python, PHP

12 Variables 12 C language 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 Variables 13 Java language 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 14

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. 15 Operator nameSyntaxExample Basic assignmenta = bx = 5; Additiona + bx = x + 5; Subtractiona - bx = 4 – y; Unary plus+ax = +5 ; Unary minus-ax = -5; Multiplicationa* bx = x * y; Divisiona / bx = x / y; Modulo (integer remainder)a % bx = 10 % 3 IncrementPrefix++ax = ++5; // x will be 6 Postfixa++y = x++; // y = x; x = x + 1; DecrementPrefix--ax = --5; // x will be 4 Postfixa--y = x--; // y = x, x = x - 1

16 Examples 16

17 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 = 42 But 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

18 Arithmetic operators: Using % op. The program converts a given number of days into months and days

19 Arithmetic operators: Using % op.

20 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 operators In 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. 21

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 22 Operator NameSyntaxMath notation Logical negation (NOT)! A Logical ANDa && b Logical ORa || b

23 Bitwise operator Bitwise operators are used for testing the bits, or shifting them right or left. Bitwise operators are not applied to float or double. OperatorMeaning &Bitwise AND |Bitwise OR ^Bitwise exclusive OR <<Shift left >>Shift right inputs& 0 & 00 0 & 10 1 & 00 1 & 11 inputs| 0 | 00 0 | 11 1 | 01 1 | 11 inputs^ 0 ^ 00 0 ^ 11 1 ^ 01 1 ^ 10 Digital logic notation:

24 Example of bitwise operators 24 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 on 00000010 ^ 00000101 = 00000111

25 Example of shifting operators 25 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. 26 Operator nameSyntax Equal toa == b Not equal toa != b Greater thana > b Less thana < b Greater than or equal toa >= b Less than or equal toa <= b Example: QuestionExpression Does Alice make more than $35,000 per year?Alice_Salary > 35000 Did 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 27 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

28 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 29 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. 30

31 Decision (Conditional) Decision or Conditional statements are a type of Control statement and are often referred to as IF..THEN..ELSE statements 31

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: 32 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 33 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 34 start read X, Y, Z stop X > Y ? stop yesno max > Z ? Output max Output z yesno Max = XMax = 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 35

36 Example of a while loop The program prints out a conversion table from Fahrenheit to Celsius. Draw a corresponding flowchart 36 Program Output

37 37 start read N stop Count > N ? output sum no yes sum = sum + count * count sum = 0 count = 1 count = count + 1 Example of a for loop The program calculates sum = 1 2 + 2 2 + 3 2 + … + N 2

38 38 start read N stop Count > N ? output sum no yes sum = sum + count * (count + 1) sum = 0 count = 1 count = count + 1 sum = 1 * 2 + 2 * 3 + 3 * 4 + … + N * (N +1) Convert to C program

39 39 start read N stop count > N ? output sum no yes prod = prod * count prod = 1 count = 1 count = count + 1 Computing factorial Convert to C program

40 40 start Read X, N stop count > N ? output sum no yes sum = prod * count term = term * X / count term = 1 prod = 1 count = 1 count = count + 1 Computing e x series up to N terms Use Taylor expansion to represent e x up to N terms. Convert to C program

41 41 start Read X, N stop term <.0001 ? output sum no yes sum = prod * count term = term * X / count term = 1 prod = 1 count = 1 count = count + 1 Computing e x series up to 4 decimal places Use Taylor expansion to represent e x up to 4 decimal places. Convert to C program


Download ppt "Introducing programming March 24. Program structure Statements to establish the start of the program Variable declaration Program statements (block statements)"

Similar presentations


Ads by Google