Program Control : Repetition
Repetition used to repeat one or more
instruction for a certain amount of time. There are kinds of repetitions :
- - For
- -While
- - Do – While
The Use of For
for(exp1; exp2; exp3) statement;
exp1 : initialization
exp2 : conditional
exp3 : increment or decrement
Example of For
#include<stdio.h>
int
main()
{
int x;
for( x = 1
; x <= 10
; x++ )
printf( "%d\n", x );
return(0);
}
The Use of While
while
(exp)
statements;
or:
while(exp){
statement1;
statement2;
…..
}
Example of While
int counter = 1;
while ( counter <= 10 ) {
printf( "%d\n", counter
);
++counter;
}
The Use of Do - While
do{
< statements >;
}
while(exp);
Example of Do - While
int counter=0;
do {
printf( "%d ", counter );
++counter;
} while (counter <= 10);
Pointers
and Arrays
Pointer
is a variable that store the address of another variable, the operators are : *
(content of) and &(address of).
Example:
int i, *ptr;
ptr = &i;
To assign a new
value to the variable pointed by the pointer:
*ptr = 5; /* means i=5 */
An array is a
collection of data items, all of the same type, accessed using a common name.
Example :
int A[10];
Assigning Value to an element
Example : A[6] = 15; A[3] = 27
Array Program Examples
There are two types of Array:
- One Dimensional Array
- Two Dimensional Array
Example of One Dimensional Array
Example of Two Dimensional Array
int a[3][4];
Example : A[6] = 15; A[3] = 27
Array Program Examples
#include <stdio.h>
void main()
{
int
i;
int
list_int[10];
for
(i=0; i<10; i++){
list_int[i] = i + 1;
printf( "list_int[%d] init with
%d.\n", i, list_int[i]);
}
} There are two types of Array:
- One Dimensional Array
- Two Dimensional Array
Example of One Dimensional Array
#include<stdio.h>
int SIZE = 5;
void main() {
int
i, j;
int
n[SIZE] = {15, 9, 1, 7, 5};
for(
i=0 ; i<= SIZE ; i++) {
printf("%5d
", n[i]);
for (
j=1; j<=n[i] ; j++) printf("%c","*");
printf("\n");
}
}Example of Two Dimensional Array
int a[3][4];


No comments:
Post a Comment