I am trying to display the elements of an array in the number of columns that the user specifies. They decide how large the array is and how many columns it will be displayed in. Right now, I am printing the elements of the array in columns but, I have extra rows and columns with numbers that are not in the array. Thus if I select array size and column number as 5 3, I would hope to see:
1 3 5
2 4
Instead, I get something like:
1 3 5
2 4 107863456
128976543 58764 896543221
5643217 90876543456 8976543
I am getting 3 columns with 4 rows. I do not know why this is happening. Here is the portion of my code that deals with creating columns, let me know if more code is needed (x is variable that holds array size, y holds number of columns):
void colDisplay(int *aPtr, int x, int y) {
int i, j;
srand(time(NULL));
for(i = 0; i < x; i++) {
aPtr[i] = rand()%5+1;
}
/*Trying to format display for number of columns used*/
printf("Unsorted columns\n");
for(i = 0; i < x; i++) {
for(j = 0; j < y; j++) {
//printf("%d = %d ", (i*y)+j, aPtr[(i*y)+j]);
printf("%d ", aPtr[(i*y)+j]);
}
printf("\n");
}
}
The inner loop is counting the columns correctly, but the outer loop is using x as a row count, instead of an item count. To fix the problem you can use a single loop that counts items, and outputs newlines at the correct times.
j = 0;
for ( i = 0; i < x; i++ )
{
printf("%d ", aPtr[i] );
j++;
if ( j == y || i == x-1 )
{
printf( "\n" );
j = 0;
}
}
I agree with the solution by #user3386109.
Also, the following change will help:
Original 'for' loop with j:
for(j = 0; j < y; j++)
Modified code:
for (j = 0; (j < y) && (i*y+j < x); j++)
Reason: index = i*y+j may exceed x if (x % y != 0) i.e. if x (array size) is not integral multiple of y (display column size).
Because of arrays index out of bound.
You should do the following:
for(i = 0; i >= 0; i++) {
boolean isContinue = true;
for(j = 0; j < y; j++) {
int index = i*y+j;
if(index==x){
isContinue = false;
break;
}
printf("%d ", aPtr[(i*y)+j]);
}
if(!isContinue){
break;
}
printf("\n");
}
Related
Looking for a bit of assistance with some assigned work. Rather than just correcting code, an explanation of what is happening if possible.
I am using a two-dimensional array to store criminal DNA profiles[10] in rows[3]. I now need to use a nested loop to check the suspects DNA profiles against the criminals DNA profiles. Here's the spec:
Change the code for matching two profiles into the code for matching the suspect
with each of the 3 criminals.
Hint: Refer to Step 3. We need to similarly use a nested loop, with the outer loop, for (int i = 0; i < sizeR; i++), for going through each of the criminals, and the inner loop, for
(int j = 0; j <sizeC; j++), for matching the corresponding chromosomes of the suspect
and each criminal.
I understand that I need to adjust:
```bool match = true;
for (int i = 0; i < size; i++)
if (suspect[i] != criminal[i])
match = false;```
I just need to know how, and perhaps an explanation of what the code is doing? Here's the full code:
#include<stdbool.h>
int main () {
int size = 10;
float suspect[size]; //declare a suspect array
//declare a criminal array for more than one criminal.
//(uses multiple rows, Row(R) Column (C))
//3 sets of 10 input values
int sizeC = 10; //values
int sizeR = 3; //sets
float criminals[sizeR][sizeC];
//read 10 input values into the suspect array from the keyboard
printf("Enter the 10 chromosomes of the suspect separated by spaces: \n");
for (int i = 0; i < size; i++)
scanf(" %f", &suspect[i]);
// read multiple profiles of 10 values into criminal array from the keyboard
for (int i = 0; i < sizeR; i++) {
printf("Enter the 10 chromosomes of the %dth criminal: \n", i+1);
// read 10 input values of a criminal into the criminals array from the keyboard
for (int j = 0; j < sizeC; j++)
scanf(" %f", &criminals[i][j])
}
//match two profiles
bool match = true;
for (int i = 0; i < size; i++)
if (suspect[i] != criminal[i])
match = false;
// display the results that match
if (match)
printf("The two profiles match! \n");
else
{
printf("The two profiles don't match! \n");
}
return 0;
}```
Thanks in advance!
This part
//match two profiles
bool match = true;
for (int i = 0; i < size; i++)
if (suspect[i] != criminal[i])
match = false;
is wrong since you wanted to compare values from a two-d array criminals with a 1-d array suspect
criminal[i] points to your ith row
I assume your size is equal to sizeR
for (int i = 0; i < sizeR; i++)
{
for (int j = 0; j < sizeC; j++)
{
if( suspect[i] == criminals[i][j])
{
match = true;
printf("suspect [%d] matches with criminals [%d][%d]\n", i, i, j);
}
}
}
I need to make a program that prints this:
.......#
......##
.....###
....####
...#####
..######
.#######
########
Basically, if the n is 8. it will print 7 dots and 1 hash***. then in the next row it will print 7 dots and 2 hashes, then 6 dots and 3 hashes until there are 0 dots and 8 hashes.
So far my code looks like this:
int main(void)
{
int G = 1;
int n = 8;
int m = 0;
int k = 0;
int Z = 1;
for (m = n; m > 0; m --)
{
for (k = n - 1; k >= Z; k --)
{
printf(".");
}
printf("\n");
Z = Z + 1;
}
for (int i = 0; i < n; i ++)
{
for (int j = 0; j < G; j++)
{
printf("#");
}
printf("\n");
G = G + 1;
}
}
But the result of this comes out as this:
.......
......
.....
....
...
..
.
#
##
###
####
#####
######
#######
########
Since this is obviously homework or some self studies, I'll write how you need to think here.
The first problem is to be able to print ONE row given total number of rows and current row.
So let's start with total number or rows. I will use more descriptive variable names, which you also should.
int total = 8;
Now we need to print one row, given the current row. Let's assume that the first row has number 1. Let's start with the dots.
for(int i=0; i<(total-row); i++)
printf(".");
Then we continue with the hashes:
for(int i=0; i<row; i++)
printf("#");
And now we just need to do this total times and add a newline after each:
for(int row=1; row<total; row++) {
for(int i=0; i<(total-row); i++)
printf(".");
for(int i=0; i<row; i++)
printf("#");
printf("\n");
}
Please note that it is very common with obo (off by one) errors when doing things like this. We could let 0 be the first row instead of one, but then we need to change a few other things. You said you wanted 1 hash and 7 dots on first line and 8 hash and 0 dots on last line, which seems a bit odd, but just change row<total to row<total+1 and you get that.
You'll rather want something that does the printing from within the same loop. Here's some pseudo code of a simple way to write this algorithm:
for(int dots=n-1; dots>DOTS_MIN; dots--)
{
for(int i=0; i < dots; i++)
print dot
for(int i=dots; i < n; i++)
print hash
printf("\n");
}
First, start from naming, it's a challenging task to find out what Z stands for.
So we have
int totalRows = 4;
int totalColumns = 8;
and we should print out totalRows of rows:
for (int row = 1; row <= totalRows; ++row) {
}
from 2nd row on we should add a new line:
for (int row = 1; row <= totalRows; ++row) {
/* Start a new line from the 2nd row on */
if (row > 1)
printf("\n");
}
Time to print dots, we have totalColumns - row of them:
for (int i = 1; i <= totalColumns - row; ++i)
printf(".");
Followed by row # symbols:
for (int i = 1; i <= row; ++i)
printf("#");
Combining these chunks all together:
int main() {
int totalRows = 4;
int totalColumns = 8;
for (int row = 1; row <= totalRows; ++row) {
/* Start a new line from the 2nd row on */
if (row > 1)
printf("\n");
/* Printing dots */
for (int i = 1; i <= totalColumns - row; ++i)
printf(".");
/* Printing # */
for (int i = 1; i <= row; ++i)
printf("#");
}
return 0;
}
I have puzzles that looks like this:
=== ====
=== ===
=== ====
left edge has length from 0 to 10 000 and right also, middle part is from 1 to 10 000.
So the question is if i can build a rectangle? like first puzzle has length of left edge equal to 0 and the last puzzle has right edge of length 0 and in the middle they fit perfectly?
I am given the number of puzzle i have and their params like this:
6
1 9 2
0 3 1
0 4 1
8 9 0
2 9 0
1 5 0
and result can be any of that:
2
0 3 1
1 5 0
or
3
0 3 1
1 9 2
2 9 0
or
2
0 4 1
1 5 0
But if there is no result i have to printf("no result")
I have to do this in C, I thought about doing some tree and searching it with BFS where vertices would have edge lengths and edge would have middle length and when reached 0 i would go all way up and collect numbers but it's hard to code. So i decided to do recursion but im also stuck:
#include<stdio.h>
int main(){
int a;
scanf("%d", &a);//here i get how many puzzles i have
int tab[a][3];//array for puzzles
int result[][3];//result array
int k = 0;//this will help me track how many puzzles has my result array
for(int i = 0; i < a; i++){//upload puzzles to array
for(int j = 0; j < 3; j++){
scanf("%d", &tab[i][j]);
}
}
findx(0, a, tab, result, k);//start of recursion, because start has to be length 0
}
int findx(int x, int a, int *tab[], int *result[], int k){//i am looking for puzzle with length x on start
for(int i = 0; i < a; i++){
if(tab[a][0] == x){//there i look for puzzles with x length at start
if(tab[a][2] == 0){//if i find such puzzle i check if this is puzzle with edge length zero at the end
for(int m = 0; m < 3; m++){//this for loop add to my result array last puzzle
result[k][m] = tab[a][m];
}
return print_result(result, k);//we will return result go to print_result function
}
else{//if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
for(int m = 0; m < 3; m++){
result[k][m] = tab[a][m];
k += 1;
}
findx(tab[a][2], a, tab, result, k);
}
}
}
printf("no result");
}
int print_result(int *result[], int k){
printf("%d", &k);//how many puzzles i have
printf("\n");
for(int i = 0; i < k; i++){//printing puzzles...
for(int j = 0; j < 3; j++){
printf("%d ", &result[i][j]);
}
printf("\n");//...in separate lines
}
}
I have an error that result array can't look like this int result[][3] because of of [] but I don't know how many puzzles I'm gonna use so?... and I have implicit declaration for both of my functions. Guys please help, I dont know much about C and its super hard to solve this problem.
I'm not sure I understand the overall logic of the problem, but you definitely are in need of some variable sized containers for result AND tab. Arrays are fixed size and must be defined at compile time. The following should at least compile without warnings:
#include<stdio.h>
#include<stdlib.h>
void print_result(int (*result)[3], int k){
printf("%d", k);//how many puzzles i have
printf("\n");
for(int i = 0; i <= k; i++){//printing puzzles...
for(int j = 0; j < 3; j++){
printf("%d ", result[i][j]);
}
printf("\n");//...in separate lines
}
}
void findx(int x, int a, int (*tab)[3], int (*result)[3], int k){//i am looking for puzzle with length x on start
for(int i = 0; i < a; i++){
if(tab[i][0] == x){//there i look for puzzles with x length at start
if(tab[i][2] == 0){//if i find such puzzle i check if this is puzzle with edge length zero at the end
for(int m = 0; m < 3; m++){//this for loop add to my result array last puzzle
result[k][m] = tab[i][m];
}
print_result(result, k);//we will return result go to print_result function
return;
}
else{//if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
for(int m = 0; m < 3; m++){
result[k][m] = tab[i][m];
k += 1;
///** Increase size of result **/
//int (*newptr)[3] = realloc(result, (k+1) * sizeof(int[3]));
//if (newptr)
// result = newptr;
}
findx(tab[i][2], a, tab, result, k);
}
}
}
printf("no result\n");
}
int main(){
int a;
scanf("%d", &a);//here i get how many puzzles i have
int (*tab)[3] = malloc(a * sizeof(int[3]));//array for puzzles
int (*result)[3] = malloc(a * sizeof(int[3]));//array for puzzles
int k = 0;//this will help me track how many puzzles has my result array
for(int i = 0; i < a; i++){//upload puzzles to array
for(int j = 0; j < 3; j++){
scanf("%d", &tab[i][j]);
}
}
findx(0, a, tab, result, k);//start of recursion, because start has to be length 0
}
Note that I changed the tab and result types to (*int)[3]. Due to order of operations, we need parentheses here. Because they are variable size, they require dynamic memory allocations. In the interest of brevity and readability, I did not check the returned values of malloc or realloc. In practice, you should be checking that the returned pointer is not NULL. Because we are using dynamic memory allocations, we should also use free if you plan on doing anything else with this program. Otherwise, it doesn't really matter because exiting the program will free the resources anyway. You actually don't want to free. because we are passing a pointer by value to findx and the realloc can change the address, it may come back with a different address. Also, take note that I needed to include <stdlib.h> for the dynamic memory allocations.
Additional Issues
Your functions print_results and findx are not declared when you call them in main. Your function either need to be above main or have "function prototypes" above main.
In the printfs you do not need the &. You do not want to send the address of the variable to printf. You want to send what will actually be printed.
Now what?
The program still does not provide you with the correct results. It simply outputs 0 as the result every time. This should at least give you a starting point. By changing this line in print_results:
for(int i = 0; i < k; i++){//printing puzzles...
to
for(int i = 0; i <= k; i++){//printing puzzles...
I was at least able to output 0 0 0. This seems more correct because if k is 0, we don't loop at all.
#include<stdio.h>
void findx(int x, int a, int tab[a][3], int result[200000][3], int puzzlesinresult) { //i am looking for puzzle with length x on start
for (int i = 0; i < a; i++) {
if (tab[i][0] == x) { //there i look for puzzles with x length at start
if (tab[i][2] == 0) { //if i find such puzzle i check if this is puzzle with edge length zero at the end
for (int m = 0; m < 3; m++) { //this for loop add to my result array last puzzle
result[puzzlesinresult][m] = tab[i][m];
}
return print_result(result, puzzlesinresult); //we will return result go to print_result function
} else { //if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
while (result[puzzlesinresult - 1][2] != tab[i][0] && puzzlesinresult > 0) {
puzzlesinresult -= 1;
}
int isusedpuzzle = 0;
for (int j = 0; j < puzzlesinresult; j++) {
if (result[j][0] == tab[i][0] && result[j][1] == tab[i][1] && result[j][2] == tab[i][2]) {
isusedpuzzle = 1;
} else {
//pass
}
}
if (isusedpuzzle == 0) {
for (int m = 0; m < 3; m++) {
result[puzzlesinresult][m] = tab[i][m];
}
puzzlesinresult += 1;
findx(tab[i][2], a, tab, result, puzzlesinresult);
}
}
}
}
}
void print_result(int result[200000][3], int puzzlesinresult) {
printf("%d\n", puzzlesinresult + 1); //how many puzzles i have
for (int i = 0; i < puzzlesinresult + 1; i++) { //printing puzzles...
for (int j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n"); //...in separate lines
}
exit(0);
}
int main() {
int a;
scanf("%d", & a); //here i get how many puzzles i have
int tab[a][3]; //array for puzzles
int result[100][3]; //result array
int puzzlesinresult = 0; //this will help me track how many puzzles has my result array
for (int i = 0; i < a; i++) { //upload puzzles to array
for (int j = 0; j < 3; j++) {
scanf("%d", & tab[i][j]);
}
}
for (int i = 0; i < a; i++) { //here i delete puzzles that doesnt contribute anything like 1 x 1,2 x 2,..
if (tab[i][0] == tab[i][2] && tab[i][0] != 0) {
for (int p = i; p < a; p++) {
for (int j = 0; j < 3; j++) {
tab[p][j] = tab[p + 1][j];
}
}
}
}
findx(0, a, tab, result, puzzlesinresult); //start of recursion, because start has to be length 0
printf("NONE");
}
This returns sometimes correct result. If you can find when this program fails I would rly appreciate sharing those cases with me :)
I am writing this code to print the following matrix in this spiral order(spiral by column).But my code is printing totally different thing.
a a+7 a+8 a+15
a+1 a+6 a+9 a+14
a+2 a+5 a+10 a+13
a+3 a+4 a+11 a+12
Here is what i did:
int main() {
int a;
int Sum = 0;
int i = 0, j = 0,n;
printf("Insert the value of n: ");
scanf("%d",&n);
printf("Insert the value of a number: ");
scanf("%d",&a);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",a);
a = a + 7;
printf("\t");
}
printf("%d",a);
a = a + 1 ;
printf("\n");
}
return 0;
}
The way I approached this is to build the matrix of values you actually want, but doing so in column order, where we can relatively easily control the logic of value progression by row. Then, with that matrix in hand, print out the values in row order, as you want the output:
int main()
{
int a = 7;
int n = 4;
int array[4][4];
for (int c=0; c < n; ++c)
{
for (int r=0; r < n; ++r)
{
// values ascending for even columns
if (c % 2 == 0)
{
array[r][c] = a + c*n + r;
}
// values descending for odd columns
else
{
array[r][c] = a + c*n + n-r-1;
}
}
}
for (int i=0; i < n; ++i)
{
for (int j=0; j < n; ++j)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
}
Output:
Demo here:
Rextester
Instead of using this complex mechanism to keep track of all elements you can just calculate the value to add at any time by simple arithmetic.
See this
int row;
int column;
printf("\n");
for (row = 0; row < n; row++) {
for (column = 0; column < n; column++) {
int base;
int flag;
if (column % 2 != 0) {
base = (column+1)/2 * 2*n - 1;
flag = -1;
}else {
base = column/2 * 2*n;
flag = 1;
}
printf( "%d ", a + base + flag * row);
}
printf("\n");
}
I hope you are able to follow this logic. If not feel free to ask.
Demo here:
Ideone
There seem to be two issues with your code as it is. As mentioned in the above comment, you are using the variable a in the loop calculation, so it is constantly being updated. This means your loop becomes invalid after a few iterations. If you define a dummy variable, this would avoid the problem. Secondly the implementation of the spiralling is close to being right, but it's not quite there.
Consider in the case n = 4. When you print along each row, the difference between a new element and the last alternates between values of (2n - 1) = 7 and 1. To take this into account, you could for example check every time you want to print whether the column index (j) is odd or even, and use this to determine which difference to add. Once you have the row machinery fixed, it shouldn't be difficult to extend it to the columns.
Simple solution using a matrix to calculate values before print them
#include <stdio.h>
int main(void)
{
int a;
int i = 0, j = 0, n;
printf("Insert the value of n: ");
scanf("%d", &n);
printf("Insert the value of a number: ");
scanf("%d", &a);
int matrix[n][n];
for (i=0; i< n*n; i++)
{
// even columns ascending
if (((i/n) % 2) == 0)
{
matrix[i%n][i/n] = a++;
}
// odd column descending
else
{
matrix[n-(i%n)-1][i/n] = a++;
}
}
for (i=0; i< n; i++)
{
for (j=0; j< n; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output
Insert the value of n: 4
Insert start value: 1
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13
I am trying to assign user input into an array; however, the program below only picks up on the first element in each line of input. The ultimate goal of this program is to find the diagonal sums of integers and return the absolute value of their difference.
Example input (note that the first number gives the number of rows and columns (square array):
Input:
3
11 2 4
4 5 6
10 8 -12
Output:
Expected = 15
Actual = 10
I realize that the issue lies in the way that the array is setup. If I print the array out I get: 111555999
Any hints/help would be very appreciated.
int main() {
int n, i, c, multi_array[200][200], sum1 = 0, sum2 = 0;
scanf("%i", &n); //N = number of rows and number of columns (square 2D array)
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d ", &multi_array[c][i]); //enter integers to store in array
}
}
for (i = 0; i != n; i++) {
sum1 += multi_array[i][i]; //add up top left to bottom right diagonal
}
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n-i]; //add up top right to bottom left diagonal
}
printf("%i", abs(sum1 - sum2)); //print absolute value of the difference between diagonals
return 0;
}
Your major problem is here, where you go out of bounds:
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n - i]; // when i is 0, th
}
When i = 0, you are accessing multi_array[0][3], which is out of bounds when N = 3.
So change it to this:
multi_array[i][n - i - 1]
You should read your array like this:
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf(" %d ", &multi_array[i][c]);
}
}
since C stored its arrays in row-major order. What you have stores the array in column-major order. It's not wrong, but it's something you do only if you really have to.
Finally, change again the input part of your code to this:
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d", &multi_array[i][c]);
}
}
so that you have to input exactly what you need to. With your initial code I have to type an extra random number when I had completed the input process.
Last but not least, I am posting the whole code, where I have wrote some extra printf()'s, which are actually for the programmer, so that he can see step-by-step if his code is acting as expected or not.
#include <stdio.h>
#include <stdlib.h> /* abs */
int main() {
int n, i, c, multi_array[200][200], sum1 = 0, sum2 = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d", &multi_array[i][c]);
}
}
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
printf("|%d|", multi_array[i][c]);
}
printf("\n");
}
for (i = 0; i != n; i++) {
sum1 += multi_array[i][i];
}
printf("sum1 is %d\n", sum1);
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n - i - 1];
}
printf("sum2 is %d\n", sum2);
printf("%i", abs(sum1 - sum2));
return 0;
}
Output:
3
11 2 4
4 5 6
10 8 -12
|11||2||4|
|4||5||6|
|10||8||-12|
sum1 is 4
sum2 is 19
15
You are clearly going out of bounds here:
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n-i]; //add up top right to bottom left diagonal
}
When i is equal to 0 the expression n-i will be equal to n, but the range of the array is from 0 to n-1. The code will read uninitialized values and cause undefined behavior.
The second array index should be 1 less.