print 2 numbers and skip 2 numbers in an array in C - c

I'm having a bit of difficulty trying to figure out a way to print some numbers in an array. I have an array[0,1,2,3,4,5,6] and I would like print the numbers 0,1,4,5. Is it possible to create a loop that can read the first two numbers skipping the next two and reading the following two numbers.

You can simply use modulo operation on current index to check if this number belongs to "print 2" or "skip 2":
int a[17];
int length = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < length; i++)
{
if (i % 4 < 2)
printf("%d ", a[i]);
}
So, for i equal to 0 and 1, it will output value. For i == 2 and i == 3, the condition will result to false. Next, it will take 4, 4 % 4 is 0, and it will repeat it every 4 steps.

Pseudocode:
arr = [0,1,2,3,4,5,6];
skip = 2;
print = true;
while(i < arr.length){
for(j = 0; j < skip; ++j){
if(print){
output arr[i];
}
//increment array counter
i++;
//toggle print bool
print = !print
}
}
Just change the value of skip to set the interval, and set print = false if you'd like it to skip the first skip entries

Related

How to loop for a specific amount

I am writing a program that would iterate through a sequence of characters, where every 4 counts would add the iterated 4 characters into a char array which means that it must be able to constantly be updating every 4 counts.
For example,
The sequence:
char sequence[32] = "qRiM1uOtGgXl5yuNPJwKo4+bAdQuPUbr";
I want a loop that would be able to get every four characters, which in this case the first 4 characters is "qRiM".
Then I would want it to be stored in a char array:
char test[4]; (This must be able to print qRiM)
Then when 4 counts has been done then the cycle would repeat where the next 4 characters would be "1uOt"
I've tried to attempt this but it would only print out qRiM and that the test[4] array is not updating.
int count_steps = 0;
for (int i = 0; i < 32; i++) {
// Adds a character from a sequence into the test array until 4
while(count_steps < 4) {
test[i] = sequence[i];
count_steps++;
}
// Checks if four counts has been done
if (count_steps == 4) {
//decoder(test, decoded_test);
// Prints out the four characters
for(int j = 0; j < 4; j++) {
printf("%c\n", test[j]);
}
// Resets back to 0
count_steps = 0;
}
else {
continue;
}
}
With details explaination from torstenvl, you can rewrite code:
for (int i = 0; i < 32; i++) {
test[i%4] = sequence[i];
if ((i+1) % 4 == 0) {
printf("\n");
for(int j = 0; j < 4; j++) {
printf("%c\n", test[j]);
}
}
}
test[i] = sequence[i];
This line assigns the ith entry in test to the ith entry in sequence. But test only has 4 entries, so on the second iteration, you are writing to test[4] throught test[7]. You need to use count_steps as the index in test.
You also need to add count_steps to i when accessing sequence so that the correct index in sequence is set in test.
And since you're adding processing 4 characters in each iteration of the for loop, you need to increment i by 4, not by 1
demo
for (int i = 0; i < 32; i += 4/* increment by 4 */) {
// Adds a character from a sequence into the test array until 4
while(count_steps < 4) {
test[count_steps] = sequence[i + count_steps]; // use count_steps as index in test and offset in sequence
count_steps++;
}
...
}

First number in array not transferring to new array correctly

