BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal

Similar documents
SEQUENTIAL STRUCTURE. Erkut ERDEM Hacettepe University October 2010

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

C: How to Program. Week /Mar/05

Chapter 2 - Introduction to C Programming

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Chapter 1 & 2 Introduction to C Language

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Fundamental of Programming (C)

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

A Fast Review of C Essentials Part I

Another Simple Program: Adding Two Integers

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Data Types and Variables in C language

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

6.096 Introduction to C++ January (IAP) 2009

Fundamentals of Programming

Chapter 2: Overview of C. Problem Solving & Program Design in C

UNIT- 3 Introduction to C++

Lecture 3. More About C

ANSI C Programming Simple Programs

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Data types, variables, constants

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

BLM2031 Structured Programming. Zeyneb KURT

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

DEPARTMENT OF MATHS, MJ COLLEGE

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Introduction to Programming

Programming and Data Structures

Programming. C++ Basics

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Introduction to C# Applications

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

ET156 Introduction to C Programming

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

CS102: Variables and Expressions

Programming for Engineers Introduction to C

Computer System and programming in C

IS 0020 Program Design and Software Tools

CS 61C: Great Ideas in Computer Architecture Introduc=on to C, Part I. We are here!

Introduction to the C Programming Language

The component base of C language. Nguyễn Dũng Faculty of IT Hue College of Science

Presented By : Gaurav Juneja

Programming in C++ 4. The lexical basis of C++

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Work relative to other classes

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

Fundamental of C programming. - Ompal Singh

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

Main Memory Organization

Basics of Programming

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Basics of Java Programming

C Programming Primer 8/31/15 1

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Creating a C++ Program

1.1 Introduction to C Language. Department of CSE

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Full file at C How to Program, 6/e Multiple Choice Test Bank

Chapter 2. Lexical Elements & Operators

>B<82. 2Soft ware. C Language manual. Copyright COSMIC Software 1999, 2001 All rights reserved.

C Language, Token, Keywords, Constant, variable

Computers Programming Course 5. Iulian Năstac

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

Procedures, Parameters, Values and Variables. Steven R. Bagley

Basic Elements of C. Staff Incharge: S.Sasirekha

Program Fundamentals

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

Structured Programming. Dr. Mohamed Khedr Lecture 4

Fundamentals of Programming. Lecture 3: Introduction to C Programming

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

C - Basic Introduction

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Chapter 2. C++ Basics

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

CS Programming In C

Lecture 10: Potpourri: Enum / struct / union Advanced Unix #include function pointers

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Objec+ves. Review. Basics of Java Syntax Java fundamentals. What are quali+es of good sooware? What is Java? How do you compile a Java program?

Fundamentals of C. Structure of a C Program

XSEDE Scholars Program Introduction to C Programming. John Lockman III June 7 th, 2012

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.


Chapter 1 Introduction to Computers and C++ Programming

Fundamentals of Programming Session 4

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

JAVA Programming Fundamentals

Unit 3. Operators. School of Science and Technology INTRODUCTION

printf( Please enter another number: ); scanf( %d, &num2);

CSCI 1061U Programming Workshop 2. C++ Basics

Introduction to C Final Review Chapters 1-6 & 13

Introduction to C Language

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Transcription:

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3 Aykut Erdem, Erkut Erdem, Fuat Akal 1

Today Introduc/on to Programming Basic Concepts Developing Algorithms Crea<ng Flowcharts The C Programming Language Your first C Program Programming Process Lexical Elements of a C Program Keywords, Iden<fiers, Constants, Data Types, Operators Standard Input and Output Type Conversion and Cas<ng 2

Today Introduc/on to Programming Basic Concepts Developing Algorithms Crea<ng Flowcharts The C Programming Language Your first C Program Programming Process Lexical Elements of a C Program Keywords, Iden<fiers, Constants, Data Types, Operators Standard Input and Output Type Conversion and Cas<ng 3

What is a Program? A computer program is a set of instruc<ons for a computer to follow e.g. instruc<ons to find the maximum value in a list of numbers 4

What is a Program? A computer program is a set of instruc<ons for a computer to follow e.g. instruc<ons to find the maximum value in a list of numbers An algorithm is a sequence of precise instruc<ons which leads to a solu<on e.g. how to find the maximum value in a list of numbers 5

