I have written a program that when executed, prompts the user to enter an integer for five times. It returns two arrays,one containing the odd numbers and the other one, the odd ones.
This is my code:
#include <stdio.h>
#define SIZE 5
int array[SIZE];
int odd[SIZE];
int even[SIZE];
int index_odd=0;
int index_even=0;
int main()
{
for(int i=0; i < SIZE; i++)
{
scanf("%d", &array[i]);
if(array[i]%2==0)
{
odd[index_odd]=array[i];
index_odd++;
}
else
{
even[index_even]=array[i];
index_even++;
}
}
printf("\nOdd numbers: \n");
for(int i=0; i < SIZE; i++)
printf("%d ", odd[i]);
printf("\nEven numbers: \n");
for(int i=0; i < SIZE; i++)
printf("%d ", even[i]);
printf("\n");
return 0;
}
Is it possible for the program to, instead of reading from a terminal, to read from a text file, as in a turn-by-turn based game:
read a line as input
assign input(value) to the right array
read the next line
assign input(value) to the right array
and so on until EOF.
The actual thing I am trying to build is a CARDIAC COMPUTER simulator, and the way it works is, it takes a series of numbers, assigns them to the right indexes of an array and then depending on what values they hold, performs operations within that array and outputs the result.
What do I need to implement in my code in order to:
read line from a text file
save it to the assigned index/array
read next line
save it to the assigned index/array
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
My code:
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
printf("%d", menu[i]);
}
I'm trying to ask the user for input and add it to the array and then at the end to output the whole array e.g 1,2,3,4....16, however as of now it always returns the value 16 no matter what the user input.
You need to run loop twice. Once for taking inputs and then for displaying all numbers.
#include <stdio.h>
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
{
printf("%d\n", menu[i]);
}
}
Your code has an array index bound check failure.
printf("%d", menu[i]);
The value of i here is going to be 16 because you are using it after the loop. The loop terminal condition is i == 16. The menu array is only defined for index values of [0..15]. The value you see in the output is entirely random depending on the state of the execution stack. You could test this by printing instead menu[65] and see random data or maybe a segmentation fault.
Printing out the array to the console is the same loop as your input, but with the printf embedded in it instead. So your code should have 2 loops in it. One loop to gather input, and the other loop to output the input.
The answer is in the comments.
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
printf("%d ", menu[i]);
you can add a loop at the end of your code like this
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for (i = 0;i<16;i++)
{
printf("%d ",menu[i]);
}
}
"I'm trying to ask the user for input and add it to the array and then at the end to output the whole array"
Just because it has not been suggested yet...
This can be done using a single loop, or with no loops at all.
(The looping option below is an adaptation of your code with comments describing differences.)
//The following items, are optionally
//defined here instead of in-line with code.
//they are used to clean up the scanf() and sprintf() calls below
#define data menu[0],menu[1],menu[2],menu[3],menu[4],menu[5],menu[6],menu[7],menu[8],menu[9],menu[10],menu[11],menu[12],menu[13],menu[14],menu[15]
#define input_data &menu[0],&menu[1],&menu[2],&menu[3],&menu[4],&menu[5],&menu[6],&menu[7],&menu[8],&menu[9],&menu[10],&menu[11],&menu[12],&menu[13],&menu[14],&menu[15]
const char input_format[] = {"%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d"};
const char format[] = {"%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n"};
//it also preferred to avoid magic numbers when possible
#define ELEMENTS 16
#define MAX_LEN_INT 11
//to demonstrate both looping and sequential methods to input and output the same thing
#define USE_LOOP 1 //change to zero for doing this with no loops
int main(void)//added void
{
int menu[ELEMENTS] = {0};
//char buffer `output` should accommodate room for max number of
//characters expressed in 32bit `int` data type: `11` (from the value: `-2147483648`)
//times count of elements to be output: ELEMENTS plus NULL terminator + punctuation.
//This should do it:
int size = ELEMENTS*MAX_LEN_INT+ELEMENTS + 1;
char output[size];//buffer for outputing final line showing user input values
memset(output, 0, sizeof(output));
#if USE_LOOP
int i;
printf("Input array values:\n");//moved outside the loop to display only once
for(i = 0; i < ELEMENTS; i++)
{
printf("enter value %d:\n", i+1);//prompt user for each input value
scanf("%d", &menu[i]);//scan value into array element
}
#else //Use sequential data entry
printf("Enter %d space delimited integer values (eg: 1 2 -45 78... 123) then <enter>:\n", ELEMENTS);
scanf(input_format, input_data);
#endif
//again, outside the loop to display only once
//place all data into printable buffer
sprintf(output, format, data);//using short representations of format specifier and data for readability
printf("%s", output);
return 0; //added return to comply with int function type.
}
Tested with largest possible number of digits using sequential method:
I create it a program that asks for raw and columns after that asks you to put numbers to the dimensional array. This arrays inputs to a file. When i open the file i can't see the array.
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
int main () {
FILE *fp;
int n,m;
int i,j;
float b;
char filename[100];
int getfloat(float *);
printf("Number of rows\n");
scanf("%d",&n);
printf("Number of colums\n");
scanf("%d",&m);
float s[n][m];
for (i=1;i<=n;i++)
{
for (j=1;j<=m;++j)
{
printf("Insert number %d",i);
printf(",%d\n", j);
scanf("%f",&b);
s[i][j]=b;
}
}
printf("Enter file name \n");
scanf("%s", filename);
// ****print file****
fp=fopen(filename,"w+");
if(fp!=NULL)
{
fputs(s,fp);
fprintf("%c",s);
}
fclose(fp);
return 0;
the only thing i see is this
If you want a list of numbers, probably in some kind of grid in the file, then at the minimum you want a loop such as the following:
for (int i=0; i<n; ++i)
{
for (int j=0; j<m; ++j)
{
fprintf(fp, "%f ", s[i][j]);
}
fprintf(fp, "\n");
}
See fprintf for documentation on the format specifiers; you'll probably want to tweak that to get better-looking values.
Also, again, note that arrays start from 0. Your initial read loop skips the very first element, and writes past the end of the actual array.
fprintf("%c", s); and fputs does not print out the contents of the array, it prints out the location stored in the array's pointer and tries to interpret it as a char. What you would need to print out the proper values is to loop through each value and use fprintf with each float value, using s[i][j] similar to how you initialized it.
The way you initialized the array is also off, as arrays begin at 0, not 1. Currently your for loop does not ever access s[0][0] or s[1][0] and so on. Your for loops should have i initialized to 0, and have the condition be i < n instead of i<=n.
I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:
#include <stdio.h>
#include <stdlib.h>
int checkInversions(int arr[], int n) {
int i, j, inverse_count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
inverse_count++;
}
}
}
return inverse_count;
}
int main() {
int arr[10], i, n;
printf("Enter the elements of the array: %d");
for (i = 0; i <= 10; i++) {
scanf("%d", &arr[i]);
}
n = sizeof(arr) / sizeof(arr[0]);
printf("\n The inverse is: %d", checkInversions(arr, n));
return 0;
}
Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.
You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.
What you meant to do was merely:
printf("Enter the elements of the array: ");
Also, since arr has 10 elements, you iterate through it as such:
for(i = 0; i < 10; i++)
You don't need to use sizeof to determine the size of the array since you already know it; it's 10.
I think you are missing the variable that should populate the %d on the printf.
Try taking out the %d on the printf call so it ends up like:
printf("Enter the elements of the array: ");
Or assign the corresponding variable to display with that "%d", like this:
printf("Enter the elements of the array: %d", variable);
Check if that helps!
Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");
Am having many problems with coding C. Apologies for any bad mistakes. Im trying to do simple horizontal histogram for frequency of integers in array. No matter what it prints out incorrect and makes infinite loop. I believe the problem lies in printHistogram function. Any tips?
Here is code:
#include <stdio.h>
//Prints histogram to screen using horizontal bar chart
void printHistogram ( int *hist, int n );
int main ( void )
{
int i, n;
printf ("How many values for array? ");
scanf ("%d", &n);
int list[n];
for (i=0; i < n; i++) {
printf ("Enter value: ");
scanf ("%d", &list[i]);
}
// Process data to compute histogram
int hist[10];
// Print histogram
printHistogram ( hist, 10);
return 0;
}
void printHistogram ( int *list, int n )
{
int i, j;
for (i=0; i < n; i++) {
printf ("[%d] ", i);
for (j = 0; j < list[i]; j++)
printf ("*");
printf ("\n");
}
}
The problem is in
for (j = 0; j < list[i]; j++)
when, you're trying to use list[i], but based on the argument passed, the value is indeterminate. So, in this case, this invokes undefined behavior and the loop goes haywire.
To elaborate, you have defined int hist[10]; as a local variable and did not initialize it, so all the members contain indeterminate value. You then, go ahead and pass the array to printHistogram(), inside which, you receive it via list and then, dereference that and expect to get some valid value magically, which is not possible.
OTOH, you are scanning values in list inside the main() and not using it. You need to make some corrections so as to make use of the scanned value later, which seems to be the actual target.
I need to read x and y coordinates from a text file then use them for polynomial regression. I can do the regression part but I can't read the values from the file. Data points are
5,10,15,20,25,30,35,40,45,50
17,24,31,33,37,37,40,40,42,41
First row is x and second row is y, and they're exactly written like this in the txt file.
From another question I managed to read all the numbers into a single x array of 20 but I really need for them in seperate arrays as x and y. How can I do this?
Here's my current code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *data;
data = fopen("data.txt", "r");
int x[20];
int i=0;
for(i=0; i<20; i++)
fscanf(data, "%d,", &x[i]);
for(i=0; i<20; i++)
printf("x are: %d\n", x[i]);
fclose(data);
return 0;
}
Thanks in advance.
If you always have 10 int in one line and 10 more int in another line as you stated in your question, you can use one more array int y[10]; to store y values. And use two for loops - one for reading 10 x values, and another for reading 10 y values. And both your arrays just need to store only 10 elements.
int x[10];
int y[10]; // Array to store y values
int i=0;
for(i=0; i<10; i++) // Read first 10 values to x array
fscanf(data, "%d,", &x[i]);
for(i=0; i<10; i++) // Read next 10 values to y array
fscanf(data, "%d,", &y[i]);
for(i=0; i<10; i++)
printf("x are: %d\n", x[i]);
for(i=0; i<10; i++)
printf("y are: %d\n", y[i]);
However if there is a chance that there may be different number of integers - more or less than 10 - in those lines then you will need to do more checks.
check exist the comma
int x[20], y[20];
int i, n;
char tail;
for(i = 0; i < 20 && 2 == fscanf(data, "%d%c", &x[i], &tail); i++){
if(tail != ',')
break;
}
n = i+1;//if(n > 20){ puts("bad format!"); return -1;}
for(i = 0; i < n; i++)
fscanf(data, "%d,", &y[i]);
fclose(data);
for(i = 0; i < n; i++)
printf("(%d, %d)\n", x[i], y[i]);
First off all i advice you to write your x and y values by pairs (seems more logical, so it is simpler to implement). For example:
1 2
3 4
5 6
So fscanf(FILE* fp, char* format,...) :
FILE* fp - pointer to stream you want to read data from (which can be even standard stdin which makes fscanf() work as scanf());
char* format - format string (for example: "%d%s%d");
... - addresses of variables and / or areas in memory that will receive inputted data. Number of variables are specified by char* format.
You use fscanf(data, "%d,", &x[i]); instead of using fscanf(data, "%d%d", &x[i],&y[i]); forgetting that you get as much data as you specify in char* format.
Also note, that fscanf() as well as scanf() returns number of successfully inputted data, meaning that you can do something like this:
while(fscanf(data,"%d%d",&x[i],&y[i]) == 2) {
// do something, or don't
}
You can leave while empty. In the end, you will get your x and y points stored in separate arrays. What happens is that fscanf() tries to read two integer values. if he manages to do this, he returns number of successfully inputted data, meaning 2. Else he returns 1 (if you missed x or y in pair) or 0 (if it is end of file).