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

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Types and Arithmetic Operators
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
CIS Computer Programming Logic
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Georgia Institute of Technology Introduction to Java, and DrJava Barb Ericson Georgia Institute of Technology Aug 2005.
UniMAP Sem2-08/09 DKT121: Fundamental of Computer Programming1 Introduction to C – Part 2.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
CSCI 1100/1202 January 28, The switch Statement The switch statement provides another means to decide which statement to execute next The switch.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
UniMAP Sem1-07/08EKT120: Computer Programming1 Week2.
C++ Programming: Basic Elements of C++.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Types of C Variables:  The following are some types of C variables on the basis of constants values it has. For example: ○ An integer variable can hold.
Introducing block scheme programming March 17. Algorithm / Flow chart An algorithm or a flowchart is a step-by-step procedure for solving a particular.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
UniMAP Sem I-09/10EKT150: Computer Programming1 Week 2 – Introduction to Computer and Algorithm.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
UNIMAP Sem2-07/08EKT120: Computer Programming1 Week 2 – Introduction to Programming.
ICS102 Lecture 1 : Expressions and Assignment King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Chapter 2: Basic Elements of C++
CSE 220 – C Programming Expressions.
Data Types and Expressions
BASIC ELEMENTS OF A COMPUTER PROGRAM
ITEC113 Algorithms and Programming Techniques
IDENTIFIERS CSC 111.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Introduction to Java, and DrJava part 1
C Operators, Operands, Expressions & Statements
Introduction to Java, and DrJava
Primitive Types and Expressions
Unit 3: Variables in Java
Introduction to Java, and DrJava part 1
Chap 7. Advanced Control Statements in Java
Session 1 – Introduction to Computer and Algorithm (Part 2)‏
OPERATORS in C Programming
DATA TYPES There are four basic data types associated with variables:
Introduction to C Programming
OPERATORS in C Programming
Chapter 12 Variables and Operators
Presentation transcript:

Introducing programming March 24

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

Start of the program 3 beginning end

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

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;

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.

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

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

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

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 char 1num 1_num char Some programming languages following these rules are C, C++, Java, Python, PHP

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.

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

Operators Arithmetic Comparison operators/relational operators Logical operators Bitwise operators Compound operators Member and point operators 14

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

Examples 16

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 =  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.

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

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

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:

Example of bitwise operators 24 Checks if bit 3 (corresponds to 4 in decimal system) is on Remember: (binary system) (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 ^ =

Example of shifting operators 25 equivalent to multiplication by 2 equivalent to division by 2

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 > Did the NY Giants defeat the Dallas Cowboys?Giants_Points > Cowboys_Points Did anyone get a perfect score on the test?TestScore == 100

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

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)

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 > Compound expression

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

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

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)

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

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.

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

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

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 = … + N 2

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 * * * 4 + … + N * (N +1) Convert to C program

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