What is a Program? A computer program is a set of instruc<ons for a computer to follow e.g. instruc<ons to find the maximum value in a list of numbers An algorithm is a sequence of precise instruc<ons which leads to a solu<on e.g. how to find the maximum value in a list of numbers Program is an algorithm expressed in a language that the computer can understand e.g. The C Programming Language 6

What is a Program? A computer program is a set of instruc<ons for a computer to follow e.g. instruc<ons to find the maximum value in a list of numbers An algorithm is a sequence of precise instruc<ons which leads to a solu<on e.g. how to find the maximum value in a list of numbers Program is an algorithm expressed in a language that the computer can understand e.g. The C Programming Language Computer soaware is the collec<on of programs e.g. MicrosoM Office, itunes, FireFox etc. 7

Pseudocode Ar<ficial, informal language that helps us develop algorithms Similar to everyday English Not actually executed on computers Helps us think out a program before wri<ng it Easy to convert into a corresponding C program Example: 1. Display Enter two integer number message 2. Read the 1 st number from keyboard 3. Read the 2 nd number from keyboard 4. Compute sum of entered numbers 5. Print Sum = + sum 8

Program Design Programming is a crea<ve process No complete set of rules for crea<ng a program Program Design Process Problem Solving Phase Result is an algorithm that solves the problem Implementa<on Phase Result is the algorithm translated into a programming language The Art of Computer Programming, Donald Knuth (expected to be 7 volumes) 9

Problem Solving Phase Be certain the task is completely specified What is the input? What informa<on is in the output? How is the output organized? Develop the algorithm before implementa<on Experience shows this saves <me in ge_ng your program to run Test the algorithm for correctness 10

Implementa/on Phase Translate the algorithm into a programming language Easier as you gain experience with the language Compile the source code Locates errors in using the programming language Run the program on sample data Verify correctness of results Results may require modifica<on of the algorithm and program 11

SoAware (Bigger Programs) Development Problem Defini<on Analysis Analyze the problem Define input, output and variables Design Design the algorithm Implementa<on Coding the algorithm Tes<ng Test and verify the correctness of the program Maintenance Fix bugs and add new features 12

Flowcharts A flowchart is a type of diagram, that represents an algorithm or process 1 st number 2 nd number Sum = 1 st number + 2 nd number 13

Basic Flowchart Symbols 1/2 Start / Stop Input Sequence Output 14

Basic Flowchart Symbols 2/2 Decision True False Repeat Repeat Loop While Loop False True False True 15

Example 1: Algorithm to find and display the sum of two integers entered via keyboard 16

Example 1: Algorithm to find and display the sum of two integers entered via keyboard Algorithm 1. Display Enter two integer number message 2. Read the 1 st number from keyboard 3. Read the 2 nd number from keyboard 4. Compute sum of entered numbers 5. Print Sum = + sum 17

Example 1: Algorithm to find and display the sum of two integers entered via keyboard Algorithm 1. Display Enter two integer number message 2. Read the 1 st number from keyboard 3. Read the 2 nd number from keyboard 4. Compute sum of entered numbers 5. Print Sum = + sum 1 st number 2 nd number Enter two integer number sum = 1 st number + 2 nd number sum 18

Example 2: Algorithm to display two integers entered via keyboard in descending order 19

Example 2: Algorithm to display two integers entered via keyboard in descending order Algorithm 1. Read the number1 from keyboard 2. Read the number2 from keyboard 3. If number1 > number2 Print number1 > number2 4. otherwise Print number2 > number1 20

Example 2: Algorithm to display two integers entered via keyboard in descending order Algorithm 1. Read the number1 from keyboard 2. Read the number2 from keyboard 3. If number1 > number2 Print number1 > number2 4. otherwise Print number2 > number1 number1 number2 True False number1 > number2 number1, number2 number2, number1 21

Example 3: Algorithm to display three integers entered via keyboard in ascending order 22

Example 3: Algorithm to display three integers entered via keyboard in ascending order Algorithm 1. Read the number1, number2 and number3 from keyboard 2. If number1 > number2 Big = number1 Small = number2 3. Otherwise Big = number2 Small = number1 23

