C progaming 4 chapters

100
1 Programming Methodology I in C/C++ CHAPTER I First Program Basic Input and Output

description

 

Transcript of C progaming 4 chapters

Page 1: C progaming 4 chapters

1

Programming Methodology I in C/C++

CHAPTER IFirst Program

Basic Input and Output

Page 2: C progaming 4 chapters

2

Overview writing program for today’s

examples Hello, World – a first program Hello, World – line by line Basic rules for C Tips for good programming style Basic Input/Output

Page 3: C progaming 4 chapters

3

Processes of Creating C Program

Editing Compiling Linking Executing

Page 4: C progaming 4 chapters

4

Editing C source code Used Editor or called IDE to

create source file Source file extension is *.c

Page 5: C progaming 4 chapters

5

Compiling Complier convert source code

into computer language (Binary 0 1)

Detect and report errors Out put called Object Code

(extension *.Obj) ALT+F9 (Compile)

Page 6: C progaming 4 chapters

6

Linking Add require code module from

program Library Libraries supplied as part of C. Output is a executable file File extension *.exe

Page 7: C progaming 4 chapters

7

Executing The execution stage is where

your program, having completed all the previous processes successfully.

Ctrl+F9 (Run Program)

Page 8: C progaming 4 chapters

8

Hello, World/* Hello, World program */#include <stdio.h>

int main(){printf(“Hello, World!\n”);return 0;

}

Page 9: C progaming 4 chapters

9

Hello, World: Line by Line/* Hello, World program */ /* */ marks a comment block Can go anywhere inside a program Anything in comments is ignored

by the compiler Extremely useful for including

explanatory information

Page 10: C progaming 4 chapters

10

Hello, World: Line by Line#include <stdio.h> #include – a C preprocessor command

that lets you include the code from another file (such as a library)

stdio.h – the standard input-output library

#include <stdio.h> -- allows you to use code from the standard input library, printf() code function

Page 11: C progaming 4 chapters

11

Hello, World: Line by Lineint main() { ... } Code is contained in functions (also

called procedures) Curly brackets mark the start and end Every program needs an entry point

(somewhere to start running) The main() function is the entry point

for C programs (Start running program)

Page 12: C progaming 4 chapters

12

Hello, World: Line by Lineint main() { ... return 0; } The main() function should always be

defined with “int” or “void” before it. int main() indicates that main() returns an

integer value void main() indicates that main() returns

no value (nothing) Traditional UNIX rule: if everything goes

well in the program, main() should return 0.

Page 13: C progaming 4 chapters

13

Hello, World: Line By Lineprintf(“Hello, World!\n”);return 0; Lines of code that will be executed

by the program when it is run Should be able to figure out what each

line does! A line of code is terminated by a

semicolon ( ; ) Execution goes in order (top-down)

Page 14: C progaming 4 chapters

14

Hello, World: Line by Lineprintf(“Hello, World!\n”); Prints out the message “Hello, World!” printf()

A function from stdio.h Used to print messages out to the screen

To use a function, you type in its name, and put any information that the function needs (its arguments) inside the parentheses after the name

Page 15: C progaming 4 chapters

15

Hello, World: Line by Line“Hello, World!\n” A single letter, number, punctuation

mark, etc. is a character A series of characters grouped

together is a string Some special kinds of characters

exist \t – tab character \n – newline character

Page 16: C progaming 4 chapters

16

Review of Hello, World/* Hello, World program */#include <stdio.h>

int main(){printf(“Hello, World!\n”);return 0;

}

Page 17: C progaming 4 chapters

17

Important Basic Rules for C Lines of code end with a semicolon Strings are enclosed inside double-

quotes Functions start and end with curly

brackets Whitespace doesn’t matter

Page 18: C progaming 4 chapters

18

Hello, World Revisited/* Hello, World program */#include <stdio.h> int main(){ printf(“Hello, World!\n”);return 0;} Works exactly the same as before

Page 19: C progaming 4 chapters

19

Hello, World Revisited/* Hello, World program */

#include <stdio.h>int main()

