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;
}
Related
I'm trying to make a program that accepts the number of students enrolled to an exam, and how many points each of them got. I try to loop the inputs but it gives seemingly random numbers in output
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int studenti;
scanf("%d", &studenti);
printf("%d ", studenti);
int niza[studenti];
for (int i = 1; i <= studenti; i++){
scanf("%d", &niza[i]);
i++;
printf("%d ",niza[i]);
}
}
What am I doing wrong? Is there another way to add array elements without knowing how big the array will be beforehand because I don't know how big they are when I pass the checks on my uni website.
The primary issue is that the for loop begins with 1 and continues to i <= studenti. In C, arrays begin with index '0' and the final index in this example is studenti - 1.
Another issue is the for loop increments i and there is an i++; in the body of the loop. i is incremented twice.
Check the return from scanf. It returns the number of items successfully scanned. Here that would be 1, 0 or EOF.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int studenti = 0; // initialize
if ( 1 == scanf("%d", &studenti)) { // successful scan
printf("%d ", studenti);
int niza[studenti]; // variable length array
for (int i = 0; i < studenti; i++) { // start from index 0
if ( 1 == scanf("%d", &niza[i])) {
printf("%d ",niza[i]);
}
else { // scanf returned 0 or EOF
fprintf ( stderr, "problem scanning array element\n");
return 2;
}
}
}
else { // scanf returned 0 or EOF
fprintf ( stderr, "problem scanning\n");
return 1;
}
printf("\n");
return 0;
}
If you don't know the length, you should probably create a linked list instead of a static array, and malloc another list element for each student.
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]);
I have written a program that should be rather simple but on execution, it is not giving the wanted results. Even when debugging the program, I guess I found the error (getting stuck in the first if condition) but I'm not able to solve it (my inexperience perhaps). Anyways, this program, which should have been frugal, took 3 days whereas I expected it to take mere hours. Please help me with guiding me where I'm going wrong and how to solve it.
Here is the code
/*WAP to read pre entered no. of ints. consider only +ve and print the pythagorean triplets in them.*/
#include <stdio.h>
int main(){
int c,p,pp,count=0,a;
printf("How many entries to accept?\n");
scanf("%d",&a);
printf("Enter the nos.\n");
for (int i = 0; i < a; i++)
{
scanf("%d",&c);
if (c<0) //skip -ve nos.
{
continue;
}
if (count==0)
{
pp=c;
count++;
}
else if (count==1)
{
p=c;
count++;
}
else if ((pp*pp)+(p*p)==(c*c)) //Tracking count not necesarry after first three
{
printf("Pythagorean triplet found\n");
printf("%d %d %d",pp,p,c);
pp=p;
p=c;
}
}
return 0;
}
The main objective is to first scan a no. to signify the inputs to be read. Then scan the inputs, separated by a space or enter, in a loop which will only accept the no. of inputs stated before. It should neglect any -ve entries. It should print out the Pythagorean triplet if it encounters one, in a consecutive manner i.e. the triplet should appear one after the other & not randomly. We have to do the task without using arrays.
sample input is (you can consider any)(all given through the terminal)
(no. of entries)
6
1 -1 3 4 -4 5
(Here it will ignore -1 & -4)
expected output will be
Pythagorean triplet found
3 4 5
I am still learning so sorry for the elaborate program.
Thank you in advance.
since I cant see the input file I dont know if the values are sorted, since we need to identify which is the hypotenuse, makes it a bit more fiddly.
Also not clear what 'skip negatives' means. Does it mean
that we might see 3 -6 4 5 and say 'yes 3,4,5' is a triple
that we might see 3 -4 5 and say yes 3 4 5
or that we might see 3 -4 5 and simply ignore the whole set
I have assumed the first one
#include <stdio.h>
int main() {
printf("How many entries to accept?\n");
int a;
if (scanf("%d", &a) != 1) {
printf("bad input\n");
return (-1);
}
printf("Enter the nos.\n");
for (int i = 0; i < a; i++)
{
int sides[3] = { 0 };
int max = 0; // longest side length -> hypot
for (int j = 0; j < 3; j++)
{
int c;
if (scanf("%d", &c) != 1) {
printf("bad input\n");
return (-1);
}
if (c < 0) //skip -ve nos.
j--; // try again
else {
if (c > max) {
max = c;
}
sides[j] = c;
}
}
int hyp = max * max; // hypotenuse squared
int adjTot = 0; // adj sides squared total
for (int j = 0; j < 3; j++)
{
if (sides[j] == max)
continue;
adjTot += sides[j] * sides[j];
}
if (adjTot == hyp)
printf("%d %d %d is py\n", sides[0], sides[1], sides[2]);
else
printf("%d %d %d isnt py\n", sides[0], sides[1], sides[2]);
}
return 0;
}
Since you say you are reading from a file it just exits if there is non numeric data
My objective is to create a program that checks if a specific bit (entered by the user) is set in a hard-coded integer (in this case 159). This code compiles, however when I enter my desired integer, the console stalls for about a second and then exits the program with no error message. None of the printf() functions are executed, as nothing else is printed out on the console before it exits. I'm fairly new to C, so I need some help with this.
#include <stdio.h>
int main() {
int x = 159;
int position = 1;
scanf("%d", position);
if (position == 0) {
position = 1;
printf("if");
}
else {
for (int i = 0; i < position; i++) {
position *= 2;
}
printf("else");
}
printf("%d", position);
if ((x & position) != 0) {
printf("true");
}
else {
printf("false");
}
}
scanf function takes address of variable like this scanf("%d", &position);
not variable itself.
it will place entered value in that address so you need to add & to your scanf.
and even after that. except when your position is 0 this code will never work:
else {
for (int i = 0; i < position; i++) {
position *= 2;
}
printf("else");
}
this is an infinitive loop.It will execute until position become so large that int doesn't have enough space to store it so position become some illogical number like uninitialized variables.
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;
}