Example 3: Algorithm to display three integers entered via keyboard in ascending order Algorithm 1. Read the number1, number2 and number3 from keyboard 2. If number1 > number2 big = number1 small = number2 3. Otherwise big = number2 small = number1 4. If number3 > big middle = big big= number3 5. Otherwise If number3 > small middle = number3 Otherwise middle = small small = number3 6. Display small, middle, big 24

Example 3: Algorithm to display three integers entered via keyboard in ascending order Number1, 2, 3 True False number1 > number2 big = number1 small = number2 T F big = number2 small = number1 middle = big big = number3 number3 > big T middle = number3 F number3 > small middle = small small = number3 small, middle, big 25

Example 4: Algorithm to find n! 26

Example 4: Algorithm to find n! Algorithm 1. Read n from keyboard 2. if n < 0 3. else Display error message factorial = 1 value = 1 while (value <= n) factorial = factorial * value increment value by 1 4. Display factorial 27

Example 4: Algorithm to find n! n Algorithm 1. Read n from keyboard 2. if n < 0 3. else Display error message factorial = 1 value = 1 while (value <= n) factorial = factorial * value increment value by 1 4. Display factorial True Can t be Nega<ve! n < 0 while (value<=n) False factorial = factorial * value value = value + 1 factorial = 1 value = 1 factorial 28

Today Introduc/on to Programming Basic Concepts Developing Algorithms Crea<ng Flowcharts The C Programming Language Your first C Program Programming Process Lexical Elements of a C Program Keywords, Iden<fiers, Constants, Data Types, Operators Standard Input and Output Type Conversion and Cas<ng 29

Anatomy of a Typical C Program #preprocessor directives declarations variables functions int main (void){ declarations; statements; return value; } 30

Your First C Program hello.c /* Welcome to BBM 101 */ #include <stdio.h> int main(void) { } printf( Hello world!\n ); return 0; $>> gcc hello.c ansi Wall o hello $>>./hello Hello world! 31

Your First C Program hello.c /* Welcome to BBM 101 */ #include <stdio.h> int main(void) { } printf( Hello world!\n ); return 0; /* comments */ global declara<ons #include external files main func<on Hello world! 32

Your First C Program hello.c Text surrounded by /* and */ is ignored by computer /* Welcome to BBM 101 */ #include <stdio.h> int main(void) { } printf( Hello world!\n ); return 0; /* comments */ global declara<ons #include external files main func<on Hello world! 33

Your First C Program hello.c /* Welcome to BBM 101 */ #include <stdio.h> int main(void) { } printf( Hello world!\n ); return 0; /* comments */ global declara<ons #include external files stdio.h allows standard input/output opera<ons main func<on Hello world! 34

Your First C Program hello.c /* Welcome to BBM 101 */ #include <stdio.h> int main(void) { } printf( Hello world!\n ); return 0; /* comments */ global declara<ons #include external files main func<on C programs contain one or more func<ons, exactly one of which must be main Hello world! 35

The main(void) of hello.c Arguments Return value Program int main(void) int main(void) { printf( Hello world!\n ); return 0; } No arguments. Returns an integer variable. return 0 to OS: everything is OK Slide credit: Bert Huang 36

C Statements One- line commands Always end in semicolon ; Examples: call func<on: printf( hello ); /* from stdio */ declare variable: int x; assign variable value: x = 123+456; 37

The Programming Process Create/Edit Program Compile Execute The cycle ends once the programmer is sa<sfied with the program, e.g., performance and correctness- wise. Do not forget, your program always has at least twenty bugs even amer you have fixed them all J 38

C Program Development Editor Pre- processor Compiler Linker Loader Disk Main Memory Create/Edit: Program is created in the editor and stored on disk. Preprocess: Preprocessor program processes the code. Compile: Compiler creates object code and stores it on disk. Link: Linker links the object code with the libraries. Load: Loader puts program in memory. CPU Execute: CPU takes each instruc<on and executes it, possibly storing new data values as the program executes. 39

Lexical Elements Token: The smallest element of a program that is meaningful to the compiler Kinds of tokens in C: Keywords Iden<fiers Constants/Literals Operators Punctuators 40