{printf(“Hello, World!\n”);

return 0;}

Also works exactly the same as before

Page 20: C progaming 4 chapters

20

Hello, World Revisited/* Hello, World program */#include <stdio.h>int main(){printf(“Hello, World!\n”)return 0;

} Doesn’t work at all Can you see why?

Page 21: C progaming 4 chapters

21

Hello, World Revisited/* Hello, World program */#include <stdio.h>int main(){printf(“Hello, World!\n”);return 0;} Works fine But bad style – no indentation! Important for code to be easy to read

Page 22: C progaming 4 chapters

22

Programming Style Put brackets on separate lines by

themselves (some variations on this) After each open bracket, increase

indentation level by one tab After each close bracket, decrease

indentation level by one tab Leave blank lines between sections Don’t let lines get too long

Page 23: C progaming 4 chapters

23

Basic Input/Output Overview Types of input and output Basic output with printf() Basic input with scanf() Memorize this for now – more

understanding will come later

Page 24: C progaming 4 chapters

24

Types of Input/Output Input from the keyboard (standard input) Output to the screen (standard output) Input from/output to a file Input/output over a network connection Input from/output to another program We’ll be focusing on stdin/stdout for now

Page 25: C progaming 4 chapters

25

Basic output with printf printf() sends the message you pass

into it to standard output automatically

Messages can be just a plain string (“Hello, World!\n”)

Use spaces/tabs/newlines in printf() to make your output nicer

Build up output with multiple calls to printf to make your code nicer

Page 26: C progaming 4 chapters

26

Good printf Example#include <stdio.h>int main(){printf(“===================\n”);printf(“ Hello, World! \n”);printf(“===================\n“);

return 0;}

Page 27: C progaming 4 chapters

27

Bad printf Example#include <stdio.h>int main(){printf(“===================\n Hello, World! \n===================\n”);return 0;

} Unreadable – hard to see what output will be The output will get messed up if you put this

into notepad (long lines will be wrapped)

Page 28: C progaming 4 chapters

28

Basic Input with scanf A little trickier than printf Need somewhere for the program

to store the user’s input Two-step process

Set aside a place for the input to be stored

Get the input

Page 29: C progaming 4 chapters

29

Basic Input example#include <stdio.h>int main(){int a;scanf(“%d”, &a);

return 0;} a is the name of the place where the

input will be stored %d tell scanf that the input is a number

Page 30: C progaming 4 chapters

30

Flowcharts help programmer in solving

problem, its used a graphical. Flowchart symbol

Terminator: Terminator: Show where to Start (Begin)

and End (stop) the program (Usually used at the beginning and the end of flowchart.)

Page 31: C progaming 4 chapters

31

Flowchart Process:

Process: Showing the action in a program. example: x/3; x=5;

Selection: Selection: Conditional expression doing

with True or False. Input/Output:

Input/Out put: Output or input data from/in process

Page 32: C progaming 4 chapters

32

Flowchart Data Flow:

Data Flow: Indicate the flows of data from one symbol to another.

Connector: Connector: Combine or Connect one

Flowchart to another.

Page 33: C progaming 4 chapters

33

Example Flowchart Flowchart for

calculating gross wage

A sequence of instruction

start

inputrate of pay

inputhours

worked

calculategross wage

outputgross wage

stop

Page 34: C progaming 4 chapters

34

Example Flowchart

calculategross with overtime

hours>40?

start

inputrate of pay

inputhours

worked

calculategross wage

without overtime

outputgross wage

stop

No YesFlowchart showing selection

Page 35: C progaming 4 chapters

35

Example Flowchart

Flowchart showing repetition

counter=5?

start

inputrate of pay

inputhours

worked

calculategross wage

outputgross wage

stop

set counter to zero

increase counterby 1

No

Yes

Page 36: C progaming 4 chapters

36

Example Flowchart

calculategross withovertime

counter=5?

start

inputrate of pay

inputhours

worked

calculategross without

overtime

outputgross wage

stop

set counter to zero

increase counterby 1

No

Yes

hours>40?No YesFlowchart showing

