Why is my nailboard experiment not working? - c

I wanted to simulate the distribution of n balls which fall on a nailboard with j rows into rows+1 cups. You see, the code is simpel. There are two inputs and an array which is called faecher which contains the cups. For every ball and row 0 or 1 is radnomly chosen. With this in mind I can calculate the cup. At the end it should vertically print as many # as there are balls in a cup. However it does not function properly. It does not matter which amount of balls I input it always prints just two #.
int main(int argc, const char *argv[])
{
int kugel = atoi(argv[1]);
int reihe = atoi(argv[2]);
int zahl;
int faecher[reihe+1];
for(int i=0;i <=reihe;i++){
faecher[i]= 0;
}
for(int j = 1;j <= kugel;j++ ){
for(int i = 0; i < reihe; i++){
zahl = rand()%2;
}
faecher[zahl]+= 1;
}
for(int j=0;j <=reihe;j++){
for(int i=1;i<=faecher[j];i++){
printf("#");
}
printf("\n");
}
return 0;
}
I was expecting an exact amount of #.

zahl = rand()%2; just sets the column the ball will fall into to 0 or 1. What you want to do is mimic the ball moving left or right at each pin. To do that, you can use zahl += rand() % 2;. However, you need to initialize zahl to 0 for each row. So remove the current int zahl; declaration and, after inside the loop on j, insert int zahl = 0;:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
int kugel = atoi(argv[1]);
int reihe = atoi(argv[2]);
// Deleted line: int zahl;
int faecher[reihe+1];
for(int i=0;i <=reihe;i++){
faecher[i]= 0;
}
for(int j = 1;j <= kugel;j++ ){
int zahl = 0; // New line.
for(int i = 0; i < reihe; i++){
zahl += rand()%2; // Changed line.
}
faecher[zahl]+= 1;
}
for(int j=0;j <=reihe;j++){
for(int i=1;i<=faecher[j];i++){
printf("#");
}
printf("\n");
}
return 0;
}
Then, for 300 balls and 10 rows, you may get an output like:
#
###########
##############################
#############################################################
####################################################################
######################################################################
########################################
###############
####

Related

Same code works in main, but not when calling from a function in C

