# Tutorial 7 question2. Part a Prototype: Void cycle (char str1[], char str2[], int n); scanf("%s %d",str1,&n); cycle(str1,str2,n); printf("%s",str2); input.

## Presentation on theme: "Tutorial 7 question2. Part a Prototype: Void cycle (char str1[], char str2[], int n); scanf("%s %d",str1,&n); cycle(str1,str2,n); printf("%s",str2); input."— Presentation transcript:

Tutorial 7 question2

Part a Prototype: Void cycle (char str1[], char str2[], int n); scanf("%s %d",str1,&n); cycle(str1,str2,n); printf("%s",str2); input output Number of times

void cycle(char str1[], char str2[], int n) { int length=0,k=0; char temp; length = strlen(str1); //length of string strcpy(str2,str1); if (strlen(str1)<=3) { return; } 012345 abcdef

k= length - 2;//position n-1 while(n>0) { temp = str2[k]; while(k>1) { str2[k]=str2[k-1]; k--; } k = length - 2; str2[1]=temp; n--; } 012345 abcdef 012345 abbcdf 012345 aebcdf

Part b Prototype: Void scramble (char str1[], char str2[]); srand(time(NULL)); //time based seeding scanf("%s %d",str1,&n); scramble(str1,str2); printf("%s",str2); input output

void scramble(char str1[], char str2[]) { int n; int max; if (strlen(str1)<=3) { printf("%s",str1); return; } else max = strlen(str1) -1;

012345 abcdef 012345 abbcdf 012345 aebcdf 012345 adebcf 012345 acdebf 012345 abcdef 012345012345

n = rand()%max; cycle(str1, str2, n); printf("%s",str2); for(n=0;n<=100;n++) str2[n]='\0'; for(n=0;n<=100;n++) str1[n]='\0'; return; }

Part c fscanfScrambleprintf

FILE *inFile; inFile = fopen("original.txt","r"); if (inFile == NULL) { printf("FIle open error!\n"); return 0; } while(fscanf(inFile,"%s",str1)==1) { scramble(str1,str2); printf(" "); } fclose(inFile);

Part d Fscanf 2 files strcmpn++cyclePrintf(n)

char str1[100]={'\0'},str2[100]={'\0'},str3[100]={'\0'}; int n=0; FILE *inFile; FILE *inFile2; inFile = fopen("original.txt","r"); inFile2 = fopen("scramble.txt","r"); if ((inFile == NULL)||(inFile2 == NULL)) { printf("FIle open error!\n"); return 0; }

while(fscanf(inFile,"%s",str1)==1) { n=0; fscanf(inFile2,"%s",str3); strcpy(str2,str1); while(strcmp(str2,str3)) { n++; cycle(str1,str2,n); } printf("%d ",n); } fclose(inFile);

Problems encounter When I index the string to What happen is that “printf(“%s”,str2);” never print out anything According to lecture 8 notes(p.10) it will print until the first occurrence of ‘\0’ 123456 abcdef

Floating point exception if (strlen(str1)<=3) { printf("%s",str1); return; } else max = strlen(str1) -2; n = rand()%max;

Download ppt "Tutorial 7 question2. Part a Prototype: Void cycle (char str1[], char str2[], int n); scanf("%s %d",str1,&n); cycle(str1,str2,n); printf("%s",str2); input."

Similar presentations