selection and repetition

Page 37: C progaming 4 chapters

37

Programming Methodology in C/C++

CHAPTER IIIProgram Elements

Part 2: Constants, Operators and Expression

Page 38: C progaming 4 chapters

38

Constant Like variables, constants are data storage

locations. Constants don't change value. You must initialize a constant when you

create it, and you cannot assign a new value later.

Two type of constants in C/C++: Literal Constants Symbolic Constants

Page 39: C progaming 4 chapters

39

Literal Constant

A literal constant is a value typed directly into your program wherever it is needed. For example: int myAge = 39;

myAge is a variable of type int 39 is a literal constant.

Page 40: C progaming 4 chapters

40

Symbolic Constants A symbolic constant is a constant that

is represented by a name. after a constant is initialized, its value

can't be changed. Two ways to declare a symbolic

constant: With #define directive:

#define STUDENT_PER_CLASS 15 #define TAX_RATE 0.1

With const keyword const int STUDENT_PER_CLASS = 15;

Page 41: C progaming 4 chapters

41

Operators & Expression

An operator is a symbol that causes the compiler to take an action

Operators act on operands. Ex.

Riel = dollar * rate;

operator operands Expression: combination of

operator(s) and operands

Page 42: C progaming 4 chapters

42

Operators Operator act on an operands

Assignment: = Arithmetic: + - * / % Increment/decrement: ++ --

Relational: > >= < <=

Equality: == != Logical: || &&

Page 43: C progaming 4 chapters

43

Assignment The = symbol is called assignment

operator

assigns the value on the right to the variable on the left e.g.: rate=4050;

Page 44: C progaming 4 chapters

44

Arithmetic Operators There are five arithmetic operators:

Operator Symbol ExampleAddition + Y = a + b;

Subtraction - Y = a - b;

Multiplication * Y = a * b;

Division / Y = a / b;

Modulus (get the reminder) % Y = 5%3; ==>y=2

Page 45: C progaming 4 chapters

45

Arithmetic

Arithmetic examples

y = 5; // y is now 5x = y + 3; // x is now 8f = 2 * 4; // f is now 8.0g = f / 3.0; // g is now 2.6…67y = x / 3; // y is now 2z = x % 3; // z is now 2

Page 46: C progaming 4 chapters

46

Increment and Decrement operators

Operator

Symbol Action Examples

Increment

++ Increments the operand by one

++x, x++

Decrement

-- Decrements the operand by one

--x, x--

++x; <==> x=x+1; --x; <==> x=x-1;

Note: ++x; prefix increment operator x++; postfix increment operator

Page 47: C progaming 4 chapters

47

Increment/Decrement operator

Example:x = 5;f = 2.5;x++; // x is now 6f--; // f is now 1.5++f; // f is now 2.5--x; // x is now 5

y = ++x – 2; // x = 6, y = 2g = f-- + 2; // f = 1.5, g = 4.5!

Page 48: C progaming 4 chapters

48

Relational Operators Operators are used to determine whether two

numbers are equal or if one is greater or less than the other.

Every relational statement evaluates to either 1 (TRUE) or 0 (FALSE).

==, <, >, !=, <=, >=

Expression Evaluates (Result)5==1 0 (false)7>1 1 (true)7!=1 1 (true)(2*2) == (3+1) 1 (true)

Page 49: C progaming 4 chapters

49

Relationalx = 5;f = 6.0;y = (x > f); // y = 0 (false)g = (x <= f); // g = 1 (true)

// usually used in conditionalsif (x > f) { // do something

}

Page 50: C progaming 4 chapters

50

Logical Operators Combine many Relational Operator together

E.g.: (x == 5) && (y == 5)

Operator Symbol Example

AND && exp1 && exp2 True (1) only if both exp1 and exp2 are true; false (0) otherwise.

Ex. (5 == 5) && (6 != 2) True (1), because both operands are true

OR || exp1 || exp2 True (1) if either exp1 or exp2 is true; false (0) only if both are false.

Ex. (0 > 1) || (6 > 1) True (1), because one operand is true

