Taking input for arrays - c

In doing a project for my computer science class, I came upon a problem with arrays. Basically, I have to take an input from the user for the number of years they want to input data for. I then have to use that input to create two arrays (one for the actual years they want the data for, and one for the data itself). I then have to print out the years and the data that the user just input.
The problem is that when I do this, the data for the years prints out fine, but the years themselves print out as random memory addresses. The other strang thing is that this only happens when I do three or more years. When I do two or less, everything else is fine. The variable for the years is an int and the variable for the data is a double.
int numberofyears;
printf("Enter the number of years you wish to take data for: " );
scanf("%d",&numberofyears); //take input for how many times arrays run
int years[numberofyears];
double dataforyear[numberofyears];
int a;
printf("Enter the years and their respective data");
for (a=0;a<numberofyears;a++){
scanf("%d %lf",&years[a],&dataforyear[a]);} //take inputs for both arrays
int b;
for (b=0;b<numberofyears;b++){
printf("%d %.2lf\n",years[b],dataforyear[b]);}
Input of:
Enter the number of of years you wish to take data for: 5
Enter the years and their respective data
1950 200.96
2000 300.55
Prints out:
1950 200.96
2000 300.55
Input of:
Enter the number of of years you wish to take data for: 5
Enter the years and their respective data
1956 325.21
1989 386.22
2003 400.00
Prints out:
0 325.21
1081671680 386.22
2003 400.00
And anything else beyond 3 years will do this. Though it seems like things beyond 5 years do not keep the last year like 3 does for whatever reason, if that helps.

How have you declared your dataforyear[] array?
If it is float dataforyear[] then change your scanf statement to
scanf("%d %f",&years[a],&dataforyear[a]);
else declare your array to double dataforyear[] if you want to keep yourscanf statement as it is.

These lines:
int years[numberofyears];
double dataforyear[numberofyears];
might be the problem. The compiler needs to know the size of your arrays at compile time. Otherwise you will have to allocate memory for your arrays. If your program isn't expected to read in a lot of data, you could always avoid allocating memory by specifying their sizes.
int years[10];
double dataforyear[10];

Related

How to create random number values in c [duplicate]

This question already has answers here:
Recommended way to initialize srand?
(15 answers)
srand() — why call it only once?
(7 answers)
Closed 2 years ago.
i am trying to create random data so i can review an algorithm in cache policy. When i use the first code with rand() i get the same numbers every time i run my code(i knew this was coming) so i tried to use srand. when i inserted it i get different numbers every time i run the code but the same 10 numbers at my loop. What am i doing wrong to create random data??? After that i will make with zip ununiformed data.
sorry my bad the loop is in main function:
for(counter=0; counter<10; counter++){
printf("Number %d is %lf\n", counter, rand_val());
}
And i am using this function to create numbers.
double rand_val(){
double rnum;
srand(time(NULL));
rnum=rand();
return(rnum);
}

Why can I assign an int to an array with not enough memory allocated? [duplicate]

This question already has answers here:
Why doesn't my program crash when I write past the end of an array?
(9 answers)
How dangerous is it to access an array out of bounds?
(12 answers)
Closed 5 years ago.
Here is my code:
#include<stdio.h>
int main()
{
int i, list[1];
list[0]=1;
list[1]=2;
list[2]=7;
list[55]=70;
i=sizeof list;
printf("%d %d %d %d %d Size of array is %d",list[0],list[1],list[2],list[3],list[55],i);
return(0);
}
It returns "1 2 7 4 70 Size of array is 4". Why can i assign, say 55 to list[55]. list[55] should not exist as I only gave the array list enough memory for 1 integer, right? In addition shouldn't this give me an error as list[3] doesn't exist? and if for some reason i am changing the size of the array why isn't the size 56? It comes out as 4.
So what is happening to give me the output i got?<--{main question}
[As i don't want to create a separate thread for a related question, why when i code int list[0]; the program crashes, if i am somehow changing the size from 1 to 4 shouldn't I be able to change the size from 0 to 4?]
Thanks for your help, I know this probably a stupid or obvious question.

how to assign spaced input numbers in array of unkown length [duplicate]

