Review Questions:
int a[5];contain? Which is the first element? The last?
int a[5]; for(i = 1; i <= 5; i = i + 1) a[i] = 0;
int i = 5; int *ip = &i;then what is ip? What is its value?
*ip++ = 0;do?
char c; int *ip = &c; /* WRONG */is in error; you can't mix char pointers and int pointers like this. How, then, is is possible to write
char *cp = malloc(10); int *ip = malloc(sizeof(int));without error on either line?
Tutorial Section
/* print an addition table for 1+1 up to 10+10 */
#include <stdio.h>
int main()
{
int i, j;
/* print header line: */
printf(" ");
for(j = 1; j <= 10; j = j + 1)
printf(" %3d", j);
printf("\n");
/* print table: */
for(i = 1; i <= 10; i = i + 1)
{
printf("%2d", i);
for(j = 1; j <= 10; j = j + 1)
printf(" %3d", i + j);
printf("\n");
}
return 0;
}
The first j loop prints the top, header row of the table.
(The initial printf(" ");
is to make it line up with the rows beneath,
which will all begin with a value of i.)
Then, the i loop prints the rest of the table,
one row per value of i.
For each value of i, we print that value
(on the left edge of the table),
and then print the sums
resulting from adding that value of i
to ten different values of j
(using a second, inner loop on j).
#include <stdio.h>
int main()
{
int i, j;
for(i = 1; i <= 10; i = i + 1)
{
for(j = 1; j <= 10; j = j + 1)
{
if((i + j) % 2 == 0)
printf("* ");
else printf(" ");
}
printf("\n");
}
return 0;
}
(Why are there parentheses around
i + j
in the expression
(i + j) % 2
?
What if they were left out?)
#include <stdio.h>
int main()
{
int i;
int squares[11]; /* [0..10]; [0] ignored */
/* fill array: */
for(i = 1; i <= 10; i = i + 1)
squares[i] = i * i;
/* print table: */
printf("n\tsquare\n");
for(i = 1; i <= 10; i = i + 1)
printf("%d\t%d\n", i, squares[i]);
return 0;
}
There's one slight trick in the declaration of the squares array.
Remember that arrays in C are based at 0.
So if we wanted an array to hold the squares of 10 numbers,
and if we declared it as
int squares[10];
the array's 10 elements would range from
squares[0] to squares[9].
This program wants to use elements
from squares[1] to squares[10],
so it simply declares the array as having size 11,
and wastes the 0th element.
Exercises
int a[] = {1, 2, 3, 4, 5, 6};
(The answer, of course, should be 21).
while(there's another line)
{
if(line contains word)
print the line;
}
Use the strstr function (mentioned in the notes) to look for the
word. Be sure to include the line
#include <string.h>at the top of the source file where you call strstr.