NOT ! !exp1 False (0) if exp1 is true; true (1) if exp1 is falseEx. !(5 >= 4) false (0), because the operand is true.

Page 51: C progaming 4 chapters

51

Operator Precedence

Parentheses in Arithmetic expressions 2*(3+3*(1+4))==36 ? 2*3+3*(1+4) ==36 ?

Operators Precedence() 1* / % 2+ - 3< <= > >= 4&& || ! 5

Page 52: C progaming 4 chapters

52

Type Casting In Arithmetic Expression

int i, m=3, n=2; float x; i=m/n; ==> i=1 int i, m=3, n=2;float x;x=m/(float)n; ==> x=1.5

(float)n is called Typecast, change integer value n to float value.

Page 53: C progaming 4 chapters

53

Programming Methodology I in C/C++

CHAPTER IIElements of a Program

Part 1: variable and function

Page 54: C progaming 4 chapters

54

Elements of a Program main( ) function #include directive variable definition or declaration function prototype program statements function definition comments

Page 55: C progaming 4 chapters

55

Definition of Functions Functions used to group codes or statements

that together accomplish a single larger task. program can send information or value to

function through parameters. value in function can send back to program through the return statement E.G., the printf() function contains many

statements that together accomplish the task of printing a message out to the screen

Page 56: C progaming 4 chapters

56

#include Directive (Line 2)2: #include <stdio.h>

used by the compiler to add code from header file to ours program.

#include<stdio.h> stdio.h called include file or library file #include is also called pre-processor

command

Page 57: C progaming 4 chapters

57

The Global Declarations before the main() function: before line 6

Define Directives Constant Declarations Type Declarations Variable Declarations Function Prototype/Definition

can be used anywhere in the program

Page 58: C progaming 4 chapters

58

Variable Declaration (Line 4)

4: int a, b, c; Used to store the values, information or

data within the program (a, b, c are variables)

Values can change as the program runs variable declarations define the name

of variable (variable name) and type of value variable will store (data type).

Page 59: C progaming 4 chapters

59

Variable Elements variable name (var_name) a string of one or more letters and

digits, but a name must begin with: At least one letter Include underscore character ( _ ) Case sensitive ( e.g. a is not the same as A) Avoid using C Keywords as a variable name

Example of keyword: int, void…

Page 60: C progaming 4 chapters

60

variable name, example Variable name, right or wrong?

salary year2_student 1numst computer$5 integer float

Two different variables with the same name Person person

Page 61: C progaming 4 chapters

61

Variable Elements (cont.) data type (Type_name)

Indicates what kind of information or value can be stored in the variable (see data type table)

Variable Type

Keyword(Type_Name

)

Bytes require

Range of value

Character char 1 0 to 255Integer int 2 -32768 to

+32767 Single-precision

float 4 1.2E-38 to +3.4E38

Double-precision

double 8 2.2E-308 to +1.8E308

Page 62: C progaming 4 chapters

62

Variable declaration syntax:

Type_name var_name;

example: int dollar; int riel, rate; double price_perunit; char sex;

Page 63: C progaming 4 chapters

63

Variable declaration (cont.)

/* string variable containing 100 characters or array of character variable */

char address[100];

/* two different variables with the same name */ double person, PERSON;

Page 64: C progaming 4 chapters

64

Function Prototype (line 6) 6: int sum(int x, int y);

define return type, name and arguments of function that use in the program to the compiler.

Function Prototype also called function declaration.

syntax:type_name FunctionName

( parameterList ) ;

Page 65: C progaming 4 chapters

65

Function Definition from line 26 to 29

26: int sum(int x, int y) 27: { 28: return (x + y); 29: }

Function body

Page 66: C progaming 4 chapters

66

Function definition A function definition specifies the

name of the function, the types and number of parameters and its return type.

A function definition also includes a function body, the statements that determine what the function does.

Page 67: C progaming 4 chapters

67

main( ) function special function that must be

defined in c program.

Function name must defined with English word main and follow by parenthesis.

Page 68: C progaming 4 chapters