I am writing a program to break numbers in an array into their digits then store those digits in a new array. I have two problems:
It does not display the first number in the array (2) when transferred to the second array, and I am not entirely sure why.
The array may contain 0's, which would break my current for loop. Is there another way to implement a for loop to only run for as many numbers are stored in a array without knowing how big the array is?
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
// Setting an array equal to test variables
int sum[50] = { 2, 6, 3, 10, 32, 64 };
int i, l, k = 0, sumdig[10], dig = 0;
// Runs for every digit in array sum, increases size of separate variable k every time loop runs
for (i = 0; sum[i] > 0; i++ && k++)
{
sumdig[k] = sum[i] % 10;
dig++;
sum[i] /= 10;
// If statement checks to see if the number was two digits
if (sum[i] > 0)
{
// Advancing a place in the array
k++;
// Setting the new array position equal to the
sumdig[k] = sum[i] % 10;
dig++;
}
}
// For testing purposes - looking to see what digits have been stored
for (l = 0; l < dig; l++)
{
printf("%i\n", sumdig[l]);
}
}
This is the output:
6
3
0
1
2
3
4
6
0
Solution:
It does not display the first number in the array (2) when transferred to the second array
changes i++ && k++ into i++,k++
Is there another way to implement a for loop to only run for as many numbers are stored in an array
There are many different ways but here is some to illustrate it in a few different scenarios:
1. The array length is known and fixed:
Let the compiler automatically allocate the array for you. And then for(i=0; i<6; i++)
2. Able to calc the array length:
Then count the number of elements when initializing the array into a varible. Then just for(i=0; i<SizeCount; i++)
3. Not-able to know array size for some reason:
It is rare but, in that case, you can pre-set a stop criteria i.e. -1 or some other flag so that you can stop when it reaches the terminator i.e. set or pre-set all other values of sum to be -1. Then you can while(sum[i] != -1) This is how string lengths work in C, either with NULL termination (string end with the number 0 or value NULL) or, with input, the line break character \n indicating a termination.
DEMO
Here is a demo of full code with some explanation:
#include <stdio.h>
int main(void){
int sum[] = {2, 6, 3, 10, 32, 64}; // compiler is smart enough know the size
int i, k = 0, sumdig[10], dig = 0;
// Runs for every digit in array sum, increases size of seperate variable k everytime loop runs
for(i = 0; i < sizeof(sum)/sizeof(int); i++, k++){
sumdig[k] = sum[i] % 10;
dig++;
sum[i] /= 10;
// If statement checks to see if the number was two digits
if (sum[i] > 0)
{
// Advancing a place in the array
k++;
// Setting the new array position equal to the
sumdig[k] = sum[i] % 10;
dig++;
}
}
// For testing purposes - looking to see what digits have been stored
for(i = 0; i < dig; i++){
printf("%i\n", sumdig[i]);
}
}
Compile and run
gcc -Wall demo.c -o demo
./demo
Output
2
6
3
0
1
2
3
4
6

How to make a series that adds up by 5 every 5 counts using for loop?

I'm kind of new in C programming and I'm trying to make a program that prints the nth term of a series and every 5 counts, it adds up by 5.
Example: 1, 2, 3, 4, 9, 10, 11, 12, 17, 18, 19, 20, 25......
Here is my code
int num,digit,count = 1;
printf("Enter n: ");
scanf("%d", &num);
for(int i=1; i<=num; i++){
count++;
if(count > 5){
count = 0;
i+=4;
}
printf("%d ",i);
}
My code doesn't get to the specific nth term that I'm asking for. For example, I've inputted 10 and it only shows up until the 6th term
The thing to do is get clear in your head what you want to do and how you are going to do it. Rather than tinkering with code, break things down into simple parts and make them clear.
#include <stdio.h>
int main(void)
{
int num = 10;
// Method 1: Spell everything out.
// i counts number of terms printed.
// j counts number of terms since last multiple of four terms.
// k is current term.
for (
int i = 0, j = 0, k = 1; // Initialize all counters.
i < num; // Continue until num terms are printed.
++i) // Update count.
{
printf("%d ", k); // Print current term.
++j; // Increment four-beat count.
if (4 <= j)
{
// Every fourth term, reset j and increment the term by 5.
j = 0;
k += 5;
}
else
// Otherwise, increment the term by 1.
k += 1;
}
printf("\n");
// Method 2: Use one counter and calculate term.
// Iterate i to print num terms.
for (int i = 0; i < num; ++i)
/* Break the loop count into two parts: the number of groups of 4
(i/4) and a subcount within each group (i%4). Looking at the
starts of each group (1, 9, 17, 25...), we see each is eight
greater than the previous one. So we multiply the group number by
8 to get the right offsets for them. Within each group, the term
increments by 1, so we use i%4 directly (effectively multiplied by
1). Then (i/4)*8 + i%4 would start us at 0 for i=0, but we want to
start at 1, so we add 1.
*/
printf("%d ", (i/4)*8 + i%4 + 1);
printf("\n");
}
You shall not change the variable i within the body of the for loop.
You need to introduce one more variable that will store the current outputted number.
Here is a demonstration program.
#include <stdio.h>
int main(void)
{
unsigned int n = 0;
printf( "Enter n: " );
scanf( "%u", &n );
for ( unsigned int i = 0, value = 0, count = 1; i < n; i++ )
{
if ( count == 5 )
{
value += 5;
count = 1;
}
else
{
++value;
}
printf( "%u ", value );
++count;
}
}
The program output is
Enter n: 13
1 2 3 4 9 10 11 12 17 18 19 20 25
Here's another take that I think is a bit less complicated, with explanations in the comments:
#include <stdio.h>
int main(void)
{
int num, count = 1;
num = 20;
// if you look closely, you actually have an initial condition before the
// main pattern starts. Once the pattern starts, its actually every _fourth_
// term that gets added by 5. You'll make things easier on yourself if you
// print out this initial condition, then handle the pattern in the loop.
// If you really want to be correct, you can wrap this in a if (num > 0) check
printf("%d ", count++);
// start at 1, because we already printed the first item
for(int i=1; i<num; i++, count++)
{
// now we can focus on every fourth term
if (i % 4 == 0)
{
// if it's the fourth one, add 5 to the previous value
// Of course this simplifies to count += 4
count = (count-1) + 5;
}
printf("%d ",count);
}
}
Demonstration

