C progaming 4 chapters
-
Upload
itcoolboy9 -
Category
Documents
-
view
244 -
download
4
description
Transcript of C progaming 4 chapters
1
Programming Methodology I in C/C++
CHAPTER IFirst Program
Basic Input and Output
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
3
Processes of Creating C Program
Editing Compiling Linking Executing
4
Editing C source code Used Editor or called IDE to
create source file Source file extension is *.c
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)
6
Linking Add require code module from
program Library Libraries supplied as part of C. Output is a executable file File extension *.exe
7
Executing The execution stage is where
your program, having completed all the previous processes successfully.
Ctrl+F9 (Run Program)
8
Hello, World/* Hello, World program */#include <stdio.h>
int main(){printf(“Hello, World!\n”);return 0;
}
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
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
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)
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.
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)
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
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
16
Review of Hello, World/* Hello, World program */#include <stdio.h>
int main(){printf(“Hello, World!\n”);return 0;
}
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
18
Hello, World Revisited/* Hello, World program */#include <stdio.h> int main(){ printf(“Hello, World!\n”);return 0;} Works exactly the same as before
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
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?
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
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
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
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
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
26
Good printf Example#include <stdio.h>int main(){printf(“===================\n”);printf(“ Hello, World! \n”);printf(“===================\n“);
return 0;}
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)
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
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
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.)
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
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.
33
Example Flowchart Flowchart for
calculating gross wage
A sequence of instruction
start
inputrate of pay
inputhours
worked
calculategross wage
outputgross wage
stop
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
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
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
37
Programming Methodology in C/C++
CHAPTER IIIProgram Elements
Part 2: Constants, Operators and Expression
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
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.
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;
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
42
Operators Operator act on an operands
Assignment: = Arithmetic: + - * / % Increment/decrement: ++ --
Relational: > >= < <=
Equality: == != Logical: || &&
43
Assignment The = symbol is called assignment
operator
assigns the value on the right to the variable on the left e.g.: rate=4050;
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
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
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
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!
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)
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
}
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.
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
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.
53
Programming Methodology I in C/C++
CHAPTER IIElements of a Program
Part 1: variable and function
54
Elements of a Program main( ) function #include directive variable definition or declaration function prototype program statements function definition comments
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
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
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
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).
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…
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
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
62
Variable declaration syntax:
Type_name var_name;
example: int dollar; int riel, rate; double price_perunit; char sex;
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;
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 ) ;
65
Function Definition from line 26 to 29
26: int sum(int x, int y) 27: { 28: return (x + y); 29: }
Function body
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.
67
main( ) function special function that must be
defined in c program.
Function name must defined with English word main and follow by parenthesis.
68
main() function (cont.)int main(){
/* statements or commands goes here*//* this block called compound statements */
return 0;}
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 */
}
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…
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 ;
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”);
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.
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
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.
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.
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 ;
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
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!”);}
80
Block { … } statements or commands place
inside the curly brackets { }
block statement can be called compound statement.
81
Programming Methodology in C/C++
CHAPTER IVControl Flow Statements
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
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.
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.”);
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.
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.”);
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.
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.”);
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.
90
The switch statement (cont.)
switch( integer_expression ){
case constant_expression_1:statement_1;break;
.......case constant_expression_n:
statement_n;break;
defalut:statement;
}
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.
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.”);
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);
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?
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);
}
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.
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
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 */
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.
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!