68

main() function (cont.)int main(){

/* statements or commands goes here*//* this block called compound statements */

return 0;}

Page 69: C progaming 4 chapters

69

main() function (cont.)void main(){

/* statements or commands goes here *//* this block called compound statements */

/* no need return 0; statement */}syntax: type main (parameter lists)

{/* compound statement */

}

Page 70: C progaming 4 chapters

70

Program Statements lines 11, 12, 15, 16, 19, 20, 22, 28

all lines of code that end with a semicolon ; is called a statements

An example of statements are: print string to screen, read input from keyboard, mathematical calculations, calling functions, etc…

Page 71: C progaming 4 chapters

71

Statements and White Space Tabs, spaces, and blank lines are

consider as a white space. ignore by the compiler. eg.

x=3+5; can be written as: x = 3 + 5 ; or x = 2

+ 3 ;

Page 72: C progaming 4 chapters

72

printf, basic output statement used to print out messages to the screen A printf message can be a string or a

placeholders for values to be substituted into

syntax: printf(Formatstring,exp1,exp2,…);

printf(“Number: %d”, 5); printf(“Character: %c”, ‘a’); printf(“A string: %s”, “Hello, World”);

Page 73: C progaming 4 chapters

73

printf (cont.) printing the variable contents

(value)

printf ("%d Add %d = %d\n", a, b, c);

%d, %s , %c are called format character conversion, its convert to/from another data type string.

Page 74: C progaming 4 chapters

74

Format characters TableFormat Character Description

%d Integer value%u unsigned integer value%ld long integer value%f float value%lf double or long float value%c Character value%s String value

Page 75: C progaming 4 chapters

75

scanf, basic input statement

used to read a value or a text from keyboard to the variables store in memory.

Like printf in reverse – instead of writing variables in, reading them in.

syntax: scanf(Formatstring,var1,var2,…); var1,var2,…: are a variables name Formatstring: what kind of data will be

input in to those variables.

Page 76: C progaming 4 chapters

76

scanf example int x,y,z; printf(“Enter number: “); scanf(“%d”, &x); printf(“Enter two numbers”); scanf(“%d%d”,&y,&z);

int a; char ch; char addr[100]; /* string variable */ scanf(“%d%c%s”, &a, &ch, addr); & (ampersand) symbol is an address of variable in

memory.

Page 77: C progaming 4 chapters

77

return statement (line 28)28: return (x + y);

return statement return a value to the calling function.

Syntax:return expression ; orreturn (expression) ;Ex. return x+y ;

Page 78: C progaming 4 chapters

78

Function demonstrate return st.

c=sum( a , b);

int sum(int x, int y){ return (x + y);}

send values to functionValue to send

back

Page 79: C progaming 4 chapters

79

void and return statement There is no return statement at the end

of function, if type name declare as void.

void printHello(){ clrscr(); printf(“\nHello world!”);}

Page 80: C progaming 4 chapters

80

Block { … } statements or commands place

inside the curly brackets { }

block statement can be called compound statement.

Page 81: C progaming 4 chapters

81

Programming Methodology in C/C++

CHAPTER IVControl Flow Statements

Page 82: C progaming 4 chapters

82

Control Flow statements Usually all the statements in our programs

are executed strictly in sequence. Control Flow statements let you control the

sequence in which statements are executed.

Two type of control statements: Conditional statements: if , if-else, switch

statement Iteration statements or loop statements: while,

for, do-while

Page 83: C progaming 4 chapters

83

The if statements The general form of an if statement is:

if (<condition>) statement ;next_statement ;

if condition is true, then statement is executed; otherwise, statement is skipped.

After the if statement has been executed, control passes to the next_statement.

Page 84: C progaming 4 chapters

84

The if statement example Compare two number num1 and

num2

if(num1>num2) printf(“\nNum1 bigger than num2.”);if(num1<num2) printf(“\nNum1 smaller than num2.”);if(num1==num2) printf(“\nNum1 equal to num2.”);

Page 85: C progaming 4 chapters

85

The if-else statements Closely related to the if statement.

