I am trying to print all inputted number by the user using the code below but instead of printing all inputted numbers it only print the last number I inputted.
#include<stdio.h>
int display(int n, int a, int b)
{
printf("\n\nOrdered pairs are: ");
for(int j=0;j<n;j++)
{
printf("(%d,%d) ",a,b);
}
return 0;
}
int main()
{
int num,i,j,x,y;
printf("Total number of points: ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
printf("\n\nPoint #%d: \n",i+1);
printf("x=");
scanf("%d",&x);
printf("y=");
scanf("%d",&y);
printf("Point #%d: (%d,%d)",i+1,x,y);
}
display(i,x,y);
return 0;
}
You don't have memory for storing more than 2 numbers (x and y) which are over-written during each iteration of the loop.
Perhaps you meant to use arrays, or dynamically allocated memory. This:
int x[100], y[100];
is one way, then you can store up to 100 numbers in each of the two arrays. Use array indexing when accessing.
Actually you are changing the value stored in x and y again and again and so, the previous values get destroyed and only the last value is stored. So you can you arrays (which are more easier to use) or you can even use structure (I would prefer to use arrays).
Related
How do i assign a value to a different variable every time the loop activates? I want to change the variable inside a scanf() so that when a new number is assigned to a different variable. Like in:
int a,b,c,i;
for(int i=1;i<=3;i++)
{
printf("enter a number:");
scanf("%d",&a);
}
The loop asks for numbers 3 times, and i want to enter 1,2, and 3. How can i assign them in a different variable each? Like 1 is assigned to a, b=2, and c=3?
You cannot change variable names at run-time, because simply they don't exist at runtime. If the type of inputs are of the same type, say, integer, you can use an array of integers to store multiple inputs.
Sample:
int array[3] = {0};
//input
for(int i=0;i<3;i++)
{
printf("enter a number:");
scanf("%d",&(array[i]));
}
//output
for(int i=0;i<3;i++)
{
printf("Number %d is %d", i+1, array[i]);
}
Thats what arrays were made for!
int numbers[3];
for(int i=0;i<3;i++)
{
printf("enter a number:");
scanf("%d",&numbers[i]);
}
Then your three numbers are available via:
numbers[0], numbers[1], numbers[2]
I need help with this problem that I was given at my school. The problem is writen in Serbian, I'll try my best to translate it.
Write a program that enters n elements of a one-dimensional array and then displays their ordinal number, index and value (see test example)
The test example is in Serbian as well, but I think you can guess what do you need to do. Here is what I tried to do:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,clan,broj=0,b,a;
a=1;
printf("Unesi broj elementa niza:\n");
scanf("%d", &n);
for (i=1;i<=n;i++)
{
printf("Unesi %d clan niza:\n", i);
printf("a[%d]=", broj);
broj++;
scanf("%d", &clan);
}
for (b=1;b<=n;b++)
{
printf("%d. clan niza je a[%d]=%d\n", a, b, clan);
a++;
}
return 0;
}
Everything works fine except that "clan" will only show as the latest entered number.
"...only the last entered number will be printed back at me, and I can't find a solution..."
Use an array.
The variable clan is not able to contain more than one int value at a time, however, the array variable int clan[n]; can hold up to n int values. Below is your code modified to accommodate n elements of a clan array using a VLA:
int main(void)
{
int n,i,broj=0,b,a;//remove clan
a=1;
printf("Unesi broj elementa niza:\n");
if(scanf("%d", &n) == 1)//test for success here, exit if fail
{
int clan[n];//use user input value to help create array of clan
for (i=0;i<n;i++)//array index is from 0 to n-1
{
printf("Unesi %d clan niza:\n", i);
printf("a[%d]=", broj);
broj++;
scanf("%d", &clan[i]);//modify to populate 1 element of clan array
}
for (b=0;b<n;b++)
{
printf("%d. clan niza je a[%d]=%d\n", a, b, clan[i]);//modify to oupput 1 element of clan array
a++;
}
}
else
{
printf("scanf() call failed. Exiting.");
}
return 0;
}
You are storing all your values into the same variable, clan. Of course, each assignment overwrites the previous value - it is one variable, not a stack.
Reading it five times in a loop gives each time that last value.
Can anyone help me fix my C code?
I have already made the formula for Linear Least-Squares Fit to fit data entered by the User.
Where I am having issues with having my program read in a series of x values (where number is known advance, but no more than 100 values) until the user enters the sentinel value -100000. Then prints out a table of values for the least-fit line y=mx+b in two tab-separated. I have not learned to use the getch() function yet so I Cannot use the header to perform this.
This is what I have come up with so far (I am adding the entire code):
#include<stdio.h>
#include<math.h>
int main()
{
int x[30],X=0,xx=0,xy=0,y[30],Y=0,n,
bnum,bden,mnum,mden,a[30],N,Yn;
float b=0.0,m=0.0;
int i=0,sent=0;
printf("Enter the number of ordered pairs\n");
scanf("%d",&n);
printf("Enter the ordered pairs\n");
for(i=0;i<n;i++)
{
scanf("%d%d",&x[i],&y[i]);
printf("\n");
}
printf("The ordered pairs are \n");
for(i=0;i<n;i++)
{
printf("%2d%2d",x[i],y[i]);
printf("\n");
}
for(i=0;i<n;i++)
{
X=X+x[i]; //Sum of values in x array
xx=xx+x[i]*x[i]; //Sum of square of values in x array
xy=xy+x[i]*y[i]; //Sum of product of values of x and y array
Y=Y+y[i]; //Sum of values in y array
}
bnum=(xx*Y)-(X*xy);
bden=(n*xx)-(X*X);
// y intercept
b=bnum/bden;
printf("The Y intercept b = %.2f \n",b);
mnum=(n*xy)-(X*Y);
mden=bden;
//slope
m=mnum/mden;
printf("The slope m = %.2f \n",m);
i=0;
// reading set of x values
while(sent!=-100000)
{
printf("Enter the x values\n");
scanf("%d",&a[i]);
i=i++;
printf("If done enter -100000 or enter another number to continue\n");
scanf("%d",&sent);
}
N=i;
printf("x y\n");
for(i=0;i<N;i++)
{
Yn=(m*a[i])+b;
printf("%3d%3d\n",a[i],Yn);
}
return 0;
}
I'm writing a program that requires me to do a union of two arrays. Here is my code so far.
I get Segmentation fault as an error after I enter set A.
#include <stdio.h>
void Union(int a[], int b[], int set1, int set2)
{
int u[20], i, j, unionIndex=0,trigger;
for(i=0; i<set1; i++)
{
u[unionIndex] = a[i];
unionIndex++;
}
for(i=0; i<set2; i++)
{
trigger=0;
for(j =0; j<set1; j++)
{
if(b[i] == u[j])
{
trigger =1;
break;
}
}
if(trigger =0)
{
u[unionIndex]=b[i];
unionIndex++;
}
}
for(i=0;i<unionIndex;unionIndex++)
{
printf(" %d",u[i]);
}
}
int main(void) {
int N=0;
int M=0;
int i;
int j;
printf("Please enter the number of elements in set A: ");
scanf("%d",N );
int a[N];
printf("Enter the numbers in set: ");
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
printf("Please enter the number of elements in set B: ");
scanf("%d",M );
int b[M];
printf("Enter the numbers in set: ");
for(j=0;i<M;i++)
{
scanf("%d",&b[i]);
}
Union(a,b,N,M);
return 0;
}
I'm pretty sure the issue has something to do with arrays because the program will compile but i get the error right after the user enters set A. I'm a beginner at C but I know a lot more about Java, so I'm thinking this has something to do with memory allocation. I'm not really sure how to solve the issue, so if you could point me in the right direction that would be helpful.
You need to pass the address of the variable to scanf()
Change
printf("Please enter the number of elements in set A: ");
scanf("%d",N );
to
printf("Please enter the number of elements in set A: ");
scanf("%d", &N);
Same goes for other place
printf("Please enter the number of elements in set B: ");
scanf("%d", &M);
There is another possible mistake
Its here
for(j =0; j<set1; j++)
{
if(b[i] == u[j])
In this set1 is equal to N, so j will go from 0 to N-1. And array u[] has only 20 elements. There is a possibility of array access out of bound if some user enter value more then 20 for N.
The problem, as I see it is in
scanf("%d",N );
and
scanf("%d",M );
It invokes undefined behavior as scanf() needs the argument to a format specifier to be a pointer to the type.
Just to clarify, you're essentially passing the address as 0 (value of the variable), which is not a valid addres, anyway.
You need to pass the address there, like
scanf("%d", &N );
and
scanf("%d", &M );
That said, in your Union() function, you're using a user-defined value to limit the for loop, against a constant value 20. In case the user input is more than 20, you'll be overrunning the memory which invokes undefined behavior.
The reason you're getting the segmentation fault is because of how you're calling scanf when reading in N and M. The %d format specifier for scanf expects an int *, i.e. the address of an int, but you're passing in an int. This is undefined behavior.
So you can fix them like this:
scanf("%d",&N );
....
scanf("%d",&M );
Some addtional bugs:
When looping to read in the values for b:
for(j=0;i<M;i++)
{
scanf("%d",&b[i]);
}
You have the wrong loop indexes:
for(j=0;j<M;j++)
{
scanf("%d",&b[j]);
}
When checking trigger:
if(trigger =0)
This is an assignment, not a comparison:
if(trigger == 0)
When looping to print out u:
for(i=0;i<unionIndex;unionIndex++)
You're incrementing the wrong variable:
for(i=0;i<unionIndex;i++)
Finally, u need to have a length of at least set1 + set2, otherwise you risk writing off the end of the array:
int u[set1+set2];
Fix those and you should get the desired results.
Note: This is a homework question.
Use FOR construction to fill 2D board with values that were given by
user. The program asks for board size n, m and then it asks for each
board value.
My try
#include <stdio.h>
int main(){
printf("Enter the number of columns");
int i = scanf("%d",&i);
printf("Enter the number of rows");
int y = scanf("%d",&y);
int r[i][y];
int a;
int b;
for (a=0; a<i; a++){
for(b=0; b<y; b++){
int r[a][b] = scanf("%d",&a,&b); //bug
}
}
}
Bug: c:13 variable-sized object may not be initialized
EDIT:
#include <stdio.h>
int main(){
printf("Enter the number of columns");
int i;
scanf("%d", &i);
printf("Enter the number of rows");
int y;
scanf("%d", &y);
int r[i][y];
int a;
int b;
for (a=0; a<i; a++){
for (b=0; b<y; b++){
scanf("%d",&r[a][b]);
}
}
}
scanf takes the address of the variable that is being read and returns the number of items read. It does not return the value read.
Replace
int i = scanf("%d",&i);
int y = scanf("%d",&y);
by
scanf("%d",&i);
scanf("%d",&y);
and
int r[a][b] = scanf("%d",&a,&b);
by
scanf("%d",&r[a][b]);
EDIT:
You are using variable length array (VLA) in your program:
int r[i][y];
as i and y are not constants and are variables. VLA are a C99 standard feature.
you have to allocate the 2D array dynamically cause you don't know it size in compilation.
replace
int r[i][y];
with
int *r = malloc(i*y*sizeof(int));
and when finish, add:
free(r);
*and also the SCANF errors, people already answered here.
First the return value of scanf isn't the value that was read from stdin, instead it is the number of input values scanf read.
Secondly, C does not allow creation of arrays by using variables. You have to first create one array by dynamically allocating it. And for each entry in the first array you have to create yet another array.
Don't forget to free the memory you allocate!
The use of scanf(%d, &var) is incorrect.
scanf reads from console an integer (this type is specified by its first paramenter %d) and stores it in the second parameter.
This second parameter must be a pointer, so an & is needed when your variable is not a pointer yet.
Therefore you should correct your code in this way:
int i;
scanf("%d",&i);
int y;
scanf("%d", &y);
And in your for loop
scanf("%d", &r[a][b]);
It doesn't print the message because of line buffering.
If you add \n to your strings (to start a new line), it might do what you expect:
printf("Enter the number of columns\n");
Alternatively, if you really want the user to type on the same line, you need to flush the buffer manually:
printf("Enter the number of columns");
fflush (stdout);