I have created a 2D array of zeros using while loops and I would like to change specific coordinates into 1s. I have tried manually typing in coordinates but for some reason it does not affect the output.
#include <stdio.h>
void print(int map[10][10]);
int main (void) {
int map[10][10] = {};
map[4][4] = 1;
print(map);
return 0;
}
void print(int map[10][10]) {
int row = 0;
while (row < 10) {
int col = 0;
while (col < 10) {
printf("0 ");
col++;
}
printf("\n");
row++;
}
}
I was intending for coordinate of the 5th column and 5th row to turn into a 1, but the array printed is still a zero. (^^this is written in c)
Thank you
You are simply printing 0 instead of printing values in the array in this line:
printf("0 ");
Change the line to print the values in the array:
printf("%d ", map[row][col]);
Related
I was trying to make a program where if I enter an integer, the program would find out the bigger number and subtract it by the smaller number. This part, I got it.
The problem is, the infinite loop part.
I tried to get type in two integers keep on printing with the while loop, and break when at least one character is typed in.
For example, if I type in 2 #, it would break.
But I couldn't find the write place to get the break; within the code and therefore whenever I enter a character it would keep on creating an infinite loop.
Is there any way to create a break in this code? I humbly ask for advice...
The following is the code which I couldn't put the break
(By the way, the reason I did the condition in while as sizeof(i)==4 || sizeof(j)==4 was to make it so it would only enter an integer, since the size of an integer is 4)
int main()
{
int i, j;
int result;
while (sizeof(i)==4 || sizeof(j)==4){
printf("type in two integers : ");
scanf("%d %d", &i, &j);
if (i < j) {
result = j - i;
}
else if (j < i){
result = i - j;
}
printf("%d\n", result);
}
return 0;
}
The bottom code is the one I tried to put break but failed (it kept creating an infinite loop)...
int main()
{
int i, j;
int result;
while (sizeof(i)==4 || sizeof(j)==4){
if (sizeof(i) == 4 || sizeof(j) == 4) {
printf("type in two integers : ");
scanf("%d %d", &i, &j);
if (i < j) {
result = j - i;
}
else if (j < i) {
result = i - j;
}
printf("%d\n", result);
}
else
break;
}
return 0;
}
and here's a code where I got rid of the sizeof and used while(1), though there wasn't much change in the fact that the break didn't work...
int main()
{
int i, j;
int result;
while (1){
printf("type in two integers : ");
scanf("%d %d", &i, &j);
if (i < j) {
result = j - i;
}
else if (j < i) {
result = i - j;
}
printf("%d\n", result);
}
return 0;
}
You can't use sizeof(i) to do run-time checks! This is a compile-time constant that, in your case (32-bit integers) will always evaluate to 4.
In order to check that two valid integers have been given, you can check the return value of the scanf function (it gives the number of fields successfully scanned):
#include <stdio.h>
int main()
{
int i, j;
int result;
while (1) {
printf("type in two integers : ");
if (scanf("%d %d", &i, &j) != 2) break; // Break here if we didn't get two integers
if (i < j) {
result = j - i;
}
else if (j < i) {
result = i - j;
}
printf("%d\n", result);
}
return 0;
}
Feel free to ask fir further clarification and/or explanation.
Drop the whole concept of endless loop with break inside if.
Make a condition for the loop based on the return value of scanf(), that is practically what it is designed for.
#include <stdio.h>
int main()
{
/* always init everything */
int i=0, j=0;
int result=0;
printf("type in two integers : ");
while (2==scanf("%d %d", &i, &j))
{
if (i < j) {
result = j - i;
}
else /* removed second if, to have a meaningful result for i==j */
{
result = i - j;
}
printf("%d\n", result);
printf("type in two integers : ");
}
return 0;
}
I'd probably actually use do {...} while (...) with a variable storing the return value of scanf()for being used in the loop condition. I'd consider it more elegant for not having to copy the print, but I kept it closer to your code structure.
More comments on your code:
as explained in comments, sizeof() works differently than you seem to think; it is static and does not change at runtime and hence cannot be used in a loop condition
with while (sizeof(i)==4 || sizeof(j)==4){if (sizeof(i) == 4 || sizeof(j) == 4){/* a */} else {/* b */}, b cannot ever be reached, because the conditions of while and if are identical
check the possible outcomes of the if conditions inside the loop, you are leaving the one with i==j undefined and return an uninitialised value
always init all variables as a habit
for a good MRE include the include lines
On your request, here is a proposal for the do-while alternative:
#include <stdio.h>
int main()
{
/* always init everything */
int i=0, j=0;
int result=0;
int iScanned=0;
do
{
printf("type in two integers : ");
iScanned=scanf("%d %d", &i, &j); /* keep the return value for loop */
if (i < j) {
result = j - i;
}
else /* removed second if, to have a meaningful result for i==j */
{
result = i - j;
}
if(2==iScanned) printf("%d\n", result); /* if to avoid awkward last output */
} while (2==iScanned);
return 0;
}
I am trying to find the closest pair of numbers entered by the user. My C code isn't working right and I can't figure out what's wrong. I think it might have something to do with storing the values but I don't know where to go from here.
#include <stdio.h>
#include <math.h>
int main()
{
int i, j,arr[50], first,second;
//loop input
for(i=0;i<50;i++) //loop 50 times
{
scanf("%d", &i); //scan
//break if i=-1
if (i==-1)
break;
//if not print
}
//2nd num - 1st num < 3rd num-1st num, closest = 1st and 2nd num
//i[0]=num1, j[0+i]=2nd num, i= 4 , 5, 7, ans=arr,
//if j[0+i]-i[0]= ans < j[0+i]-i[i]=ans
//arr[i]=8,2,17,4,25
for(i=0;i<50;i++)
{
for(j=i+1;j<50;j++)
{
if(arr[j]-arr[i]<arr[j+1]-arr[i])
{
first = arr[i];//3
second = arr[j+1];//5
}
}
}
printf("%d %d\n", first, second);
return 0;
}
Don't post it as answer, prefer editing your code instead. Anyway, the problem is here :
for (j = i + 1; j < len; j++)//j<i <-why is it wrong?
How isn't it wrong? You've initialised j with the value i+1. How's it supposed to be ever less than i? And due to that, it's picking up values from outside the array and providing you with unexpected results.
The correct form is :
for (j = 0; j < i; j++)
The problem is with this chunk of code. You're scanning in the counter variable i instead of array. And then you're manipulating stuff using array arr. Why should that work in any scenario?
for(i=0;i<50;i++) //loop 50 times
{
scanf("%d", &i); //scan
//break if i=-1
if (i==-1)
break;
//if not print
}
And i can never be -1 unless it's a miracle.
I have a program that I would like to dynamically allocate an array that gets filled by the user through the terminal argument line in Linux. After the user enters the numbers, the array of numbers should be sorted.
#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
int array[100];
int count = 0;
while(1){
printf("please enter a number: \n");
scanf("%d", &i);
if(i == 0){
for (int k = 0; k < count -1; k++) {
if(array[k] <= array[k + 1]){
int temp = array[k];
array[k] = array[k+1];
array[k+1] = temp;
}
}
for (int j = 0; j < count; ++j)
{
printf("%d ", array[j]);
}
printf("\n");
break;
} else {
array[count] = i;
count++;
}
}
}
This only sorts the array if I type the numbers in low to high, but if I enter the numbers from high to low eg. 4, 3, 2 and then 1, it prints 2, 3, 1 and then 4, instead of the 1,2,3,4 that it does if I type it that way.
I don't want to initialize the array with 100, I just can't get it to work if I don't initialize it. I want it to be increased if necessary.
Thank you :)
Errors/Deviations from the proposed program:
As mentioned, you want to use command line arguments - You need main(argc,*argv[]) instead of main().
For dynamic allocation you need malloc/calloc but instead of that you have used static array.
Your code shows you are not clear about concept of sorting, leave the program aside and use a pen and paper first to clear that.
I want to display multiplication table which will look like this:
1 2 3 4 5 6 7 8
1 1x1=1
2 1x2=2 2x2=4
3 1x3=3 2x3=6 3x3=9
4 1x4=4 2x4=8 3x4=12 4x4=16
5 1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
6 1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
7 1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
8 1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
So far I have something like this:
#include <stdio.h>
int main()
{
int n, i;
scanf("%d", &n);
int row,col;
if(n<1 || n>9)
{
printf("input error");
return 0;
}
for (row=0; row<=n;row++){
if(row==0)
{
for(i=1; i<=n; i++)
{
printf("\t%d", i);
}
}
for(col=0; col<=row;col++)
{
if(col==0 && row>0)
printf("%d\t", row);
if(row>=1 && col!=0)
printf("%dx%d=%d\t", col, row, col*row);
}
if(row!=n)
printf("\n");
}
return 0;
}
I think it displays the table properly, but the code looks sloppy and I'm sure it can be done in a much cleaner way. Any suggestions?
I'd unroll the first pass through each of the loops that displays the row & column headers:
#include <stdio.h>
int main()
{
int n, i;
scanf("%d", &n);
int row,col;
if(n<1 || n>9)
{
printf("input error");
return 0;
}
for(i=1; i<=n; i++)
{
printf("\t%d", i);
}
printf ("\n");
for (row=1; row<=n;row++){
printf("%d\t", row);
for(col=1; col<=row;col++)
{
printf("%dx%d=%d\t", col, row, col*row);
}
if (row!=n)
printf("\n");
}
return 0;
}
Most of what makes your code look sloppy is simply bad style. Here are a few tips based on what is generally considered good style and best practice:
Print a prompt whenever your program is getting input from the user
Put all variable declarations together at the top of the main function
Use parenthesis to make the order of operations clear, especially when using the && and || operators
Make error messages clear
return a negative value to indicate an error
Put a space on both sides of binary operators (i.e. "n < 1" as opposed to "n<1")
Put a space after commas when declaring multiple variables
Put a space after semi-colons in for loop conditions
The following is generally considered a good-style for loop:
for (condition) {
...
}
The following is generally considered a good-style if statement
if (condition) {
...
}
Use comments to explain your code and increase readability
Use indentation to show code grouping
Aside from all of these things, your program also does not print a newline after the very last row (row n) due to the very final if statement. This causes the user's command-line prompt to be displayed on the same line as the last row printed by your program, which is probably not desirable.
Applying all of these things to your code gives the following result:
#include <stdio.h>
int main()
{
// all variables declared together, at the top of main
int n, i;
int row, col; // space after comma
printf("Enter multiplication table size: "); // prompt
scanf("%d", &n);
// better-style if statement
if ((n < 1) || (n > 9)) { // parenthesis make the order of operations clearer
// clearer error message, with a newline at the end
printf("Error: table size must be at least 1 and not greater than 9\n");
return -1; // return a negative value to indicate an error
}
// better-style for loop
for (row = 0; row <= n; row++) { // spaces around binary operators, space after semi-colons
// better-style if, indented also
if (row == 0) {
// better-style for, indented
for (i = 1; i <= n; i++) { // spacing
printf("\t%d", i); // indented
}
}
// better-style for
for (col = 0; col <= row; col++) { // spacing, indentation
if ((col == 0) && (row>0)) // parenthesis, spacing, indentation
printf("%d\t", row); // indentation
if ((row >= 1) && (col != 0)) // parenthesis, spacing, indentation
printf("%dx%d=%d\t", col, row, col * row); // indentation, spacing
}
// surrounding if statement removed, so a newline is printed after every row, including the last one
printf("\n");
}
return 0;
}
Note that I mainly used comments to explain the changes I made to your code, whereas you would want to use them to explain the functionality.
This code has to get coordinates and write them to the coords array, and also return the number of coordinates that have been entered.
The code has to stop once the user enters 0 0 but the code should not save it.
For example if I enter 1 2 3 4 0 0 the code will set the array to (1,2) (3,4).
But in this code when I enter 0 0 it show me error, and once I enter the numbers at first the print show me just zeros.
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
++row;
}
printf("%.3lf %.3lf", coords[row][0], coords[row][1]); /* TEST */
}
return row+1;
}
The problem is that when you print coords[row][0] and coords[row][1] you are actually sending to stdout the next coordinates which are not still entered by the user. You are sending to stdout undefined values and not the values you entered. The line printf("%.3lf %.3lf", coords[row][0], coords[row][1]); should be printf("%.3lf %.3lf\n", coords[row-1][0], coords[row-1][1]); And add the next to line \n otherwise the information printed is illisible.
Try this code
#include <stdio.h>
#include <stdlib.h>
#define DIM 2
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
row++;
}
printf("%.3lf %.3lf\n", coords[row-1][0], coords[row-1][1]); /* TEST */
}
return row+1;
}
int main(void)
{
double cords[5][2];
int n = 5;
coordinatesread(cords, n);
return 0;
}
Okey, let's see. The problem in your code is that you are incrementing the value of row before printing the values in coords[row][0]=columnin
You are not going to print a line if the values are both zero, so you can move this line:
printf("%.3lf %.3lf", coords[row][0], coords[row][1]);
Right before this one:
++row;
The new code should look like this:
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
printf("%.3lf %.3lf", coords[row][0], coords[row][1]);
++row;
}
}
return row+1;
}
PD:
Notice that your code does not work fine if you want to scan N valid coordinates, because the last one will be ignored. The problem is here:
while(row!=n-1)
If you have decided to use while loop instead of for, you should iterate until row = N. Let's suppose N = 3. If you want to scan 3 valid coordinates, the loop will iterate while N != 2. This will scan only two of them (when row = 0 and row = 1). Change it to:
while(row!=n)
In addition, when you are iterating over an array (or a table in this case), using for is better than while. Both are correct, but for is more stylized. If you change it, the code look like this:
int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
for(int row = 0; i < n; i++)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
printf("%.3lf %.3lf", coords[row][0], coords[row][1]);
}
}
return row;
}