How to remove memory directions from an empty vector

I'm starting into C programming and my english is not the best, so I'll try to explain myself the best i can...
I was trying to do a program that generates random numbers, pairs and odd numbers, and saves those numbers into two different vectors...
So it looks like this
#include <stdio.h>
#include <stdlib.h>
#define ARRAYSIZE 6
void main()
{
int randomNumber, position, pairVector[ARRAYSIZE], oddVector[ARRAYSIZE];
srand(time(NULL));
for (position = 0; position < ARRAYSIZE; position++)
{
randomNumber = rand() % 49 + 0;
if (randomNumber % 2 == 0)
pairVector[position] = randomNumber;
else
oddVector[position] = randomNumber;
}
// Loop to print all the pair random numbers
for (position = 0; position < ARRAYSIZE; position++)
{
if(pairVector[position] >= 0)
printf("%d ", pairVector[position]);
}
// Separation of the pair and odd numbers
printf("\n\n\n");
// Loop to print all the odd random numbers
for (position = 0; position < ARRAYSIZE; position++)
{
if (oddVector[position] >= 0)
printf("%d ", oddVector[position]);
}
}
As u can see, I have 2 loops to print pairs and odd numbers, this numbers are printed with 2 loops, so here goes my question...
Without the condition >= 0 in the vector inside the loop, I got printed some memory directions (because if I have a size of 6 ints but only 3 numbers (pair or odd), the other 3 directions are printed too)... What can I do to remove those directions from the printed vector without the condition? Maybe pointers?
Thanks in advice and sorry for my bad english.
You can set the both arrays elements at 0
for(position = 0; position < ARRAYSIZE; position++)
pairVector[position] = 0;
do it for the both arrays and your arrays will be filled with 0 (zeroes), next fill up your arrays with rand numbers, so you will have something like
example: 24, 22, 58, 0, 0, 0
when you want to printout array, just go something like
for(position = 0; position < ARRAYSIZE; position++)
{
if(pairVector[position] != 0)
printf("%d ", pairVector[position]);
}
Due to the fact that you don't know when the arrays are gonna be filled completely, I suggest you to do a while loop until the both arrays are filled.
void main()
{
int randomNumber, position, pairVector[ARRAYSIZE], oddVector[ARRAYSIZE];
srand(time(NULL));
int pairIndex, oddIndex;
pairIndex = oddIndex = 0; // you will increment them once you find a number for regarding array
while ((pairIndex < ARRAYSIZE) || (oddIndex < ARRAYSIZE) )
{
randomNumber = rand() % 49 + 0;
if (randomNumber % 2 == 0){
if (pairIndex<ARRAYSIZE)
pairVector[pairIndex++] = randomNumber;
}
else{
if (oddIndex<ARRAYSIZE)
oddVector[oddIndex++] = randomNumber;
}
}
// Loop to print all the pair random numbers
for (position = 0; position < ARRAYSIZE; position++)
{
if(pairVector[position] >= 0)
printf("%d ", pairVector[position]);
}
// Separation of the pair and odd numbers
printf("\n\n\n");
// Loop to print all the odd random numbers
for (position = 0; position < ARRAYSIZE; position++)
{
if (oddVector[position] >= 0)
printf("%d ", oddVector[position]);
}
}
In your approach the loop went through only 6 times and for sure one or both arrays could be incomplete. In the solution above you will fill both arrays and then you print them.