Okay so I'm a beginner programmer so any tips on any part of the code are greatly appreciated,
but the main question is why does the code in function int longestSequence(int n,int array[n]);work when placed in main, but not when called from the function?
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int longestSequence(int n,int array[n]);
int main()
{
int n;
scanf("%d", &n);
int mat[n][n];
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
scanf("%d", &mat[i][j]);
}
}
int arraySize = n*n;
int array[arraySize];
int arrayIndex = 0;
for(int i=0; i<n; i++){
if(i%2 == 0){
for(int j = 0; j<n; j++){
array[arrayIndex++] = mat[i][j];
}
}else{
for(int j = n-1; j>=0; j--){
array[arrayIndex++] = mat[i][j];
}
}
}
/// Here's the same code that works when in main
// int numOfSequental = 0;
// int maxNumOfSequental = INT_MIN;
// for(int i = 0; i<n; i++){
// if(niz[i] == (niz[i+1]-1)){
// numOfSequental++;
// if(numOfSequental>maxNumOfSequental){
// maxNumOfSequental = numOfSequental;
// }
// continue;
// }
// numOfSequental = 0;
// }
//calling the function in printf
printf("Length of the sequence: %d", longestSequence(arraySize, array[arraySize]));
return 0;
}
int longestSequence(int n,int array[n])
{
int numOfSequental = 0;
int maxNumOfSequental = INT_MIN;
for(int i = 0; i<n; i++){
if(array[i] == (array[i+1]-1)){
numOfSequental++;
if(numOfSequental>maxNumOfSequental){
maxNumOfSequental = numOfSequental;
}
continue;
}
numOfSequental = 0;
}
return maxNumOfSequental+1;
}
"the main question is why does the code in function int longestSequence(int n,int array[n]); work when placed in main, but not
when called from the function?"
As called it should not work in either place.
printf("Length of the sequence: %d", longestSequence(arraySize, array[arraySize]));
// ^^^^^^^^^^^
return 0;
Note first that the index passed: arraySize is one beyond the legal index for array. In C, indexing is zero based, and so it goes from 0 - arraySize - 1
More importantly though the 2nd argument of longestSequence should be a pointer to the array, not an indexed element of the array.
printf("Length of the sequence: %d", longestSequence(arraySize, array));
return 0;
Also, in general, to compare subsequent numbers in an array with size n, the range of comparisons should be limited to:
a[i] == a[i+1] //for i == 0 through i == n-1
Change:
for(int i = 0; i<n; i++){
// ^^^
if(array[i] == (array[i+1]-1)){//array out of bounds when i == n
// ^^^
To
for(int i = 0; i<n-1; i++){
// ^^^^^
if(array[i] == (array[i+1]-1)){//i will never reach n
EDIT:
One last thing addresses comment about replacing calls to scanf() with using the 2nd argument of main. First to do that the code must include the prototype of main: int main(int argc, char *argv[]);. With this prototype, the program as called from the command line can now include command line arguments, eg: if running from CMD prompt in Windows:
C:\dev> myProg.exe 3 1 2 3 4 5 6 7 8 9
Inside your program then arguments of argc and argv[]` are populated as follows:
argc == 11 //total number of arguments
argv[0] == "myProg.exe" //program name is alway in argv[0]
argv[1] == "3"
argv[2] == "1"
...
argv[10] == "9"
Which should translate to creating a 3x3 array populated with the 9 subsequent values.
So the first statements in your code could now be: (in psuedo code)
int n = atoi(argv[1]);//check value of n before using
int array[n][n];
int index = 2;
for(int i = 0; i<n ; i++)
for(int j = 0; j<n ; j++)
array[i][j] = atoi(argv[index]);
index++;

How to create map with random numbers inside in c

I have task about printing board where you should input dimension and program will create a board with 2 numbers inside each cell: 1'st number is random from 1-3 and second one should be zero. I can make it only with zero but when i tried to make a random number everything went wrong way..
Maybe anyone knowns what it wrong with it?
Function calls uploading map:
int randfunc(int i, int n);
int uploadmap(int m,int n){
int a[m][n];
int i,j,k;
// time_t t;
//srand((unsigned)time(&t));
//int randnum = rand() % 3 + 1;
for(i = 0; i < m;i++){
printf("+---");
}
printf("+\n");
memset(a,0,sizeof(a));
for(i = 0;i < m;i++){
for(j = 0; j < n;j++){
printf("|%d %d",randfunc(i,n),a[i][j]);
}
printf("|\n");
for(k = 0;k < m;k++){
printf("+---");
}
printf("+\n");
}
return 0;
}
function which calls random numbers from 1 to 3:
int randfunc(int i, int n) {
time_t t;
srand((unsigned) time(&t));
for( i = 0 ; i < n ; i++ ) {
printf("%d\n", rand() % 3 + 1);
}
return 0;
}
Main function :
int main(int argc, const char * argv[]) {
int m,n;
printf("Enter dimension: \n");
scanf("%d %d",&m, &n);
printf("Map has been uploaded %d\n",uploadmap(m,n));
return 0;
}
The following simple code could work:
#include <stdio.h>
#include <stdlib.h>
void uploadmap(int m,int n) {
for (int i = 0;i < m; ++i) {
for(int j = 0; j < n; ++j)
printf("|%d 0", (rand() % 3)+1);
printf("|\n");
}
}
int main() {
int m, n;
printf("Enter dimension: \n");
scanf("%d %d",&m, &n);
uploadmap(m,n);
return 0;
}

Writing values in a 2 dimensional array in c

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.

How to print a 2d array with a function in C?

I'm trying to print a 2d array with a function, but I keep getting the error "pointer expected"
I'm trying to make a battleship-type grid. I'm fine with printing out the co-ordinate row and column, but I can't actually get the 2d array (which contains "." in every element) to print at all.
Any help would be appreciated, I'm very new to this. Thanks! :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int length;
int width;
int i;
int j;
char invisible_board;
void board_setup(int *rows, int *columns){
char *invisible_board[*rows][*columns];
char *player_board[*rows][*columns];
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
invisible_board[i][j] = "."; //Sets all elements in hidden board to water
}
}
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
player_board[i][j] = ".";
}
}
}
void display(int *rows, int *columns, char *invisible_board){
printf(" ");
for (i=1; i < *rows +1;i++){
printf("%d ",i);
}
printf("\n"); //Prints top row of co-ordinates
for (i=1; i < *columns+1;i++){
printf("%d ",i);
for (j=0;j < *columns;j++){ //Prints left column of co- ordinates and rows of game board
printf(" %c ",invisible_board[i-1][j]);
}
printf("\n");
}
}
int main(void){
printf("Please enter the amount of rows in your board\n");
scanf("%d",&length);
printf("Please enter the amount of columns in your board\n");
scanf("%d",&width);
board_setup(&length,&width);
display(&length,&width,&invisible_board);
return (0);
}
this is the simplest changes I could make to your code to get you to working code.... now.... this isn't good code yet. But gets you started.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int length;
int width;
int i;
int j;
char invisible_board[100][100]; // dynamically allocate....
char player_board[100][100]; // dynamically allocate....
void board_setup(int *rows, int *columns){
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
invisible_board[i][j] = '.'; //Sets all elements in hidden board to water
}
}
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
player_board[i][j] = '.';
}
}
}
void display(int *rows, int *columns){
printf(" ");
for (i=1; i < *rows +1;i++){
printf("%d ",i);
}
printf("\n"); //Prints top row of co-ordinates
for (i=1; i < *columns+1;i++){
printf("%d ",i);
for (j=0;j < *columns;j++){ //Prints left column of co- ordinates and rows of game board
printf(" %c ",invisible_board[i-1][j]);
}
printf("\n");
}
}
int main(void){
printf("Please enter the amount of rows in your board\n");
scanf("%d",&length);
printf("Please enter the amount of columns in your board\n");
scanf("%d",&width);
board_setup(&length,&width);
display(&length,&width);
return (0);
}

8 queens puzzle: using random numbers causes infinite loop

When executing this code, my terminal hangs most of the time, but every once in a while I get the solution I want printed out. I know this is not the best way to solve the queens puzzle, so please don't comment on that. Thank you to anyone that takes the time to help.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int check(int number, int arr[]){
int num = 0;
int i;
for(i = 0; i < 8; i++){
if(arr[i] == number)
num = 1;
}
return num;
}
int main(int argc, char * argv[]){
srand(time(NULL));
int r, r2, i, v;
char arr[8][8];
int sum[8] = {0};
int sum2[8] = {0};
int row[8];
int col[8];
int cRow[8];
int cCol[8];
int count = 0;
int sums = 0;
int sums2 = 0;
//Fill arrays and 2d array.
for(i = 0; i < 8; i++){
row[i] = 0;
col[i] = 0;
cRow[i] = 0;
cCol[i] = 0;
for(v = 0; v < 8; v++){
arr[i][v] = '_';
}
}
for(v = 0; v < 8; v++){
sum[v] = 0;
sum2[v] = 0;
printf("%d", sum[v]);
}
//Loop ends when 8 queens have been drawn
while(count < 8){
r = rand() % 8;
r2 = rand() % 8;
sums = r + r2;
sums2 = r2 - r;
/*If space on board is empty. If row and col value have not been used.
Once a value of both row and col that have not been used has been reached
by random, mark that value between 0-7 as used.*/
if((row[r] == 0) && (col[r2] == 0) && (check(sums, sum)==0)&& (check(sums2, sum2)==0)){
sum[count] = sums;
sum2[count] = sums2;
row[r] = 1;
col[r2] = 1;
/*These two are used to store coordinate values in 2 arrays to be written later.*/
cRow[count] = r;
cCol[count] = r2;
count++;
printf("\n%d\n", r);
printf("%d\n", r2);
printf("%d\n\n", sums);
for(v = 0; v < 8; v++){
//sum[v] = 0;
printf("%d", sum[v]);
}
}
}
//Print the coordinate values.
printf("\n");
for(v = 0;v<8;v++)
printf("%d ", cRow[v]);
printf("\n");
for(v = 0;v<8;v++)
printf("%d ", cCol[v]);
printf("\n");
//Write the coordinate values.
for(i = 0; i < 8; i++){
arr[cRow[i]][cCol[i]] = 'Q';
}
//Print 2d array
for(i = 0; i < 8; i++){
for(v = 0; v < 8; v++){
printf("%c ", arr[i][v]);
}
printf("\n");
}
return 0;
}
The infinite loop problem is because your program cannot "backtrack" if it ever gets to a point where it is not possible to legally place any more queens. At that point, it just loops forever futilely picking spots that won't work. Instead, to break out of this, it needs to "unplace" something it has placed already. (Thus, you will need to explicitly detect when there are no more legal spots remaining in a column, row or diagonal.)

Resources