w3resource

C Exercises: Fill the array elements with number o to n – 1 repeated times


Fill array with repeated values up to a given number

Write a C program that reads an array of integers (length 10), fills it with numbers from o to a (given number) n – 1 repeatedly, where 2 ≤ n ≤ 10.

Sample Solution:

C Code:

#include <stdio.h>
int main ()
{
  int n, i, array_nums[10], k;

  // Prompt user for input
  printf("Input an integer (2-10)\n");
  scanf("%d", &n);

  if (n >= 2 && n <= 10)
  {
    k = 0;

    // Loop to fill array with sequential numbers, starting from 0
    for (i = 0; i < 10; i++)
    {
      array_nums[i] = k;
      k++;

      if (k == n)
      {
        k = 0;
      }
    }

    // Loop to print array elements
    for (i = 0; i < 10; i++)
    {
      printf("array_nums[%d] = %d\n", i, array_nums[i]);
    }
  }
  return 0; // End of program
}

Sample Output:

Input an integer (2-10)
8
array_nums[0] = 0
array_nums[1] = 1
array_nums[2] = 2
array_nums[3] = 3
array_nums[4] = 4
array_nums[5] = 5
array_nums[6] = 6
array_nums[7] = 7
array_nums[8] = 0
array_nums[9] = 1

Flowchart:

C Programming Flowchart: Fill the array elements with number o to n – 1 repeated times.


For more Practice: Solve these Related Problems:

  • Write a C program to fill an array cyclically with values from 0 to n-1 using modulo arithmetic.
  • Write a C program to generate a repeating sequence for an array of fixed length based on a user-specified range.
  • Write a C program to populate an array by iterating through numbers 0 to n-1 repeatedly until the array is full.
  • Write a C program to create an array with a cyclic pattern using nested loops and the modulo operator.

Go to:


PREV : Reverse the first and last elements of an array.
NEXT : Replace array elements with one-third of the previous.

C programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.