Professional Documents
Culture Documents
do
{
Code to execute at least once
} while ( condition );
Do … while Example
#include <stdio.h>
int main()
{
int x;
x = 0;
do
{
/* "Hello, world!" is printed at least one time even though the condition is
false*/
printf( “Hello, world!\n” );
} while ( x != 0 );
getchar();
return 0;
}
Break and Continue
• Two keywords that are very important
to looping are break and continue.
This program will loop and print the value of x, except when x=2 or
x=4, then stop the iteration and continue with t next iteration.
Arrays
• An array lets you declare and work with
a collection of values of the same type.
For example, you might want to create
a collection of five integers. One way to
do it would be to declare five integers
directly:
– int a, b, c, d, e;
• An easier way is to declare an array of
five integers:
– int a[5];
Array, Cont.
• The five separate integers
inside the previous array are
accessed by an index.
• All arrays start at index zero
and go to n-1 in C. Thus, int
a[5]; contains five elements.
For example:
– int a[5];
• a[0] = 12; a[1] = 9; a[2] = 14;
a[3] = 5; a[4] = 1;
Array, Cont.
• One of the benefits of array indexing is
that you can use a loop to manipulate
the index. For example, the following
code initializes all of the values in the
array to 0:
int a[5];
int i;
for (i=0; i<5; i++)
a[i] = 0;
Array Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[MAX];
int i,rtotal=0;
/* fill array */
for (i=0; i < MAX; i++)
a[i]=2*i;
printf("a[i]\t value \t rtotal \n -------------------------------------\n");
for (i=0; i < MAX; i++)
{
rtotal+=a[i];
printf("a[%d]\t%d\t%d\n",i,a[i],rtotal);
}
system("pause");
return 0;
}
Output of the Array Example
Strings
• A string in C is simply an array of
characters. The following line declares
an array that can hold a string of up to
99 characters.
– char str[100];
– str[0] is the first character of the string,
str[1] is the second character, and so on.
str[99]=0 or ‘\0\?
– Because C uses null-terminated strings,
which means that the end of any string is
marked by the ASCII value 0 (the null
Array declaration /
initializing
• char str[15];
• char course[6]={‘M’,’E’,’3’,’2’,’5’,’\0’};
• char course[]=“ME325”;
• int x[3]={5,6,8};
int main()
{
char course[]="ME325";
int i=0;
printf("Course: %s\n\n",course);
printf("index\tchar\tcode\n");
for (i=0; i < 6; i++) /* fill array */
printf("%d\t%c\t%d\n",i,course[i],course[i]);
system("pause");
return 0;
}
This example will print the sentence Course: ME325 then a table showing each
character as character and ASCII code