Keywords 32 words are defined as keywords in C They have predefined uses and cannot be used for any other purpose in a C program auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while 41

Iden/fiers A sequence of lepers, digits, and the underscore character _ sa<sfying iden<fier = c { c d }* with c = { A,, Z, a,, z, _ }, d = {0,,9}, and asterisk * means 0 or more Case- sensi<ve e.g., firstname and firstname are two different iden<fiers. Iden<fiers are used for Variable names Func<on names Macro names 42

Iden/fier Examples Valid iden<fiers X a1 _xyz_33 integer1 Double Invalid iden<fiers xyz.1 gx^2 114West int ß This is a keyword pi*r*r 43

Variables A variable is a loca<on in main memory where a value is stored (just like Algebra) Variables must be declared before they are used Variable declara<ons must appear before executable statements A syntax error is raised at compile- <me if above two are violated Every variable has a name, a type, size and a value 44

Basic Data Types Integer (int) Character (char) Floa<ng Point (float) Double Precision Floa<ng Point (double) Data Type Modifiers signed / unsigned short / long 45

int 4 bytes (on Unix) Base- 2 representa<on. need one bit for + or - Range: - 2 31 to 2 31 Variants: short (2 bytes), long (8 bytes), unsigned (only non- nega<ve) Slide credit: Bert Huang 46

char 1 byte ASCII representa<on in base- 2 Range: 0-255 (lots of unused) Slide credit: Bert Huang 47

float Stands for floa<ng decimal point 4 bytes Similar to scien<fic nota<on: 4.288 * 10 3 Very different interpreta<on of bits than int and char. Range: - 10 38 to 10 38 Slide credit: Bert Huang 48

Basic Data Types Type Size in Bytes Range signed char 1-127 to +127 unsigned char 1 0 to 255 short int 2-32,767 to +32,767 unsigned short int 2 0 to 65535 int 4-32,767 to +32,767 unsigned int 4 0 to 65,535 long int 8-2,147,483,647 to +2,147,483,647 unsigned long int 8 0 to 4,294,967,295 float 4 ~10-37 to ~10 38 double 8 ~10-307 to ~10 308 long double 16 ~10-4931 to ~10 4932 49

Declaring a Variable A declara<on consists of a data type name followed by a list of (one or more) variables of that type char c; int mycounter; float rate; double trouble; A variable may be ini<alized in its declara<on char c = a ; int a = 220, b = 448; float x = 1.23e-6; /*0.00000123*/ double y = 27e3; /*27,000*/ Variables that are not ini<alized may have garbage values Placing a new value replaces the previous value Reading variables from memory does not change them 50

Constants Integer Constants 0, 37, 2001 Floa<ng- point Constants 0.8, 199.33, 1.0 Character Constants a, 5, + String Constants a, Monday Common Escape Sequences \a audible alarm \b backspace \n newline \r carriage return \t horizontal tab \f form- feed \\ backslash \ double quote How to define? #define PI 3.14; const double PI = 3.14; 51

Operators Arithme<c operators *, /, %, +, - Assignment operator = Logical operators We will cover this next week in the selec<ve- structures lecture 52

Arithme/c Operators For arithme<c calcula<ons Addi<on (+), subtrac<on (- ), mul<plica<on (*) and integer division (/) Integer division truncates remainder 7 / 5 evaluates to 1 Modulus operator(%) returns the remainder 7 % 5 evaluates to 2 Arithme<c operators associate lem to right Operator precedence Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: (a + b + c ) / 3 See next slide for why 53

Operator Precedence Operator(s) Opera/on(s) Precedence ( ) Parentheses Evaluated first. Innermost parentheses is evaluated in case of nested parentheses. Same level parentheses are evaluated from lem to right. *, /, % Mul<plica<on Division Modulus +, - Addi<on Subtrac<on Evaluated second. If there are several, they are evaluated from lem to right. Evaluated last. If there are several, they are evaluated from lem to right. 54

Operator Precedence y = 2 * 5 * 5 + 3 * 5 + 7 y = 10 * 5 + 3 * 5 + 7 y = 50 + 3 * 5 + 7 y = 50 + 15 + 7 y = 65 + 7 Left-most multiplication Left-most multiplication Multiplication precedes addition Left-most addition Last operation y = 72 55