What needs to be modified to get desired result in this C code

I have written a small piece of code that would perform Run length encoding kind of stuff on 1-D array but still far from desired result.
main()
{
int a[8]={2,0,0,0,3,0,0,9};
int i,temp,ct=0,flag,m;
int found[90]={0};
for(i=0;i<=7;i++)
{
if(!a[i])
{
ct++;
if(!found[a[i]])
{
flag=i;
found[a[i]]=1;
}
}
}
a[flag]=ct;
m=ct;
for(i=0;i<m;i++)
{
printf("%d",a[i]);
}
}/* end of main*/
Now for above array i would like to have output something below
2 5 0 3 9
But with my piece of code am getting
2 5 0 0 3
Can I have any suggestion on that?
Shouldn't run length encoding turn 2,0,0,0,3,0,0,9 into 2 1 0 3 3 1 2 0 9 1?
1) The first thing I see is wrong is that you aren't looking at the entire array. You're using < to stop before 8, but also stopping at 7, so you only evaluate array items 0 - 6.
2) If ct stands for count it's never reset (ct=0 only on declaration). Also it's assignment is this: a[flag]= ct; which overwrites your original data. It basically tracks the value of i.
This is my version I've just put together:
#define SZ 8
main()
{
int a[SZ]={2,0,0,0,3,0,0,9};
int i; //absolute position
int runningCount = 1; //because we start at array index 1 and not zero
for (i = 1; i <= SZ; i++) {
if (a[i - 1] == a[i]) //value same as one before it...
runningCount++;
else { // new value found. print last one, and the count of the last one.
printf("%d %d ", a[i - 1], runningCount);
runningCount = 1; //reset for next loop
}
}
return 0;
}
The output is 2 1 0 3 3 1 0 2 9 1
Ok based on the comment left below, your algorithm would actually look like this:
#define SZ 8
main()
{
int a[SZ]={2,0,0,0,3,0,0,9};
int i; //absolute position
int zero_count = 0; //target zeros specifically...
for (i = 0; i < SZ; i++) {
if (a[i] == 0)
zero_count++;
}
//now write it out in a bizarre, unparsable format again...
for (i = 0; i < SZ; i++) {
if (a[i] != 0) //write out all non zero values
printf("%d ", a[i]);
if (i == 0) { //this says put the zero count after the first number was printed
printf("%d 0 ", zero_count); //inserting it into a strange place in the array
}
}
return 0;
}
which outputs: 2 5 0 3 9
You need a <= in your for loop:
for(i=0;i<=7;i++)
instead of
for(i=0;i< 7;i++)
Otherwise you miss the last element.
All you appear to be doing is (a) counting the number of times 0 occurs in the array, and (b) replacing the first occurrence of 0 with that count. It's not clear how this is meant to be a useful encoding.
In any case, you're not getting your desired result, at least in part, because you're only modifying one element of the array. I suspect what you want, or at least think you want, is to shift the non-zero elements of the array to the left as you encounter them.
What is the utility of compressing the array in the way you propose? Is some other piece of code going to have to reconstruct the original, and if so how do you expect to do so from your desired result?

Resources