Example 6.1 assign 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 to ten elements in turn, and output in reverse order
#include<stdio.h> int main() { int i,a[10]; for(i=0;i<=9;i++) scanf("%d",&a[i]); for(i=9;1>=0;i--) printf("%d",a[i]); return 0; }
Example 6.2 use array to process Fibonacci sequence
#include<stdio.h> int main() { int a[20]={1,1}; int i; for(i=2;i<20;i++) a[i]=a[i-2]+a[i-1]; for(i=0;i<20;i++) { if(i%5==0) printf("\n"); printf("%d",a[i]); } printf("\n"); return 0; }
Example 6.3 the area of ten areas is required to be output from small to large
#include<stdio.h> int main() { int i,j,t,a[10]; printf("Please enter ten areas\n"); for(i=0;i<10;i++) scanf("%d",&a[i]); for(j=0;j<10;j++) { for(i=0;i<9-j;i++) if(a[i]>a[i+1]) { t=a[i]; a[i]=a[i+1]; a[i+1]=t; } } for(i=0;i<10;i++) printf("%5d",a[i]); printf("\n"); return 0; }
Example 6.4 interchange elements of row and column of a two-dimensional array
#include<stdio.h> int main() { int a[2][3]={1,2,3,4,5,6}; int b[3][2],i,j; printf("The original array is\n"); for(i=0;i<2;i++) { for(j=0;j<3;j++) {printf("%3d",a[i][j]); b[j][i]=a[i][j]; } printf("\n"); } printf("The array after exchange is\n"); for(i=0;i<3;i++) {for(j=0;j<2;j++) printf("%3d",b[i][j]); printf("\n"); } return 0; }
Example 6.5 has an array of 3 * 4, which requires the output of the maximum number, as well as its row number and column number
#include<stdio.h> int main() { int a[3][4]={1,2,3,4,9,8,7,6,-10,10,-5,2},i,j; int row=0,colum=0,max; max=a[0][0]; for(i=0;i<3;i++) { for(j=0;j<4;j++) if(a[i][j]>max) max=a[i][j]; } printf("%d",max); printf("row=%d\ncolum=%d\n",row,colum); return 0; }
Example 6.6 output a known string
#include<stdio.h> int main() { char c[15]={'I',' ','a','m',' ','a',' ','s','t','u','d','e','n','t','.'}; int i; for(i=0;i<15;i++) printf("%d",c[i]); printf("\n"); return 0; }
Example 6.7 output a diamond
#include<stdio.h> int main() { char c[][5]={{' ',' ','*'},{' ','*',' ','*'},{'*',' ',' ',' ','*'},{' ','*',' ','*'},{' ',' ','*'}}; int i,j; for(i=0;i<5;i++) {for(j=0;j<5;j++) printf("%c",c[i][j]); printf("\n"); } return 0; }
Example 6.8 input a line of characters to determine how many words there are
int main() { int num=0,word=0,i,string[81]; printf("Please enter a line of characters\n"); gets(string); for(i=0;(c=string[i])!='\0';i++) { if(c==' ') word=0; else if(word==0) {num++;word=1;} } printf("This string contains%d Word\n",num); return 0; }
Example 6.9 has three strings, asking for the largest one
#include<stdio.h> int main() { char str[3][20]; char string[20]; int i; for(i=0;i<3;i++) gets(str[i]); if(strcmp(str[0],str[1])<0) strcpy(string,str[1]); else strcpy(string,str[0]); if(strcmp(string,str[2])<0) strcpy(string,str[2]); printf("Maximum characters are%s\n",string); return 0; }