I did this code to try the basic operations on bidimensional arrays (2d arrays), but it doesn't print
on screen the letter 'A'.
Can someone help me figure this out?
Thanks
#include <stdio.h>
#define ROWS 2
#define COLS 3
int main()
{
int x;
int y;
int i;
int j;
int Field[ROWS][COLS];
printf("Enter two values: ");
scanf("%d %d", &x, &y);
Field[y][x] = 1;
for(i = ROWS - 1; i > 0; i--){
for(j = 0; j < COLS; j++){
if(Field[i][j] == 1){
printf("A");
}
}
}
return 0;
}
In the outer loop
for(i = ROWS - 1; i > 0; i--){
the range of indices is (in the descending order) [ROWS-1, 1], So the index 0 is not processed in this loop.
It is better such a loop to write the following way
for ( i = ROWS; i != 0; i-- ){
for(j = 0; j < COLS; j++){
if(Field[i-1][j] == 1){
printf("A");
}
}
}
In this case the variable i can have even an unsigned integer type as for example size_t and the code will be valid even when ROWS is equal to 0.
Otherwise the expression ROWS - 1 can yield the maximum value of the unsigned type when ROWS is equal to 0.
as mentioned i>0 should be i>=0 other wise you won't traverse the array completely.
also note that even after you you corrected that statement , it's better to check input x and y , because if they are greater or equal to ROWS and COLS , than by passing boundaries of your array here Field[y][x] = 1; your program will lead to undefined behavior.
so I suggest this
scanf("%d %d", &x, &y);
if (x < ROWS && y < COLS)
Field[y][x] = 1;
else
return 0;
//rest of your code with i>=0 in this loop for(i = ROWS - 1; i >= 0; i--)
This: for(i = ROWS - 1; i > 0; i--){ fails to traverse the necessary array location, and does not clearly convey to future maintainers of your software what exactly the intent is.
However, to do what you have described in your problem description, unless there is a compelling reason to set up a decrementing index (--), a normal incrementing (++) set of for loops is adequate and more idiomatic :)
for(i = 0; i < ROWS; i++)
{
for(j = 0; j < COLS; j++)
{
if(Field[i][j] == 1)
{
printf("A");
}
}
}
This code adds some protections to out of bounds arrays and prints 'A'. Should be a good starting point for you.
#include <stdio.h>
#define ROWS 2
#define COLS 3
int main()
{
int x,y,i,j = 0;
int Field[ROWS][COLS]; // 2 Rows 3 Column array
printf("\nEnter row value less than %i: ",ROWS);
scanf("%d", &y);
printf("\nEnter column value less than %i: ",COLS);
scanf("%d", &x);
if(x >= COLS || y>= ROWS)
{
printf("\nOut of bounds inputs!");
return 0;
}
Field[y][x] = 1;
for(i = ROWS - 1; i > 0; i--)
{
for(j = 0; j < COLS; j++)
{
if(Field[i][j] == 1)
{
printf("A");
}
}
}
return 0;
}
Related
I want to take integers like that
1 2 3
4 5 6
Than I should sum them with same line like
1+4=5
2+5=7
3+6=9
And I should print 5 7 9.
To do this I tried to take values from user in this way but only first scanf is running and the other is not.What is the reason for that and how can I fix it or is there any other useful way to do that?(How many value will user enter is unknown.)
char s1[21];
scanf("%[^\n]", s1);
char s2[21];
scanf("%[^\n]", s2);
for(int i =0; i<b1; i++)
printf("%d ",s1[i]+s2[i]);
You should read into integer arrays, not strings. scanf() will skip over the whitespace between the numbers.
int numbers1[b1], numbers2[b1];
for (int i = 0; i < b1; i++) {
scanf("%d", &numbers1[i]);
}
for (int i = 0; i < b1; i++) {
scanf("%d", &numbers2[i]);
}
for (int i = 0; i < b1; i++) {
printf("%d ", numbers1[i] + number2[i]);
}
printf("\n");
The following program doesn't work. I should debug it, but I am too lazy for that. However take a look. It might help giving you some idea.
#include <stdio.h>
#define SIZE 50
int main() {
int n[SIZE][SIZE], row, col, sum, i, j;
int numCol; // column of first row
int yeah = 1; // tells wether all the rows have the same number of columns
char c = 'c'; // to check for the newline
for(row = 0; row < SIZE; row++) {
for(col = 0; c != '\n' && col < SIZE; col++) {
if( scanf("%d%c", &n[row][col], &c) < 2 && row > 0 ) {
if( col != numCol - 1) {
yeah = 0;
}
goto outside_pls; // the only way to exit the outer loop;
}
} // end inner for
if( row == 0 ) {
numCol = col;
}
else if( col != numCol ) {
yeah = 0;
}
} // end outer for
outside_pls:
if( yeah ) {
printf("%d %d\n", row, col);
for(j = 0; j < col; j++) {
sum = 0;
for(i = 0; i < row; i++) {
sum += n[i][j];
}
printf("%d ", sum);
}
}
else {
puts("Number of columns doesn't match");
}
return 0;
}
You should take the index you are in and get all of your variables in the same index in all of your arrays.
Code should look like this
for(int i = 0; i< array1.length(); i++){
sum = array1[i]+array2[i]+.......;
}
I am writing a program which determines the intersection of 2 integer arrays (size of 10 elements). I think I got every other parts covered except for sorting out duplicates. Does anyone know a way of checking duplicates without making a function or using an external C library?
#include <stdio.h>
#define SIZE 10
int main(void){
//Initialization
int array1[SIZE];
for (int i = 0; i < SIZE; i++)
{
printf("Input integer %d of set A: ", i + 1);
scanf("%d", &array1[i]);
}
int array2[SIZE];
for (int i = 0; i < SIZE; i++)
{
printf("Input integer %d of set B: ", i + 1);
scanf("%d", &array2[i]);
}
int intersection[SIZE];
for (int i = 0; i < SIZE; i++)
{
intersection[i] = '\0';
}
//Intersection check
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if (array1[i] == array2[j])
{
intersection[i] = array1[i];
break;
}
}
}
//duplicate check
int count = SIZE;
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++)
{
if (intersection[i] == intersection[j])
{
for (int k = j; j < count; i++)
{
intersection[k] = intersection[k + 1];
}
count--;
}
}
}
//printing set
for (int i = 0; i < SIZE ; i++)
{
//printf("%d\n", intersection[i]);
if (intersection[i] != '\0')
{
printf("%d\n", intersection[i]);
}
}
return 0;
}
In the code above i was trying one method although it didn't work and instead made the program stuck after inputting all the elements. I am open to other methods as long it doesn't require an external library to run. Thanks
As i see it now , in the third loop where you checking your duplicates i thing that you have to increese k not i :
for (int k = j; j < count; k++), also you must decrise the size of j in your code under the count--;.So your code for checking duplicates seems right but , you want the intersection of this two arrays you made , so you dont have to check for duplicates because in the array intersection[SIZE] you will put only one number from the two arrays, so you will not have duplicates .You should check for duplicates if you wanted to make the union of this two arrays .I make some changings to your code acording what you want to create and this code here find the intersection from two arrays.Try this and delete the duplicate check because that makes your code to run to infinity . One last thing your intersection check must be replace whith this :
//Intersection check
int i = 0, j = 0,k=0; // k is for the intersection array !
while (i < SIZE && j < SIZE) {
if (array1[i] < array2[j])
i++;
else if (array2[j] < array1[i])
j++;
else if(array1[i]==array2[j]) // if array1[i] == array2[j]
{
intersection[k]=array2[j];
//printf("intersection[%d]=%d\n",i,intersection[i]);
intersectCount++;
k++;
i++;
j++;
}
}
printf("intersectCount=%d\n",intersectCount);
So I have been trying to solve this problem where I have to write a code that counts the number of mines that are around a certain point on a imaginary minefield. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int row;
int col;
int count;
int mineCount = 0;
int i;
int j;
// allocating memory
scanf("%d %d", &row, &col);
char **m = malloc(sizeof(char* ) * row);
for(i = 0; i < row; i ++)
{
m[i] = malloc(sizeof(char) * (col + 1)); //empty minefield
}
//planting mines
for(count = 0; count < row; count ++)
{
scanf("%s", m[count]);
}
// counting mines
for(i = 0; i < row; i ++)
{
for(j = 0; j < (col + 1); j ++)
{
if(m[i][j] != 42)
{
if(m[i-1][j] == 42)
mineCount += 1;
if(m[i+1][j] == 42)
mineCount += 1;
if(m[i][j+1] == 42)
mineCount += 1;
if(m[i][j-1] == 42)
mineCount += 1;
if(mineCount > 0)
m[i][j] = mineCount;
}
}
}
//printing out the minefield
for(i = 0; i < row; i ++)
{
for(j = 0; j < col; j ++)
printf("%c", m[i][j]);
printf("\n");
}
return 0;
}
I put '5 5' for the first input, and for the minefield, my input would be something like this:
*....
..*..
...*..
.*...
....*
at the end though, I get this 'segmentation fault (Core dumped)' error. I have been searching around for answers and found out that this happens when I try to access something that I have no access to. Any help would be appreciated. Thanks.
if(m[i-1][j] == 42)
if(m[i][j-1] == 42)
For these statements you need to have checks if i and j are not 0, otherwise you are accessing invalid memory
Third input of ...*.. // 6 char long will make
//planting mines
for(count = 0; count < row; count ++)
{
scanf("%s", m[count]);
}
to buffer overflow and write an extra . to out-of-bound memory.
Also, I don't see any free, assuming you must have implemented that.
Have a look at if(m[i+1][j]). If i=row-1 this will be equal to row. But as you only allocated row values and the addressing starts at 0 row-1 is the highest value, which you are able to address.
And also at if (m[i-1][j]) and if(m[i][j-1]) when i or j is zero respectively.
Being new to C, and this website, I'm unfamiliar with this problem I'm having. I have a 2 dimensional array with [8][8] elements. I'm trying to get the user to enter numbers into the array until finished. The program is far from finished, but I'm stuck on this problem before I can move on. Basically I use a for loop to let the user enter into each element. However, when the first row is complete, it overwrites it's last value onto the first column second row element spot. How can I prevent this from happening: Here's my code:
#include <stdio.h>
#include <string.h>
int Check_rules();
void Print_Array(int array[][8], int size)
{
int i, j;
for (i = 0; i <= size; i++)
{
printf("\n");
for (j = 0; j <= size; j++)
{
printf("%d ",array[i][j]);
}
}
printf("\n\n");
}
int main()
{
int size = 8;
int i, j;
int fullArray[size][size];
int grid1[3][3];
int grid2[3][3];
int grid3[3][3];
int grid4[3][3];
int grid5[3][3];
int grid6[3][3];
int grid7[3][3];
int grid8[3][3];
int grid9[3][3];
for (i = 0; i <= size; i++)
{
for (j = 0; j <= size; j++)
fullArray[i][j] = 0;
}
printf("Want to play a game? Enter values 1-9 starting in row 1 column 1, \nand we will work our way from there. Here's the playing board.\nIt's Sudoku, so follow the rules of the game.\n\n");
for (i = 0; i <= size; i++)
{
printf("\n");
for (j = 0; j <= size; j++)
printf("%d ",fullArray[i][j]);
}
printf("\n\n");
int tmp;
char *keeper = (" ");//space for marker
for (i = 0; i <= size; i++)
{
for (j = 0; j <= size; j++)
{
printf("Enter first value(press 0 and ENTER to skip a box, \nand -1 to cancel game): ");
scanf("%d", &tmp);
if(tmp == -1)
return 0;
fullArray[i][j] = tmp;
Print_Array(fullArray,size);
}
}
return 0;
}
If you run this you'll see my problem when you enter the last value in row 1. It overwrites the second row first column element spot?
Everywhere you have <= size, you actually want < size. This is because C uses 0-based indexes. That means if you have an array with 5 elements, the indexes are 0, 1, 2, 3, 4. In a loop like for (int i = 0; i <= 5; i++), i would get the values 0, 1, 2, 3, 4, 5. That last one is an invalid index into the array. Using i < 5 fixes the problem (ensures i stops before it reaches 5).
Fixed and cleaned up version of your code:
#include <stdio.h>
#include <string.h>
void printArray(int size, int array[][size]) {
for (int i = 0; i < size; i++) {
printf("\n");
for (int j = 0; j < size; j++) {
printf("%d ", array[i][j]);
}
}
printf("\n\n");
}
int main() {
int size = 8;
int fullArray[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
fullArray[i][j] = 0;
}
}
printf("Enter values in row 1 column 1, and we will work our way from there. Here's the playing board. \n\n");
printArray(size, fullArray);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("Enter first value (press 0 and ENTER to skip a box, or -1 to cancel game): ");
int number;
scanf("%d", &number);
if(number == -1) {
return 0;
}
fullArray[i][j] = number;
printArray(size, fullArray);
}
}
return 0;
}
EDIT
To clarify, this is fixed version of the original code in the question. The new code is a bit different, but I think the issue is the same.
I've written a little thing which asks the user for some input (rows and cols), which should then set everything in an array to a dot (".") and print it out, but this crashes my application.
void main()
{
int i,j, m, n;
printf("The number of lines (m): ");
scanf("%d", m );
printf("\nThe number of columns (n): ");
scanf("%d", n);
//create my array
char mineGrid[n][m];
//set all fields in to safe (.)
for (j = 0; j <= n; j++)
{
for (i = 0; i <= m; i++)
{
mineGrid[j][i] = ".";
}
}
//print a grid of dots
for (j = 0; j <= n; j++)
{
for (i = 0; i <= m; i++)
{
printf("%s", mineGrid[j][i]);
}
}
}
Any idea why this is crashing?
On cause of major trouble here is that you have a lot of loop that look like
for (j = 0; j <= n; j++)
/* ^ */
/* | */
/* Look! */
which will run j from 0 to n, but you have declared your array as
char mineGrid[n][m];
which means that space has been allocated for rows numbered 0 to n-1.
All you index loops are wrong in that way. The idomatic way to write those loops is
for (j = 0; j < n; ++j)
where I have fixed the range and also changed the increment from post- to pre- which is an old micro-optimization that generally does not make any difference in c these days (because compilers are smart enough to fix it), but can if you switch to c++ and use a non-trivial class in that way. So I keep it in my list of little things to "fix".
That's because you're putting a string in the array instead of char.
do it like this:
void main()
{
int i,j, m, n;
m = 5;
n = 6;
//create my array
char mineGrid[n][m];
//set all fields in to safe (.)
for (j = 0; j <= n; j++)
{
for (i = 0; i <= m; i++)
{
mineGrid[j][i] = '.';
}
}
//print a grid of dots
for (j = 0; j <= n; j++)
{
for (i = 0; i <= m; i++)
{
printf("%c", mineGrid[j][i]);
}
printf("\n");
}
}
you created n X m elements but used n+1 X m+1 elements in array. use like bellow
a
for (j = 0; j < n; j++)
{
for (i = 0; i < m; i++)
{
mineGrid[j][i] = '.';
}
}
That's because for an array of size N, the valid array indexes 0 to N-1. But you are accessing N th element which is not a valid array index and accessing it invokes undefined behavior.
for (j = 0; j <= n; j++)
{
for (i = 0; i <= m; i++) // Array out of bounds in either condition check
With that said, you have issues with your input as well.
scanf("%d", m ); // Missing & operator before m.