Computer Programming I UP ITTC AY 2009-2010
Control Structures Lesson 4
Control Structures Kinds
Sequence Control Structures Selection Control Structures
of Control Structures
if if-else switch
Repetition Control Structures
while do-while for
Sequential Program int main() { statement1; statement2; …. statementN; }
statement1
statement2
statementN
if Statement
used to conditionally execute a statement or block of statement.
if (expression) statement;
True or False
In C, every expression has a numeric value An expression is ‘true’ when its value is nonzero it is false it evaluates to zero. Therefore, in the following – if (expression) statement statement is executed if expression evaluates to non-zero.
if-else Statement if (expression) statement1; else statement2;
if expression is false, statement2 is executed both statements can be (and very often are) replaced by blocks of statements (“compound statements”) The else portion is optional.
Multiple if-else constructs
Multiple if-else constructs can also be used to choose between three of more options. TRUE
if (expression1) statement1; else if (expression2) statement2; else statement3;
expression1
statement1
FALSE expression2 FALSE statement3
rest of program
TRUE
statement2
The conditional or ternary operator: ‘?: ‘
The ?: operator is a more efficient form for expressing simple if statements.
It has the following form: <expression1>? <expression2>: <expression3>
It simply states: if (<expression1>) <expression2>; else <expression3>;
The conditional or ternary operator: ‘?: ‘
Example:
Suppose we want to assign the maximum of a and b to z. Using the ? operator, we have the following statement: z = (a > b) ? a : b;
which is the same as: if (a > b)
z = a; else
z = b;
Exercise 6
Write two version of a program using if-else and the conditional operator to determine whether a year is a leap year or not. Hint: Any year exactly divisible by 4 is a leap year. However, if that same year is exactly divisible by 100 it is not, unless it is also exactly divisible by 400.
switch Statement
A multi-way conditional statement similar to the if … else if … else … allows the selection of an arbitrary number of choices based on an integer value switch (<expression>) { case
: <statements> case : <statements> …. …. case : <statements> default : <statements> }
switch Statement
expression must have an integer value (char, int)
when the switch statement is executed: the expression is evaluated if a case matches the value of the expression, the program jumps to the first statement after that case label otherwise, the default case is selected the default is optional
while loop The while loop has the following while ()
syntax:
<statement>
where,
The boolean_expression in the syntax can be any expression that evaluates to TRUE or FALSE only. The statement can be either a simple statement or a compound statement.
while loop FALSE expression
The statement is executed as long as condition is true. The loop terminates when the condition is no longer true.
TRUE statement/s
rest of program
while loop Here
is a simple example of the use of the while loop: i=1 while (i<=5) { printf("%d",i); i++; }
while loop There
are some things you have to remember when using the while loop. First
and foremost is that the while loop must terminate eventually. This means that you have to make sure that the boolean expression must evaluate to FALSE at some foreseeable point. Loops that do not terminate are called infinite loops.
do-while loop statement/s TRUE
do { statement(s); } while ( condition );
condition FALSE rest of program
Similar to while loops Except the condition is evaluated after the loop body The loop body is always executed at least once, even if the expression is never true
do-while loop Example:
i=1; do { printf("%d", i); i++; } while (i<=5);
for loop initialization
for ( ; ; ) { statement(s); }
condition
statement(s)
increment
rest of program
break and continue C
provides two commands to control how we loop:
break – to exit from a loop or a switch continue – skip an iteration of the loop
Exercise 7
Write a program that prints a 10 x 10 multiplication table. Write a program that ask the user to enter a number from 1 to 12 and prints the corresponding month. Example: 1 January, 2 February
Subprograms Lesson 5
Introduction C
provided subprograms Procedures Scope of identifiers Parameters Functions
Subprograms
A subprogram is a sequence of program statements that have common goals. There are two types of subprograms:
Procedures Functions
The difference between a procedure and a function is that a function returns a value (of a specific type) after it finishes executing.
C-provided Subprograms C
provides us with a lot of procedures and functions that we can use for our different purposes. All we need to do is to “include” the header where the procedure/function belongs to by using the #include precompiler directive.
C-provided Subprograms Here
are some of the most popular C procedures and functions: printf – prints formatted text on screen (stdio.h) scanf – read formatted text from keyboard(stdio.h)
C-provided Subprograms Here
are some of the most popular C procedures and functions:
strcpy – copies one string to another (string.h) strcmp – compares two strings (string.h) strlen – gets the length of a string (string.h)
Procedures The syntax for definition of a procedure: void <procedure_name> () { <statements> }
Procedures A
procedure should be called by a running function before it will be executed. This is also true for functions. To call: <procedure_name>();
Procedures Example: void p(int n) {
} TO CALL:/*placed in function that will run*/ p(1); p(i); /* assume: int i = 1; */
Scope of identifiers
In C, there is such a thing as the scope of an identifier. The scope of an identifier is confined in the block where it is declared. All the variables/constants that are declared at the start of a block is said to be local with respect to everything outside the block, but is said to be global with respect to everything inside the block.
Parameter Passing Parameter
passing
A way of passing information from one subprogram to another.
Parameter Passing There
are two types of parameters:
Formal parameters Actual parameters
Functions As
was said before, functions are different from procedures only in the sense that, when called, it returns a value of a specific type to whatever procedure or function that called it. Otherwise, they are very much the same.
Functions Here
is the syntax for the definition of functions: () { <statements> }
Procedure/Function Declaration
The following are the syntax for procedure and function declaration, respectively. void<procedure_name>(); ();
We do not really need to use subprogram declarations. That is if all functions called are placed before the calling function.
Lesson Review
A subprogram is a sequence of program statements that have common goals. There are two types of subprograms: Procedures and Functions. The difference between a procedure and a function is that a function returns a value (of a specific type) after it finishes executing. C provides us with a lot of procedures and functions that we can use for our different purposes.
Lesson Review
In C, there is such a thing as the scope of an identifier. The scope of an identifier is confined in the block where it is declared. Parameter passing is a way of passing information from one subprogram to another. There are two types of parameters: Formal parameters are the variables found in the heading of the declaration of a procedure. Formal parameters are considered as local variables. Actual parameters are the variables or expressions used when calling the procedure.
Exercise 9 Write
a function named min that takes two integers as its parameters and returns the value of the smaller of the two parameters. Write a program that uses the function in the previous problem to determine the smallest of five integers inputted by the user.
Arrays, Strings and Pointers Lesson 6
Introduction
Arrays Strings Pointers
Arrays
C provides us with a way to declare a group of data items and give them a common name. This is called array.
Arrays are declared in the following manner: <array_name> [ ]; where
data_type can be any type discussed so far array_name is an identifier num_elements is a constant integer value greater than 0
Arrays
Examples: int number[100]; float grade[10]; char str[50];
Accessing Array Data
Each element in an array is considered as a single variable and is accessed via its index.
The syntax for accessing a single element in an array is as follows: <array_name> [] where
index is an expression that evaluates to an integer. In using the index, it is important to remember that the ith element is accessed using an index of i-1
Initializing Arrays
You can optionally initialize an array in the declaration itself. The syntax for an array declaration with initialization is: <array_name> [] = { , , ...}; Example: float grade[10] = {83.5, 97.5, 71.0, 88.0};
Strings
When declaring an array of characters, add one to num_elements to accommodate the ‘\0’ (null terminator character) which marks the end of the string. For example, if you want to store a name that can be at most 30 characters, the declaration should be: char name[31]; when you use scanf to let the user enter a string of characters. scanf("%s", name); scanf
appends ‘\0’ to the end of the string inputted.
Strings
You may also initialize an array of characters with a string constant. So instead of doing it like this, char name[31] = {'V', 'a', 'n'};
you can do it like this, char name[31] = "Van";
but you can’t assign a string constant to it with an assignment statement.
name = "Van";
/* Error: ... */
Strings
C provides you with the functions to manipulate strings. Whenever you want to use these functions, don’t forget to add the preprocessor directive #include <string.h>.
Strings
To assign a string to a string variable, you must use strcpy. char name[31]; strcpy (name, "van");
To compare two strings, use strcmp. if strcmp(name, "van") == 0){ // strcmp returns 0 if they are the same printf("Your name contains 3 characters."); }
Strings
To find the length of a string, use strlen. if (strlen(name) == 3) printf("Your name contains 3 characters.");
To append to the end of a string, use strcat. strcat (name, "essa"); printf("Now your name is vanessa.");
Pointers
A pointer, in its simplest term, is a variable which points at certain memory location.
In much the same way as an integer variable contains a number and a character variable contains a single character, a pointer, a pointer variable contains the address of a memory location.
Uses of Pointers
C uses pointers to create dynamic data structures – data structures built up from blocks of memory allocated from the heap at run-time.
C uses pointers to handle variable parameters passed to functions.
Pointers in C provide an alternative way to access information stored in arrays. Pointer techniques are especially valuable when you work with strings. There is an intimate link between arrays and pointers in C.
Pointers
Pointers that point to a specific data types hold the addresses of either characters, integers, floats, or the like. The syntax for declaring pointers is as follows: *; Examples: int *i_ptr; char *c_ptr; float *f_ptr;
Pointers
In C, we get the address of any variable by using the following syntax: &
Let’s say that we have three other variables: char ch; int num; float dec;
Pointers
And so, we can now perform the following assignment operations: c_ptr = &ch; i_ptr = # f_ptr = &dec;
Pointers
How do we reference the value inside the memory location pointed to by a pointer variable? The syntax for doing this is as follows: *<pointer_variable_name>
Pointers
As an example, we have here a simple C program which writes the letter ‘R’ on screen: #include <stdio.h> main() { char *c_ptr, ch; ch = 'R'; c_ptr = &ch; printf("%c", *c_ptr); }
The method of accessing the value pointed at by a pointer variable is called dereferencing or indirection.
Pointers and Arrays: Pointer Arithmetic
Pointers and arrays are so closely related to each other that they have a correspondence.
If p points to an object in array of the same type: (p + 1) points to the next object in the array (p + i) points to the ith object in the array *(p + 1) refers to the value of the next object in the array *(p + i) refers to the value of the ith object p points to
Lesson Review
C provides us with a way to declare a group of data items and give them a common name. This is called array. Each element in an array is considered as a single variable and is accessed via its index. C provides you with the functions to manipulate strings. Whenever you want to use these functions, don’t forget to add the preprocessor directive #include <string.h>. A pointer, in its simplest term, is a variable which points at certain memory location.
Exercise 10 Write
a function int getMaximum( int anData[], int nNum ) which returns the highest number among the nNum data items stored in the array anData. Write a function int getMaximum( int *pnData, int nNum ) which returns the highest number among the nNum data items stored in the array pnData.
Exercise 11 Write
a function void reverseString(char* str) which reverses a string parameter. For example, if the input is “string”, the output should be “gnirts” . Write a function void toUpperCase(char* str) which converts all lower case letters contained in a string to upper case letters. For example, if the input is “2 String(s)”, the output should be “2 STRING(S)”.
End