This is my simple for loop code:
for(int i=0; i < sisi ; i++)
{
for(int j=1; j <= sisi-i; j++)
{
if(j != sisi-i)
{
printf(" ");
}
else
{
for(int b=0; b < 2i+1; b++)
{
}
}
}
printf("\n");
}
The error is caught at line 6, it says 'error expected a ";"', but i think the code is ok and no wrong grammar inside the code... But why is it occured?
In your for loop condition 2i is invalid expressión.
It should be like this:
for(int b = 0; b < (2 * i) + 1; b++)
The error is this line:
for(int b=0;b<2i+1;b++)
If you wanted 2x i then use this:
int b;
for(b = 0; b < (2*i)+1; b++)
You can't multiply by putting a number next to a variable. It has to be 2 * i. You'll want to change 2i + 1 to 2 * i + 1.
Related
What is the output of this C code?
//The output gives 5 hi's. I can't understand how it is 5. I think the output may 8 hi's. So I want an explanation for this output.
void main()
{
int i = 0, j = 0;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 4; j++)
{
if (i > 1)
break;
}
printf("Hi\n");
}
}
Actually Your Hi is working on this loop
for (i = 0; i < 5; i++)
{
printf("Hi\n");
}
Your inner loop has no effect on output because there is no output statement there
just a break statement
see
for (j = 0;j < 4; j++)
{
if (i > 1)
break;
}
that's why You have only 5 Hi on your output according to values of i
Happy Coding
for (j = 0;j < 4; j++)
{
if (i > 1)
break;
}
This for loop does nothing essentially.
The inner for loop doesn't really do anything. The only thing that really happens is it checksif (i>1) and it gets out of the inner loop.
So the execution goes back into the outer loop and "hi" is printed once for every i value
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.
I am trying to solve this Queen problem of placing 4 queen in 4x4 matrix . I know it can be solved with backtracking algorithm . However i have not studied that and i am trying to solve it with my current knowledge . So what i am trying is to generate all possible combination of Queen in 4x4 matrix and print only one which cannot cancel each other .
1) For generating all combination , i am using rand function .
However there is obviously fault in my above coding . There are some outputs with only three '1' instead of four '1' . I am not able to eliminate this problem .
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
srand(time(NULL));
int ar[30][30], i , j , a , b , c = -1, d = -1, k = 0;
while (1)
{
for (i = 0 ; i < 4 ; i++)
{
for (j = 0 ; j < 4 ; j++)
{
ar[i][j] = 0;
}
}
for (i = 0 ; i < 2 ; i++)
{
for (j = 0 ; j < 2 ; j++)
{
a = rand() % 3 ;
b = rand() % 3 ;
if (a != c || b != d)
{
ar[a][b] = 1 ; // here 1 = Queen
c = a ;
d = b;
}
}
}
}
}
2) Also is there any way i can reduce the time complexity using only these method ?
Instead of using temporary variables to check whether the array is filled, use the array itself!
for (i = 0 ; i < 2 ; i++)
{
for (j = 0 ; j < 2 ; j++)
{
a = rand() % 3 ;
b = rand() % 3 ;
if (ar[a][b] == 0)
{
ar[a][b] = 1 ; // here 1 = Queen
}
}
}
Your problem is that the inner loop will execute 4 times and you can only control 1 repeat with variables c and d.
Let's say a is 1 and b is 1: you make c = 1 and d = 1.
then a is 2 and b is 1 ... making c = 2 and d = 1.
then if a is 1 and b is 1 again, you cannot check for duplicate.
(1) You check only that a queen isn't placed on the same square as the last queen you placed. Remove the variables c and d and check whether ar[a][b] is still zero.
(2) Your scatter approach will produce many set-ups that are misses. Especially, because you don't enforce that ther cannot be any queens on the same rank and file. (In addition, rand() % 3 produces random values from 0 to 2, inclusively. You will never get a non-threatening configuration that way.)
If you want to use your random (bogosort) approach, you could use a one-dimensional array where the index is the rank and the number is the file where a queen is. Then you start with:
int queen[4] = {0, 1, 2, 3};
and shuffle the array. For 4 queens, that will yield 4! = 24 possibile configurations. You could try to iterate through them systematically.
The following is the brute force, backtracking code for the 8 queens problem, asked some time ago. Just change 8 to 4:
int checkBoard(int board[8][8]);
int putQueens(int board[8][8], int nQueens);
void printBoard(int board[8][8]);
int eightQueens(void)
{
int board[8][8];
memset(board, 0, sizeof(int)*64);
if (putQueens(board, 0)) {
printBoard(board);
return (1);
}
return(0);
}
int putQueens(int board[8][8], int nQueens)
{
int i, j;
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
if (board[i][j]==0) {
board[i][j]= 1;
if (checkBoard(board)) {
if (nQueens==7) return(1);
if (putQueens(board, nQueens+1)) return(1);
}
board[i][j]= 0;
}
}
}
return(0);
}
int checkBoard(int board[8][8])
{
int i, j;
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
if (board[i][j]) {
int ii, jj;
for (ii=i+1; ii<8; ii++) {
if (board[ii][j]) return(0);
}
for (jj=j+1; jj<8; jj++) {
if (board[i][jj]) return(0);
}
for (ii=i+1, jj=j+1; ii<8 && jj<8; ii++, jj++) {
if (board[ii][jj]) return(0);
}
for (ii=i-1, jj=j-1; ii>0 && jj>0; ii--, jj--) {
if (board[ii][jj]) return(0);
}
for (ii=i-1, jj=j+1; ii>0 && jj<8; ii--, jj++) {
if (board[ii][jj]) return(0);
}
for (ii=i+1, jj=j-1; ii<8 && jj>0; ii++, jj--) {
if (board[ii][jj]) return(0);
}
}
}
}
return (1);
}
void printBoard(int board[8][8])
{
int i,j;
printf(" ");
for (j=0; j<8; j++) printf(" %1d",j+1); printf("\n");
for (i=0; i<8; i++) {
printf("%1d ",i+1);
for (j=0; j<8; j++)
printf(" %1c", board[i][j]==0? '-':'*');
printf("\n");
}
}
Ok, so I'm writing a program to make a 10 x 10 array filled with random numbers between 0 & 9, and (with each step organized into a function):
(a) sum the first row and print it out
(b)print out average of main diagonal (top to bottom, left to right)
(c)print out how many 0's are in the first column
(d)make more 10 x 10 arrays with random numbers between 0 & 9 and if all the values in the main
diagonal (top to bottom, left to right) are 7 or greater, print out the array, and the
amount of tries it took. If it can't do it in 1,000,000 attempts, print that it could not
be done.
(e)make a 1D dynamically allocated array containing 10 numbers between -10 & +10, multiply by
the first array made and display the resulting vector
Can't figure out what's not making it work, getting the wrong values for all the steps when they're printed out :'( and some errors
void simple_array(int ten_by_ten[10][10])
{
int i, j;
printf("\n");
for (i=0; i<10; ++i)
{
for (j=0; j<10; ++j)
{
ten_by_ten[i][j] = rand() % 10;
printf("%d ", ten_by_ten[i][j]);
}
printf("\n");
}
}
void sum_first_row(int y[10][10])
{
int i = 0, j, sum_row = 0;
for (j=0; j<10; ++j)
{
sum_row += y[i][j];
}
printf("\nThe sum of the first row is: %d\n", sum_row);
}
void average_main_diagonal(int z[10][10])
{
int i, j = 0, average_diagonal = 0;
for (i=0; i<10; ++i)
{
++j;
average_diagonal += z[i][j];
}
printf("\nThe average of the diagonal is: %lf\n", (average_diagonal / 10.0));
}
void zeros(int a[10][10])
{
int i, j = 0, zeroz = 0;
for (i=0; i<10; ++i)
{
if (a[i][j] == 0)
++zeroz;
}
printf("\nThere are %d zero's in the first column\n", zeroz);
}
void multiple_arrays()
{
int sum_diagonal = 0,array[10][10], i, j, k, l, c;
while ((sum_diagonal < 70) && (c <= 1000000))
{
j = 0;
k = 0;
l = 0;
i = 0;
for (i=0; i<10; ++i)
{
for (j=0; j<10; ++j)
{
array[i][j] = rand() % 10;
}
}
for (k=0; k<10; ++k)
{
++l;
sum_diagonal += array[k][l];
}
++c;
}
if (c = 1000000)
printf("\nCould not get a diagonal with numbers >= 7\n");
else
{
j = 0;
i = 0;
for (i=0; i<10; ++i);
{
printf("\n");
for (j=0; j<10; ++j)
printf("%d ", array[i][j]);
}
printf("It took %d many tries to get a diagonal with all numbers >= 7", c);
}
}
void array_multiplication(int b)
{
int **arrays, i, j, k, l, m, prod[10];
arrays = (int **) calloc (10, sizeof(int *));
for (i=0; i<10; ++i)
arrays[i] = (int *) calloc (1, sizeof(int));
for (i=0; i<10; i=i+1)
{
arrays[i] = (rand() % 21) -10;
}
for (k=0; k<10; ++k)
{
prod[k] = 0;
for (l=0; l<10; ++l)
prod[k] = prod[k] + b[k][l] * arrays[l];
}
printf ("The product is: <");
for (m=0; m<10; ++m)
printf ("%d, ", prod[m]);
printf (">\n");
}
int main()
{
int x[10][10];
simple_array(x);
sum_first_row(x)
average_main_diagonal(x);
zeros(x);
multiple_arrays();
array_multiplication(x);
return (0);
}
Getting the following errors:
When I comment out the "array multiplication" function (because it's getting the following errors: (a) assignment makes pointer from integer without cast "arrays[i] = (rand() % 21) -10;" (b) value is neither array nor pointer "prod[k] = prod[k] + b[k][l] * arrays[l];" (c) passing arg1 of "array_multiplication" makes integer from pointer without cast "array_multiplication(x);"
and it prints out an incorrect average of the diagonal
Help is Extremely appreciated!!!
Thanks,
--Rob
arrays[i] = (rand() % 21) -10; : arrays[i] is a pointer. You can't assign an integer to a pointer. Actually you just assigned some allocated memory to arrays[i] on the previous line, so even if this worked you would leak that memory.
Maybe you meant to have two nested loops, if you want to put a value in every row and every column?
Also you never free the memory you calloc'd. And don't cast the value returned by calloc either.
The other errors, you meant to declare your function as
void array_multiplication(int b[10][10])
instead of (int b). It is complaining that you are doing array operations on an int.
Your code that looks at the diagonals is incorrect (which you knew). You are incrementing "j" before using it...and so "i" is 0 and "j" is 1...which is not the diagonal. You either need to do your "++j" AFTER using it to look up the value....but would be better suited to just use z[i][i] (use "i" for BOTH indices).
This problem happens in both average_main_diagonal and multiple_arrays.
I have been trying out some basic exercises involving loops.
Can someone tell me why the following snippets have different outputs?
While Loop
while (i<3)
{
while(j<3)
{
printf("(%d %d) ",i,j);
j++;
}
i++;
}
Output
(0 0) (0 1) (0 2)
For Loop
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("(%d %d) ",i,j);
}
Output
(0 0) (0 1) (0 2) (1 0) (1 1) (1 2) (2 0) (2 1) (2 2)
Aren't they supposed to have the same output?
Try:
while (i<3)
{
j = 0;
while(j<3)
{
printf("(%d %d) ",i,j);
j++;
}
i++;
}
In your code, what is happening is simple - for the first loop i = 0, j = 0, 1, 2, 3 for the second i = 1, j = 3...
You aren't reinitializing the variable before the while loop starts, like in the for loop. Try this:
i = 0;
while (i<3)
{
j = 0;
while(j<3)
{
printf("(%d %d) ",i,j);
j++;
}
i++;
}
You never reinit the vars in the while loop.
Can someone tell me why the following snippets have different outputs?
Yes, they are not equivalent. To make the two snippets of code equivalent, you need to initialize i = 0 and especially j = 0 inside the while loop like so:
i = 0;
while (i < 3) {
j = 0;
while(j < 3) {
printf("(%d %d)", i, j);
j++;
}
i++;
}
Remember that
for(init-statement condition; expression) {
statement
}
is translated to
init-statement
while(condition) {
statement
expression
}
In particular,
for(j = 0; j < 3; j++)
printf("(%d %d)", i, j);
is translated to
j = 0;
while(j < 3) {
printf("(%d %d)", i, j);
j++;
}
As such, you are missing the very key j = 0 initialization before entering the inner while loop as well as the i = 0 initialization before entering the outer while loop.
So to wrap it all up, the translation of
for(i = 0; i < 3; i++) {
for(j = 0; j < 3 ; j++)
printf("(%d %d)", i, j);
}
is (first pass)
i = 0;
while(i < 3) {
for(j = 0; j < 3; j++)
printf("(%d %d)", i, j);
i++;
}
and finally
i = 0;
while(i < 3) {
j = 0;
while(j < 3) {
printf("(%d %d)", i, j);
j++;
}
i++;
}
Inner while loop executes only once, because your j variable equals 3 and is never reseted.
Short and sweet, you didn't reset the variable "j" once it hits 3 after the first iteration of "i".
Always initialize your while variable before you use them.
in the while statement your value for j remains at 3 and no longer executes. it is reset in the for loop.
As others said, you haven't reset the your j variable. In general I can say
s1;
while(condition){
s0;
s2;
}
... is not equal to ...
for(s1;condition;s2){
s0;
}
... because if s0 contains a continue then s2 is not executed in the first case and executed in the second.
Secondly the variable declarations in s1 will be limited to the loop in the second case. This is used to be desired, but sometimes not. In that case you can do the declaration before the loop.
This is why you declare your variables in the scope they should exist in. For example, this should return the same values as you'd get from the for.
while (i<3)
{
int j;
while(j<3)
{
printf("(%d %d) ",i,j);
j++;
}
i++;
}
Why? Because j is recreated for each loop of the outer while.