if (<condition>)statement1;

elsestatement2;

Next_statement ;

if condition is true, statement1 is executed and statement2 is skipped.

if condition is false, statement1 is skipped and statement2 is executed.

Page 86: C progaming 4 chapters

86

if-else examples Compare two number num1 and

num2

if(num1>num2) printf(“\nNum1 bigger than num2.”);else printf(“\nNum1 smaller than or equal

to num2.”);

Page 87: C progaming 4 chapters

87

If-Else If-Else If you have several different possibilities,

can chain together if-else statements

if (<condition1>) { statements;

} else if (<condition2>) statements;

} else { statements;

}

Statements that go along with the FIRST condition that is true are executed.

Page 88: C progaming 4 chapters

88

Compare two numbers/* declare num1 and num2 as integer *//* read input num1 and num2 */

if(num1>num2) printf(“\nnum1 bigger than num2.”); else if(num1<num2) printf(“\nnum1 smaller than num2.”);else printf(“\nnum1 equal to num2.”);

Page 89: C progaming 4 chapters

89

The switch Statement The switch statement is a multi-way

conditional statement generalizing the if-else statement.

The general form of the switch statement is given byswitch (<condition>)statement

Where statement is typically a compound statement containing case labels and optionally a default label.

Page 90: C progaming 4 chapters

90

The switch statement (cont.)

switch( integer_expression ){

case constant_expression_1:statement_1;break;

.......case constant_expression_n:

statement_n;break;

defalut:statement;

}

Page 91: C progaming 4 chapters

91

The While Statement The general form of a while statement is

while( <Condition> ){ statement ;}next_statement ;

First condition is evaluated. If is true, statement is executed, and control is passes back to the beginning of the while loop.

statement is executed repeatedly until condition is false, and the control passes to the next statement.

Page 92: C progaming 4 chapters

92

The while loop example print number from 1 to 5

i=1;

while(i<=5){ printf(“number %d\n”,i); ++i;}printf(“\nEnd of while statement.”);

Page 93: C progaming 4 chapters

93

The do loop statement Can be considered a variant of the while state. the do statement making its test at the bottom.

do block statement ;

while (condition);example: i=1;

do{ printf(“\nNumber %d”, i );

i++; }while(i<=5);

Page 94: C progaming 4 chapters

94

Positive integer number

int n;do{

printf(“\nEnter a positive integer: ”); scanf(“%d”,&n);}while (n <= 0);

Try: Input only M or F into sex variable?

Page 95: C progaming 4 chapters

95

For Loop Syntax for (<initialization>;

<condition>; <step>) { // steps }

for (<initialization>;<condition>;<step>) statements;

int i;for (i = 1; i <=5 ; i++) {

/* do steps */printf(“Number=%d\n”,i);

}

Page 96: C progaming 4 chapters

96

The break and continue statements In C/C++, the break and continue

statements are used to interrupt ordinary iterative flow of the control in loops.

break statement used to interrupt the normal flow of control within a loop.

The break statement is used within a switch statement, which can select among several cases.

Page 97: C progaming 4 chapters

97

The break exampleint i;for(i=1; i<=10; i++){ printf(“for loop %d\n”, i);

if( i==3 ) break;}printf(“Finish for loop

here!”);

The Outputfor loop 1for loop 2for loop 3Finish for loop here

Page 98: C progaming 4 chapters

98

The break st. examplefor (i=0; i<10; i++){

scanf(“%d”,&x);if (x<0 ){printf(“All done”);break; /*exit loop if value is negative*/}printf(“%d”,sqrt(x));

}/* break jumps to here */

Page 99: C progaming 4 chapters

99

The continue statement

The continue statement causes the current iteration of a loop to stop and causes the next iteration of the loop to begin immediately.

Page 100: C progaming 4 chapters

100

continue exampleint i;for(i=1; i<=5; i++){

printf(“loop %d \n”, i);

if( i < 4 ) continue; printf(“Visit me!\n”);

}

The Outputloop 1loop 2loop 3loop 4Visit me!loop 5Visit me!