Assignment Operator (=) variable = expression ; Expressions Opera<ons total = number1 + number 2 ; Variables temp = number1 ; Constants #define PI 3.14 circumference = 2 * PI * radius ; Func<on Calls maxvalue = findmax(number1, number2) ; Precedence of the assignment operator is lower than the arithme<c operators 56

l- value vs. r- value 5 x x = 5; y = 10; 10 y l(em)- value usage of y r(ight)- value usage of x y = x ; There is a memory loca<on named y. This loca<on will receive a value. There is a memory loca<on named x, where there is a value si_ng, go and get me that value. X + 1 = 3 ; is an invalid l- value expression. 57

Further Assignment Opera/ons Compound Assignment x += y ; equals to x = x + y ; Nested Assignments x = y = z = 0 ; equals to x = (y = (z = 0)) ; x -= y = z ; equals to x -= (y = z) ; x = y += z ; equals to x = (y += z) ; 58

Increment/Decrement Operators Post- increment/- decrement Use the value then increase/decrease Nota<on: i++ or i- - i = 5; j = (i++) * 2; à i = 6 and j = 10 Pre- increment/- decrement Increase/Decrease the value then use Nota<on: ++i or - - i i = 5; j = (++i) * 2; à i = 6 and j = 12 Invalid Usage Examples ++(i-3) ++(++i) 2 * i++ -i à ambiguous, compiler-dependent 59

printf printf( formatted text,exp1,exp2,...); Use placeholders for variables: %d int %f float %c char Examples: printf( Hello world!\n ); printf( %d plus %d is %d\n, x, y, x+y); Slide credit: Bert Huang 60

Increment/Decrement Operators int main(void) { int a = 0, b = 0, c = 0; a = ++b + ++c; printf( \n%d %d %d, a,b,c); a = b++ + c++; printf( \n%d %d %d, a,b,c); a = ++b + c++; printf( \n%d %d %d, a,b,c); a = b-- + --c; printf( \n%d %d %d, a,b,c); 2 1 1 2 2 2 5 3 3 5 2 2 } return 0; 61

scanf scanf( formatted text,&var1, &var2,...); %c a single character is expected in the input %d an integer is expected in the input %f a floa<ng point is expected in the input Each argument must be a pointer to the variable where the results of input are to be stored. 62

Standard Input and Output Example #include<stdio.h> int main(void) { float principal, rate, interest; int years; printf( principal, rate, and years? ); scanf( %f %f %d, &principal, &rate, &years); rate /= 100; interest = principal * rate * years; printf( interest = %f\n, interest); Expects two float and one integer numbers as input (from keyboard) } return 0; Prints a float number (on to the screen) 63

Type Conversion and Cas/ng If operands are of mixed data types, the compiler will convert one operand to agree with the other using the following hierarchy structure: long double (highest) double float long int char/short (lowest) 64

Implicit Cas/ng Done automa<cally by the compiler whenever data from different types is intermixed int i; double x = 17.7; i = x; float x; int i = 17; x = i; i = 17 x = 17.0 65

Explicit Cas/ng int total_score = 333, num_students = 4; float average; average=total_score/num_students; printf("average score (no casting) is %.2f\n", average); average=(float)total_score/(float)num_students; printf("average score (with casting) is %.2f\n", average); Average score (no cas<ng) is 83.00 Average score (with cas<ng) is 83.25 66

Effects of Cas/ng Cas<ng a float as an int causes trunca<on float a = 3.1; int x = (int) a; /* x is now 3 */ Be careful with math: float a, b, c; int x = 2, y = 3; a = x/y; /* what happens here? */ b = (float)x/y; c = (float)x / (float)y; Slide credit: Bert Huang 67

Summary Introduc/on to Programming Basic Concepts Developing Algorithms Crea<ng Flowcharts The C Programming Language Your first C Program Programming Process Lexical Elements of a C Program Keywords, Iden<fiers, Constants, Data Types, Operators Standard Input and Output Type Conversion and Cas<ng 68

Next week Condi/onal Branching Logical Expressions if and If- else statements switch statement goto statement 69