This question already has answers here:
Scan multiple integers without knowing the actual number of integers
(2 answers)
Closed 7 years ago.
Currently, I am asking user to specify number of input values being specified.
This the code for it:
#include<stdio.h>
#include<math.h>
#include<string.h>
void main()
{
int i,n;
printf("\nHow many record you will enter: ");
scanf("%d",&n);
float x[n];
printf("\n\nEnter the values of velocity (m/s):");
for(i=0; i<n; i++)
{
scanf("%f",&x[i]);
printf("\n%f",x[i]);
}
}
The code runs fine. But, I want to write code in such a way that it will calculate 'n' by scanning the input (numbers separated by space, not necessary one space between each number) without asking the user.
Can you suggest me a way for it.
PS: I am new to coding
Thanks in advance
You can have a look at fgets() and strtok(). Combining both of them , you can design as per your target. Also, you may need to know and use malloc() and free() to make use of dynamic memory allocation.
Maybe this answer can help you.

print the changed variable before the calculation is done [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
in a c program, i want the variable 'count' to be printed at the beginning of the program. But the calculation for the value of 'count' is done later. How do you accomplish this?
count = 0;
printf("the value of count is : %d", count);
count = 20;
I know in this case, the output is 0. But I need 20 to be printed.
The idea of program flow is that commands are executed in a certain order. You don't expect the waiter to bring you your meal before you have told him what you want to eat - but that seems to be what you are asking.
Of course the order of lines in a file is not necessarily the order of execution: you have have a line "at the start of the file" that is executed later: for example
#include <stdio.h>
// we define the print statement here:
void printCount(count) {
printf("the count is now %d\n", count);
}
int main(void) {
int count = 20;
printCount(count); // but we don't execute it until we get here...
return 0;
}
Now your "print" statement occurs (in the file) before you assign (calculate) count - but of course they are being executed in the correct order.
afterthought
If it's a case of printing "the number of cases is n", you could of course do
printf("the number of cases is ");
cases = 5; // whatever math is needed happens here...
printf("%d\n", cases);
and the result is
the number of cases is 5
just as you wanted... this works because there was no carriage return after printing "the number of cases is" - so the number follows when you have figured it out.
edit
Reading through the question and comments one more time I think I understand what your issue is. You have a loop that counts a number of inputs (say the number of lines in a file) and want to print both the total number of cases (not known before the loop) and something about each case (discovered during the loop) but without having to loop over all the data twice. There is a way to do this, using a print buffer. If data access is really slow and looping twice would be prohibitive, this might be an option. You would want to initialize a "sufficiently large" print buffer in memory and use snprintfto create the string you need. In reality you will "loop over" the bytes in the output string twice but there is minimal performance penalty (compared to everything else). Incomplete example:
int count=0,num, sofar=0;
char buf[2000];
// assume file is opened and handle is fp
while(true){
if (fscanf(fp, "%d", &num) <1) break;
sofar+=snprintf(buf+sofar, "%d\n", 2*num); // some "math" on number for each "case"...
count++;
}
printf("There were %d lines\n", count);
printf("Here they are multiplied by two:\n");
printf("%s\n", buf);
Obviously the above is incomplete - you need to check for errors, open/close the file, etc - I am just trying to point out the principle - this way you only loop through the data (file) once but print the count before the contents.
you can't print 20. how can you print a variable before its get initialized?

Reading, Processing & Outputting numbers from files in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Before I go on a mission to write some code, I was hoping someone could confirm the following is possible (or at least fairly simple) to do.
I am wanting to read a file containing numbers that are in 9 columns (separated by a single space) and many rows. The second column is ordered numerically, from largest to smaller. I want to discard all rows that contain below a specified number in this second column and then generate a new file and output just the top rows that conform to this rule.
Additionally, I would like to add a 10th column that is the result of a calculation between 2 other columns.
Is this done using arrays?
Many thanks in advance.
This is trivial in awk. Suppose $N is a shell variable that contains the minimum value you want from the second column, and you want to make column 10 the sum of columns 3 and 5:
awk '$2 > '$N'{ $10 = $3 + $5 }1' input-file
This outputs all of the rows. Pipe the output to head to reduce the number of lines output, or add a counter in the awk script. If you write C code to do this, you are wasting your time unless it is an exercise to help learn C.
On the other hand, it's pretty straightforward in C. For simplicity, assume you only have 2 columns:
int c[2];
do {
rc = scanf( "%d %d", c, c + 1 );
if( c[1] > N && rc == 2 )
printf( "%d %d %d", c[0], c[1], c[0] + c[1] );
} while( rc > 0 );
The most strait-forward approach is probably to convert each column within the file into an array, then manipulate it as you describe from there.
Keep in mind, the file stores characters not integers, make sure you allocate your arrays accordingly to what you desire to store.
You may also find this question discussing the conversion of characters to integers useful.

Resources