Home > Article > Backend Development > In C language, count the number of 1's in the array after N moves
Given an array of size N. The array is initially all zeros. The task is to count. The number of 1's in the array after N moves. Each Nth step has an associated rule. The rule is -
The first move-change the element at position 1, 2, 3, 4………….
th The second move - change the elements at positions 2, 4, 6, 8... ……..
Count the number of 1’s in the last array.
Arr[]={ 0,0,0,0 } N=4
Output
Number of 1s in the array after N moves − 2
Explanation - Array after subsequent movement-
Move 1: { 1,1,1,1 } Move 2: { 1,0,1,0 } Move 3: { 1,0,0,3 } Move 4: { 1,0,0,1 } Number of ones in the final array is 2.
Input
Arr[]={ 0,0,0,0,0,0} N=6
Output
Number of 1s in the array after N moves − 2
Explanation - Array after subsequent movement-
Move 1: { 1,1,1,1,1,1,1 } Move 2: { 1,0,1,0,1,0,1 } Move 3: { 1,0,0,1,0,0,1 } Move 4: { 1,0,0,0,1,0,0 } Move 5: { 1,0,0,0,0,1,0 } Move 4: { 1,0,0,0,0,0,1 } Number of ones in the final array is 2.
The method used in the following program is as follows
Function Onecount takes an Arr[] and its size N as input and returns no. The number in the final array after N moves.
The for loop starts from 1 and goes to the end of the array.
Each i represents step i.
Nested for loop starts at index 0 and goes to the end of the array.
For each i-th move, if index j is a multiple of i (j%i==0), replace 0 at that position with 1.
Continue this process for each i until the end of the array.
Finally traverse the entire array again, counting no. It contains 1 and is stored in the count.
#include <stdio.h> int Onecount(int arr[], int N){ for (int i = 1; i <= N; i++) { for (int j = i; j <= N; j++) { // If j is divisible by i if (j % i == 0) { if (arr[j - 1] == 0) arr[j - 1] = 1; // Convert 0 to 1 else arr[j - 1] = 0; // Convert 1 to 0 } } } int count = 0; for (int i = 0; i < N; i++) if (arr[i] == 1) count++; // count number of 1's return count; } int main(){ int size = 6; int Arr[6] = { 0 }; printf("Number of 1s in the array after N moves: %d", Onecount(Arr, size)); return 0; }
If we run the above code, it will generate the following output-
Number of 1s in the array after N moves: 2
The above is the detailed content of In C language, count the number of 1's in the array after N moves. For more information, please follow other related articles on the PHP Chinese website!