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++;
}
...
}
Related
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
The aim of my C program is to take two arrays (both comprised of unique numbers) and merge the two of them into a new array, eliminating any numbers that are the same between both of them. However, when I try to merge the two, it instead prints back both arrays combined without eliminating any duplicates.
My program creates "array_C" by first adding in the elements from "array_A". Afterwards, it checks if there are duplicates between "array_B" and "array_C" using a counter variable. For every value in "array_C" that the for loop checks, if the value of "array_B" is not equal to the value in "array_C", the counter decreases by 1. If after all the values in "array_C" are checked, the counter is <= 0, that means there are no duplicates of that value in "array_C", and it should be added to the end of "array_C". I keep track of this using a "position" variable.
//Creation of array_C
int length_C = length_A + length_B;
int array_C[length_C];
//Copying array_A to array_C
for (i = 0; i < length_A; i++) {
array_C[i] = array_A[i];
}
//Checking array_C against array_B for duplicates
counter = length_A;
int position = length_A;
for (i = 0; i < length_B; i++) {
for (j = 0; j < length_C; j++) {
if (array_B[i] != array_C[j]) {
counter--;
} else {
counter++;
}
}
//this is the position tracker to add new value in array_C
if (counter <= 0) {
array_C[position] = array_B[i];
position++;
}
}
If I entered this:
Enter the length of array 1: 6
Enter the elements of the array: 1 2 3 4 5 6
Enter the length of array 2: 6
Enter the elements of the array: 3 4 5 6 7 8
I expect the results should look like this:
Here is the merged array:
1 2 3 4 5 6 7 8
But instead, it looks like this:
1 2 3 4 5 6 3 4 5 6 7 8
So apparently something is going wrong and it is not understanding that it should only add variables that are not duplicates.
Your logic is flawed. That's why you are getting unexpected outcome. See the following revision in your code:
for (i = 0; i < length_B; i++) {
int skip = 0;
for (j = 0; j < length_C; j++) {
if (array_B[i] == array_C[j]) {
skip=1;
break;
}
}
if(skip == 1) continue;
array_C[position++] = array_B[i];
}
the problem is with the logic inside your inner for loop. according to the problem statement if any value of array_c matches with any value of array_b you should get rid of that value otherwise add the value to array_c. so you can simply try doing the following. please make sure you understand the code. if you have any question feel free to ask.
for (i = 0; i < length_B; i++) {
bool isExistInArrayC = false;
for (j = 0; j < length_C; j++) {
if (array_B[i] == array_C[j]) {
isExistInArrayC = true;
break;
}
}
//this is the position tracker to add new value in array_C
if (isExistInArrayC == false) {
array_C[position] = array_B[i];
position++;
}
}
The suggestions will certainly work, but performance (especially with large size arrays) will be very poor. I would maintain a sorted array "C" and do a binary search into it when adding integers from array B.
You'll need a double-linked list for array C of course.
try to input 20 numbers with array and to output
the numbers in the double location only but somehow it's print
also the 0 location... please help.
#include<stdio.h>
#define n 20
int main()
{
int num[n]={0},i=0,order=1,double_locaion=0;
for(i=0;i<n;i++)
{
printf("please enter %d number\n",order);
scanf("%d",&num[i]);
order++;
}
for(i=0;i<n;i++)
{
if (i%2==0 && i!=1 && i!=0)
{
printf("%d\n",num[i]);
}
}
}
Try this, start with 2 and increase by 2 every time, the you don't have to deal with 0th element and odd element.
for (i = 2; i < n; i += 2)
{
printf("%d\n",num[i]);
}
First of all there is no way that your code is printing the 0-th location of the array. That's impossible given the condition of the if statement.
Secondly n- you don;t need to use macro expansion for that name.
/* This program takes 20 integer number from input.
* Prints the numbers entered in odd positions.(First,Third,..etc).
*/
#include<stdio.h>
#include<stdlib.h>
#define NUM 20
int main(void)
{
int numArr[NUM];
for(size_t i = 0; i < NUM; i++) {
printf("please enter %zu number\n",i+1);
if( scanf("%d",&numArr[i]) != 1){
fprintf(stderr, "%s\n","Error in input" );
exit(1);
}
}
for(size_t i = 0; i < n; i++)
{
if( i%2 == 0 )// if you want to omit the first number put the
// the condition (i%2 == 0 && i)
{
printf("%d\n",numArr[i]);
}
}
return 0;
}
What you did wrong that your code skipped 0th element?
if (i%2==0 && i!=1 && i!=0)
^^^^
i when 0 makes this condition false - and you never get to print it.
i!=1 ?
If i=1 then i%2 will be 1, so you will not even check the second conditions, the whole conditional expression will become false. So you can safely omit this logic.
Is there a better way?
Sure,
for(size_t i = 0; i < n; i += 2){
printf("%d\n",num[i]);
}
Explanation
If you consider that every time you check the modular arithmetic of 2 the elements which results to 0 remained are
0,2,4,6,8,10,...18
See the pattern? Starts with 0 and increments by 2 each time and when does it stop? Yes before reaching 20 coding it we get
for(size_t i = 0; i < n; i += 2){
/* Initialize with i=0 as first number is 0 (i=0)
* Increments by 2 (i+=2)
* Runs when less than 20 (i<n)
*/
printf("%d\n",num[i]);
}
If you want to omit the 0-th index do initialize properly
for(size_t i = 2; i < n; i += 2){
If you mean you want the numbers from array that are present at even position than you can do like this:
for (i = 2; i < n; i=i + 2) //Initialize i = 0 if 0 is consider as even
{
printf("%d\n",arr[i]);
}
I above code i is initialized to 2 and the increment in each iteration is 2 so it will access elements only at even position (2,4,6...).
I am trying to learn how to code in C, and I am trying to add unique characters to an array, from an input array, only if the character does not already exist in the unique array, in a very simple way.
I am really stumped and would appreciate some assistance how to think it through correctly.
Here's my code:
/* get each character and how many times it shows up
* to do this we need to store each unique char in a char array, and the count for each
* unique char in an int array */
char unique_chars[count];
for(int each = 0; each < count; ++each)
unique_chars[each] = '0';
/* count is the total number of chars stored in theinput array. */
int no_times = 0;
for(int each = 0; each < count; ++each)
{
if(theinput[each] != unique_chars[each])
unique_chars[each] = theinput[each];
if(theinput[each] == unique_chars[each])
continue;
for(int item = 0; item < count; ++item){
if(theinput[each] == unique_chars[item]){
++no_times;
}
}
printf("%c is in theinput array %d times.\n", theinput[each], no_times);
no_times = 0;
}
/* print all the values in the unique_chars array*/
printf("values in unique_chars are: \n");
for(int each = 0; each < count; ++each);
printf("\n");
return 0;
This is one of the many things I have tried. It returns the following:
./uniquely
exsss
The characters typed in are: exsss
Number of characters are: 6
values in unique_chars are:
e x s s s
Please how can I do this right?
You should rework the algorithm of your program as follows:
set count_unique to zero
for each index in the input
set count to zero
go through input to again using index i
if input[index] is the same as input[i]
count++
if count is 1 after the loop
unique_chars[count_unique++] = input[index]
for each index from zero to count_unique
print unique_chars[index]
However, this is the long way of doing it. The short way is to walk through the input once, increment counts, then walk through the counts, and print indexes of values of 1:
int counts[256];
for (int i = 0 ; i != count ; i++) {
counts[(unsigned)input[i]]++;
}
for (int i = 0 ; i != 256 ; i++) {
if (counts[i] == 1) {
printf("%c ", i);
}
}
printf("\n");
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