Programming Methodology I in C/C++ CHAPTER I First Program Basic Input and Output 1
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
2
Processes of Creating C Program
Editing Compiling Linking Executing
3
Editing
C source code Used Editor or called IDE to create source file Source file extension is *.c
4
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) 5
Linking
Add require code module from program Library Libraries supplied as part of C. Output is a executable file File extension *.exe
6
Executing ď Ž
ď Ž
The execution stage is where your program, having completed all the previous processes successfully. Ctrl+F9 (Run Program)
7
Hello, World /* Hello, World program */ #include <stdio.h> int main() { printf(â&#x20AC;&#x153;Hello, World!\nâ&#x20AC;?); return 0; }
8
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 9
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 10
Hello, World: Line by Line int 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) 11
Hello, World: Line by Line int 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. 12
Hello, World: Line By Line printf(“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) 13
Hello, World: Line by Line printf(“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 14
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 15
Review of Hello, World /* Hello, World program */ #include <stdio.h> int main() { printf(â&#x20AC;&#x153;Hello, World!\nâ&#x20AC;?); return 0; }
16
Important Basic Rules for C
Lines of code end with a semicolon Strings are enclosed inside doublequotes Functions start and end with curly brackets Whitespace doesn’t matter
17
Hello, World Revisited /* Hello, World program */ #include <stdio.h> int main () { printf(“Hello, World!\n”); return 0;}
Works exactly the same as before 18
Hello, World Revisited /* Hello, World program */ #include <stdio.h> int main() { printf(“Hello, World!\n”); return 0; }
Also works exactly the same as before 19
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? 20
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 21
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 22
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
23
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 24
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 25
Good printf Example #include <stdio.h> int main() { printf(“===================\n”); printf(“ Hello, World! \n”); printf(“===================\n“); return 0; } 26
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) 27
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
28
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 29
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.)
30
Flowchart
Process:
Selection:
Process: Showing the action in a program. example: x/3; x=5; Selection: Conditional expression doing with True or False.
Input/Output:
Input/Out put: Output or input data from/in process 31
Flowchart
Data Flow:
Data Flow: Indicate the flows of data from one symbol to another.
Connector:
Connector: Combine or Connect one Flowchart to another.
32
start
Example Flowchart ď Ž
ď Ž
Flowchart for calculating gross wage A sequence of instruction
input rate of pay input hours worked calculate gross wage
output gross wage
stop 33
Example Flowchart Flowchart showing selection
34
start
input rate of pay
Example Flowchart
set counter to zero
input hours worked
Flowchart showing repetition
calculate gross wage
output gross wage
increase counter by 1
No
counter =5? Yes
stop
35
start
Example Flowchart
input rate of pay
set counter to zero
input hours worked
Flowchart showing selection and repetition
No
hours >40?
calculate gross without overtime
Yes calculate gross with overtime
output gross wage
increase counter by 1
No
counter =5? Yes
stop
36
Programming Methodology in C/C++ CHAPTER III Program Elements Part 2: Constants, Operators and Expression 37
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
38
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.
39
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; 40
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 41
Operators
Operator act on an operands
Assignment: = Arithmetic: + - * / % Increment/decrement: ++ - Relational: > >= < <= Equality: == != Logical: || &&
42
Assignment
The = symbol is called assignment operator
assigns the value on the right to the variable on the left
e.g.: rate=4050;
43
Arithmetic Operators ď Ž
There are five arithmetic operators: Operator
Symbol
Example
Addition
+
Y = a + b;
Subtraction
-
Y = a - b;
Multiplication
*
Y = a * b;
Division
/
Y = a / b;
Modulus (get the reminder)
%
Y = 5%3; ==>y=2
44
Arithmetic
Arithmetic examples
y x f g y z
= = = = = =
5; y + 2 * f / x / x %
3; 4; 3.0; 3; 3;
// // // // //
// y x is f is g is y is z is
is now 5 now 8 now 8.0 now 2.6…67 now 2 now 2
45
Increment and Decrement operators Operator Symbol Increment ++
Action
Examples
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 46
Increment/Decrement operator Example: x = 5; f = 2.5; x++; f--; ++f; --x;
// // // //
x f f x
is is is is
now now now now
6 1.5 2.5 5
y = ++x â&#x20AC;&#x201C; 2; // x = 6, y = 2 g = f-- + 2; // f = 1.5, g = 4.5! 47
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 5==1 7>1 7!=1 (2*2) == (3+1)
Evaluates (Result) 0 (false) 1 (true) 1 (true) 1 (true) 48
Relational x f y g
= = = =
5; 6.0; (x > f); // y = 0 (false) (x <= f); // g = 1 (true)
// usually used in conditionals if (x > f) { // do something }
49
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 false Ex. !(5 >= 4) false (0), because the operand is true. 50
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 51
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. 52
Programming Methodology I in C/C++ CHAPTER II Elements of a Program Part 1: variable and function 53
Elements of a Program
main( ) function #include directive variable definition or declaration function prototype program statements function definition comments 54
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 55
#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 56
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 program57
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). 58
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…
59
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 60
ď Ž
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 Bytes require Range of value (Type_Name) Character Integer Singleprecision Doubleprecision
char
1
0 to 255
int
2
float
4
double
8
-32768 to +32767 1.2E-38 to +3.4E38 2.2E-308 to +1.8E308 61
Variable declaration
syntax: Type_name var_name;
example:
int dollar; int riel, rate; double price_perunit; char sex; 62
Variable declaration (cont.) /* string variable containing 100 characters or array of character variable */ ď&#x201A;§
char address[100];
/* two different variables with the same name */ ď&#x201A;§
double person, PERSON;
63
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 ) ; 64
Function Definition ď Ž
from line 26 to 29 26: 27: 28: 29:
int sum(int x, int y) { Function body return (x + y); }
65
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. 66
main( ) function
ď Ž
special function that must be defined in c program.
ď Ž
Function name must defined with English word main and follow by parenthesis.
67
main() function (cont.) int main() { /* statements or commands goes here*/ /* this block called compound statements */ return 0;
} 68
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 */ } 69
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…
70
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 ; 71
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’);
72
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. 73
Format characters Table Format Character %d %u %ld %f %lf %c %s
Description Integer value unsigned integer value long integer value float value double or long float value Character value String value 74
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. 75
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. 76
return statement (line 28) ď Ž
ď Ž
28: return (x + y); return statement return a value to the calling function. Syntax: return expression ; or return (expression) ; Ex. return x+y ; 77
Function demonstrate return st. c=sum( a , b);
send values to function
Value to send back
int sum(int x, int y) { return (x + y); } 78
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!”); }
79
Block { … }
statements or commands place inside the curly brackets { }
block statement can be called compound statement.
80
Programming Methodology in C/C++ CHAPTER IV Control Flow Statements
81
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 82
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. 83
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.”); 84
The if-else statements ď Ž
Closely related to the if statement. if (<condition>) statement1; else statement2; Next_statement ; ď Ž
ď Ž
if condition is true, statement1 is executed and statement2 is skipped. if condition is false, statement1 is skipped and statement2 is executed. 85
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.”);
86
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.
87
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.”); 88
The switch Statement ď Ž
ď Ž
ď Ž
The switch statement is a multi-way conditional statement generalizing the ifelse statement. The general form of the switch statement is given by switch (<condition>) statement Where statement is typically a compound statement containing case labels and optionally a default label. 89
The switch statement (cont.) switch( integer_expression ) { case constant_expression_1: statement_1; break; ....... case constant_expression_n: statement_n; break; defalut: statement; } 90
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.
ď Ž
91
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.”); 92
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);
93
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? 94
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); }
95
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.
96
The break example int i; for(i=1; i<=10; i++) { printf(“for loop %d\n”, i); if( i==3 ) break; } printf(“Finish for loop here!”);
The Output for loop 1 for loop 2 for loop 3 Finish for loop here
97
The break st. example for (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 */ 98
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.
99
continue example int i; for(i=1; i<=5; i++) { printf(“loop %d \n”, i); if( i < 4 ) continue; printf(“Visit me!\n”); }
The Output loop 1 loop 2 loop 3 loop 4 Visit me! loop 5 Visit me!
100