Related
Declare an array containing these number and print the evens numbers and odd numbers
Now I initialized an array that containing 11 integers.
Here is my code
#include <stdio.h>
int main(void) {
int nums[11] = {11,3,9,7,6,10,13,17,2,8,3}; // create an variables that store integers
int evens[11] = {0}; // initialized an array to store even numbers
int odds[11] = {0}; // initialized an array to store even numbers
int length = sizeof(nums) / sizeof(nums[0]); // get the length of nums
int nums_index = 0;
int evens_index = 0;
int odds_index = 0;
for (nums_index; nums_index < length;nums_index++) {
if (nums[nums_index] % 2 == 0) {
evens[evens_index] = nums[nums_index];
evens_index++;
}
else if(nums[nums_index] % 2 != 0) {
odds[odds_index] = nums[nums_index];
odds_index++;
}
printf("%d\n",evens[evens_index]);
printf("%d\n",odds[odds_index]);
}
return 0;
}
The major question is whether the output has problems when I compile my code.
The output is :0 11 0 3 0 9 0 7 6 0 10 0 0 13 0 17 2 0 8 0 0 3
Why it could happened?
Thank you all.
You need separate indexing for each array, advancing the index for evens and odds only when nums[i] value is one of the two.
Otherwise you would get sort of a copy of nums with zeroes in place of those numbers of the opposite type (odd/even).
For instance:
int j = 0;
int k = 0;
for (int i = 0; i < length; i++) {
if (nums[i] % 2 == 0) {
evens[j] = nums[i];
j++;
}
else if(nums[i] % 2 != 0) {
odds[k] = nums[i];
k++;
}
printf("%d\n",evens[i]);
printf("%d\n",odds[i]);
}
This will compose the arrays like:
11 3 9 7 13 17 3 0 0 0 0 --- for odds
6 10 2 8 0 0 0 0 0 0 0 0 --- for evens
The second problem is that you are printing inside the loop, firstly a value from evens and immediately after a value for odds.
So if you want to display them nice and separate, you can move both printf outside the first loop, then looping again on each result array for displaying it completely, before proceding to the other.
#include <stdio.h>
void PrintNumbers(int*, int);
int main(void) {
int nums[11] = {11,3,9,7,6,10,13,17,2,8,3}; // create an variables that store integers
int evens[11] = {0}; // initialized an array to store even numbers
int odds[11] = {0}; // initialized an array to store even numbers
int length = sizeof(nums) / sizeof(nums[0]); // get the length of nums
int nums_index = 0;
int evens_index = 0;
int odds_index = 0;
for (nums_index; nums_index < length; nums_index++)
{
if (nums[nums_index] % 2 == 0)
{
evens[evens_index] = nums[nums_index];
evens_index++;
}
else if(nums[nums_index] % 2 != 0)
{
odds[odds_index] = nums[nums_index];
odds_index++;
}
}
printf("Original List: ");
PrintNumbers(nums, length);
printf("Even numbers: ");
PrintNumbers(evens, length);
printf("Odd numbers: ");
PrintNumbers(odds, length);
return 0;
}
void PrintNumbers(int* numbers, int n)
{
for (int i = 0; i < n; i++)
{
printf("%d, ", numbers[i]);
}
printf("\n");
}
Output:
Original List: 11, 3, 9, 7, 6, 10, 13, 17, 2, 8, 3,
Even numbers: 6, 10, 2, 8, 0, 0, 0, 0, 0, 0, 0,
Odd numbers: 11, 3, 9, 7, 13, 17, 3, 0, 0, 0, 0,
This is the last part in a huge project. The question of my project is to code the program in C which can convert from decimal to binary. I did everything, however, I stuck with one part. After separating into two arrays - one array contains the positions of 1 and another one includes the positions of 0. For example with number 19. My arrays have:
array1 = {4,1,0} //which are pow(2,4),pow(2,1), and pow(1,0). Obviously, these numbers should be replaced with number 1.
Similarly, array2 = {3,2} // which are pow(2,3) and pow(2,2) indicate the numbers should be substituted with number 0.
My question is: Is there any way to combine and sort these two arrays into one new array. Eventually, we need to compare the value of the new array to seek for the repeated value to replace 0 and 1.
Example: lets look at number 19;
array1 = {4,1,0};
array2 = {3,2};
newarray = {4,3,2,1,0};
expectedoutput = {1 0 0 1 1};
Below is my code to convert from decimal to binary, but it does not accomplish due to the unsolved question above.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int main(){
int number,number1,y,i,total=0,z,a,ya,a1,m,n,count1=0,count2=0;
int array1[10];
int array2[10];
float x,xa;
printf("Enter the number you want to convert from decimal integer to binary: \n");
scanf(" %d",&number1);
number = number1;
x = log2f(number1);
y = floor(x);
while(y!=0){
for (m=0;m<=100;m++){
x = log2f(number1);
y = floor(x);
number1 = number1 - pow(2,y);
//array1 = (int * )malloc(y * sizeof(int));
array1[m] = y;
count1 += 1;
if (number1==0){
break;
}
}
}
x = log2f(number);
y = floor(x);
for (i=0;i<=y;i++){
z = pow(2,i);
total += z;
}
a = total - number;
a1=a;
xa = log2f(a);
ya = floor(xa);
while(ya!=0){
for (n=0;n<=100;n++){
xa = log2f(a);
ya = floor(xa);
a = a - pow(2,ya);
array2[n] = ya;
count2 += 1;
if (a==0){
ya = 0;
break;
}
}
}
Assuming both array1 and array2 are sorted in descending order, one approach to create the binary array expectedoutput is by continuously comparing the first elements of array1 and array2. Whichever is greater of the two first elements will be the value that gets sent to expectedoutput as either a 1 or a 0. The greater first element is then removed from its containing array. Here is an illustration:
/*
expectedoutput = {}
array1 = {4, 1, 0}
array2 = {3, 2}
procedure: --------------------------------------------------------------------
(any element from array1 is added to expectedoutput as 1, and from array2 as 0)
{4, 1, 0} ------- ------- {3, 2}
^ | ^
4 > 3 --> array1 = {1, 0} , expectedoutput = {1}
|
{1, 0} ------- ------- {3, 2}
^ | ^
1 < 3 --> array2 = {2}, expectedoutput = {1, 0}
|
{1, 0} ------- ------- {2}
^ | ^
1 < 2 --> array2 = {}, expectedoutput = {1, 0, 0}
|
{1, 0} ------- ------- {}
|
----------> array2 is empty, so add 1 to expectedoutput
until array1 becomes empty
Now: array1 = {}, array2 = {},
expectedoutput = {1, 0, 0, 1, 1}
*/
Since we are dealing with 1s and 0s, it would be a good idea to set empty arrays to some invalid value like -1. You can use memset at initial declaration as int array1[10]; memset(array1, -1, sizeof(array1)); so that later on array1 = {4, 1, 0, -1, -1, -1, -1, -1, -1, -1}. Similarly with any other array.
Now we can implement the above procedure by writing two functions: one that removes the first element from an array, and another that creates expectedoutput using two arrays.
To remove first element of an array:
// remove_first(arr, len) removes the first element of arr[len]
// For example: arr[5] = {3, 2, 6, -1, -1}
// remove_first(arr, 5)
// arr[5] == {2, 6, -1, -1, -1}
void remove_first(int *arr, int len) {
for (int i = 0; i < len-1; ++i) {
arr[i] = arr[i+1];
}
arr[len-1] = -1;
}
To create binary array:
// create_binary_array(arr, arr1, len1, arr2, len2) updates arr by setting
// its elements to either 1 or 0, using arr1 and arr2
// For example: arr[10] = {}, arr1[10] = {3, 1}, arr2[10] = {2}
// create_binary_array(arr, arr1, 10, arr2, 10)
// arr == {1, 0, 1}, arr1 == {}, arr2 == {}
void create_binary_array(int *arr, int *arr1, int len1, int *arr2, int len2) {
int i = 0;
while (arr1[0] != -1 || arr2[0] != -1) {
if (arr1[0] == -1) {
while (arr2[0] != -1) {
arr[i] = 0;
++i;
remove_first(arr2, len2);
}
} else if (arr2[0] == -1) {
while (arr1[0] != -1) {
arr[i] = 1;
++i;
remove_first(arr1, len1);
}
} else if (arr1[0] > arr2[0]) {
arr[i] = 1;
++i;
remove_first(arr1, len1);
} else if (arr1[0] < arr2[0]) {
arr[i] = 0;
++i;
remove_first(arr2, len2);
}
}
}
so now you can have:
int expectedoutput[10];
memset(expectedoutput, -1, sizeof(expectedoutput));
int array1[10] = {4, 1, 0, -1, -1, -1, -1, -1, -1, -1};
int array2[10] = {3, 2, -1, -1, -1, -1, -1, -1, -1, -1};
create_binary_array(expectedoutput, array1, 10, array2, 10);
// Now: expectedoutput == {1, 0, 0, 1, 1, -1, -1, -1, -1, -1}
I have an array that holds 28 ints which are all 1's and 0's. However, I need to print this information as 4 characters so how do I get each 7 bytes of data to become one bit in order to print.
Not sure this makes sense so I will illustrate what I need to:
Right now my array (in order) is this: 0101101111011101011000100010
But I need to somehow take those first 7 numbers (0101101) and print that out as Z and do that with the next 7, the next 7...
Thanks for your help!
I think this might be something along the lines you are looking for.
int to_int(int *bits) {
int power = 2;
int digit = 1;
int value = 0;
int i=0;
for(i=0; i <= 6; i++) {
if(bits[i] == 1) {
value += digit;
}
digit *= power;
}
return value;
}
int main() {
int myArray[28] = {0, 1, 0, 1, 1, 0, 1,
1, 1, 1, 0, 1, 1, 1,
0, 1, 0, 1, 1, 0, 0,
0, 1, 0, 0 ,0, 1, 0};
char theChars[5];
theChars[0] = to_char(&myArray[0]);
theChars[1] = to_char(&myArray[7]);
theChars[2] = to_char(&myArray[14]);
theChars[3] = to_char(&myArray[21]);
theChars[4] = '\0';
printf("%s\n",&theChars[0]);
}
Also, I don't think your expected output is correct.
Well, there is always the stupid way:
Cycle through each 7 blocks.
int bytes=7;
for(int i=0; i++;i<4){
double ASCII = 0;
for(int j=0; i++;j<bytes){
ASCII+=Math.pow(2, bytes-j-1)*array[i*bytes + j]
}
char c = (char) ASCII // you'll have some trouble with types here
}
Assuming your input array is called inputBits[] Try something like this:
const int input_bit_count = 28;
char output[input_bit_count / 7];
int outIdx = 0;
// step through the bit stream converting bits to 7-bit characters
for( int inIdx = 0; inIdx < input_bit_count; ){
// shift over and add the next bit to this character
output[outIdx] <<= 1;
if( inputBits[inIdx] != 0 ){
output[outIdx] |= 1;
}
inIdx++;
if( inIdx % 7 == 0)
// after each 7 bits, increment to next output character
outIdx++;
}
// done processing, now print it out
for( int chIdx = 0; chIdx < input_bit_count / 7; chIdx++ ){
printf( "%c", output[chIdx] );
}
I am trying to read a series of 8 integers from a file into an array then display those integers. I keep getting a segmentation fault the third time around, and I can't quite figure out what I am doing wrong.
struct aStruct {
int a;
int b;
...
};
typedef struct aStruct myStruct;
while(fgets(line, MAX_LENGTH, file) != NULL) {
int myArray[8] = {0};
char* val = strtok (line," ,\n\t\r");
while (val != NULL)
{
myArray[i] = atoi(val);
i++;
val = strtok (NULL, " ,\n\t\r");
}
myStruct foo;
foo.a = myArray[0];
foo.b = myArray[1];
...
}
The input file is structured like so:
0, 0, 1, 5, 0, 0, 0, 0
1, 0, 2, 5, 0, 0, 0, 0
2, 0, 3, 5, 0, 0, 0, 0
3, 0, 4, 5, 0, 0, 0, 0
4, 0, 5, 5, 0, 0, 0, 0
When tested with:
printf("myArray[0]: %d ", myArray[0]);
I get an odd output of 0 0
Where I believe it should be 0 1. Am I not initializing something correctly, or is my new syntax incorrect for the struct? I've tried a few different combinations, cant quite figure it out.
I think your problem here is in uninitialized or non reset i variable. Adding i = 0 inside your while-loop might help.
while(fgets(line, MAX_LENGTH, file) != NULL) {
i = 0; // <<< reseting array index
int myArray[8] = {0};
char* val = strtok (line," ,\n\t\r");
while (val != NULL)
{
//...
i++;
}
}
I've been thinking if there is any smarter solution if I want to check all eight neighbors of an arbitrary element in a binary number only 2D array in C
What I do is:
Psudo Code:
//return how many neighbor of an element at x,y equals 1.
int neighbor(int** array, int x, int y)
if x>WIDTH
error
if y>HIEGHT
error
if x==0
ignore west, nw, sw, and calculate the rest.....
etc..
this is pretty dull, is there any smarter solution?
I used a similar approach to get Adjacent Mines for a particular cell in the Minesweeper Game. What I did, is I used an Array like this (MAX_NUMBER_OF_CELLS = 8) :
int offset[MAX_NUMBER_OF_CELLS][2] = {
{-1, -1},
{-1, 0},
{-1, 1},
{0, -1},
{0, 1},
{1, -1},
{1, 0},
{1, 1}
};
Considering we are talking about the CELL at location 0, 0 in a matrix. We will simply add these offset values, to the CELL to check, if the adjacent CELL is a valid CELL (i.e. it falls within the matrix). If it is VALID, then we will see if it contains 1, if yes than increment sum by 1 else not.
//rest of the values represent x and y that we are calculating
(-1, -1) (-1, 0) (-1, 1)
-------------------------
(0, -1) |(0, 0(This is i and j))| (0, 1)
-------------------------
(1, -1) (1, 0) (1, 1)
sum = 0;
for (k = 0; k < MAX_NUMBER_OF_CELLS; k++)
{
indexX = i + offset[k][0];
indexY = j + offset[k][1];
if (isValidCell(indexX, indexY, model)) // Here check if new CELL is VALID
// whether indexX >= 0 && indexX < rows
// and indexY >= 0 && indexY < columns
{
flag = 1;
if (arr[indexX][indexY] == 1))
sum += 1;
}
}
EDIT 1 :
Here is one working example (C is not my language, though still tried my hands on it to give you one idea :-)) :
#include <stdio.h>
#include <stdlib.h>
int findAdjacent(int [4][4], int, int, int, int);
int main(void)
{
int arr[4][4] = {
{0, 1, 0, 0},
{1, 0, 1, 1},
{0, 1, 0, 0},
{0, 0, 0, 0}
};
int i = 2, j = 2;
int sum = findAdjacent(arr, i, j, 4, 4);
printf("Adjacent cells from (%d, %d) with value 1 : %d\n", i, j, sum);
return EXIT_SUCCESS;
}
int findAdjacent(int arr[4][4], int i, int j, int rows, int columns)
{
int sum = 0, k = 0;
int x = -1, y = -1; // Location of the new CELL, which
// we will find after adding offsets
// to the present value of i and j
int offset[8][2] = {
{-1, -1},
{-1, 0},
{-1, 1},
{0, -1},
{0, 1},
{1, -1},
{1, 0},
{1, 1}
};
for (k = 0; k < 8; k++)
{
x = i + offset[k][0];
y = j + offset[k][1];
if (isValidCell(x, y, rows, columns))
{
if (arr[x][y] == 1)
sum += 1;
}
}
return sum;
}
int isValidCell(int x, int y, int rows, int columns)
{
if ((x >= 0 && x < rows) && (y >= 0 && y < columns))
return 1;
return 0;
}
One possible optimization, if you want to know the number of neighbors of cells a lot more than you want to change the cells, is to preprocess the number of neighbors for each cell and save the results in an another array.
int** actualArray;
// fill in with 0s and 1s
int** numberOfNeighbors;
// write a function to calculate the number of neighbors for cell x,y in actualArray and
// store the result in numberOfNeighbors[x][y]
preprocess(actualArray, numberOfNeighbors); // call this whenever actualArray changes
// now you can get the number of neighbors of a cell in constant time
// from numberOfNeighbors[x][y]
Are you trying to find the current position of the element in the array? If so, you can define a macro like:
#define OFFSET(x,y) ((GridWidth*y)+x)
Or, if you're trying to find which surrounding 'boxes' could contain an element (i.e which neighbors are 'in bounds')...
for k = 0 while k < GridWidth
for m = 0 while m < GridWidth
if k < GridWidth
toRight = true
if m < GridWidth
toDown = true
if k > 1
toLeft = true
if m > 1
toUp = true
From there, combine the directions to get diagonals - if toRight && toUp, then toUpRight=true etc
EDIT - I forgot to mention, this is if the grid is stored in a 1d array. For 2d, m would be for GridHeight