基于第二阵列数据打印第一阵列数据的次数

时间:2013-12-09 09:53:44

标签: c arrays for-loop

抱歉标题结构不好,想不出怎么说出来。

无论如何,当涉及到C中的数组和循环时,我遇到了一个问题。我需要有一个用户输入5个字母并将它们存储在第一个数组中。然后我需要它们在1到10之间输入5个数字并将它们存储在第二个数组中。然后我需要根据在第二个数组中输入的相应数字打印第一个数组的数据。

例如,如果输入第一个数组的第一个字母是A,输入第二个数组的第一个数字是4,我需要打印出AAAA。

我知道我需要在某处使用for循环,我确信这会比while循环更好,因为我将知道循环中使用的所有数据。

到目前为止,这是我的代码,它并不多,但我讨厌问一个问题甚至没有一些代码。

干杯!

#include <stdio.h>
#include <stdlib.h>

int main() {

char input1[5];
int input2[5], i;

printf("Please enter a letter to be stored in the first array: \n");
scanf(" %c", &input1[0]);
printf("Please enter another letter to be stored in the first array: \n");
scanf(" %c", &input1[1]);
printf("Please enter another letter to be stored in the first array: \n");
scanf(" %c", &input1[2]);
printf("Please enter another letter to be stored in the first array: \n");
scanf(" %c", &input1[3]);
printf("Please enter a final letter to be stored in the first array: \n");
scanf(" %c", &input1[4]);
printf("The first array contains these values: %c, %c, %c, %c and %c. \n", input1[0],    input1[1], input1[2], input1[3], input1[4]);

printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[0]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[1]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[2]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[3]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[4]);
printf("The second array contains these values: %d, %d, %d, %d and %d \n", input2[0], input2[1], input2[2], input2[3], input26[4]);

2 个答案:

答案 0 :(得分:2)

for(i=0;i<5;i++){
  for(j=0;j<input2[i];j++){
    printf("%c",input1[i]);
  }
}

答案 1 :(得分:0)

代码:

for(i=0; i < input1.length; i++) {
   char charValue = input1[i];
   int loopNumber = input2[i];
   for(j=0 ;j < loopNumber; j++) {
      printf("%c" + charValue);
   }
}