Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having problems with the following code in different methods.
When i run my code and enter 2 as my parameter, i get an infinite loop of zero's and ones.
I'm not sure what is wrong with that section.
Any help would be great. Thank you!
/*global variables*/
int CPI[];
int Count[];
Whenever i choose 1 as my parameter, i enter 3 as my instruction classes however i am unable to input the CPI of class 3 or even the instruction count of class 3. Once i input the CPI and instruction count of class 2 it ends.
void SelectOne(){
tot = 0;
printf("\n Enter the number of instruction classes: ");
scanf("%d", &n);
printf("\n Enter the frequency of the machine (MHz): ");
scanf("%d", &f);
int CPI[n];
int Count[n];
int a;
for(a = 1; a < n; a++){
/*printf("%d",n);*/
printf(" Enter CPI of class %d : ", a);
scanf("%d", &CPI[a-1]);
printf(" Enter instruction count of class %d : ", a);
scanf("%d", &Count[a-1]);
tot =+ Count[a-1];
}
}
This is the method in which i get an infinite loop of 0's and 1's.
void SelectTwo(){
printf("\n ---------------------------");
printf("\n +Class/t + CPI/t +Count +");
int a;
for(a = 1; a <= n; a++){
printf("\n %d\t + %d\t + %d ", a, CPI[a-1], Count[a-1]);
}
}
I believe my problem is in main but i'm not sure of how to fix this.
int main(){
int sel = 1;
while(sel != 4){
printf("\n 1) Enter Parameters ");
printf("\n 2) Print table of parameters ");
printf("\n 3) Print table of performance ");
printf("\n 4) Quit");
printf("\n \n Enter Selection: ");
scanf("%d", &sel);
if(sel == 1){
SelectOne();
}
if(sel == 2){
SelectTwo();
}
if(sel == 3){
SelectThree();
}
else{
printf("quit");
}
}
}
"Whenever i choose 1 as my parameter, i enter 3 as my instruction classes however i am unable to input the CPI of class 3 or even the instruction count of class 3. Once i input the CPI and instruction count of class 2 it ends."
This is because you tell it to. Here:
for(a = 1; a < n; a++){
if you enter 3, then the loop runs once when a == 1, a second time when a == 2, and then quits, because a < 3 is no longer true. You want this:
for( a = 0; a < n; a++ ){ /* Change a = 1 to a = 0 */
printf(" Enter CPI of class %d : ", a + 1);
scanf("%d", &CPI[a]); /* Change [a-1] to [a] */
printf(" Enter instruction count of class %d : ", a + 1);
scanf("%d", &Count[a]); /* Change [a-1] to [a] */
tot += Count[a]; /* Change =+ to += and [a-1] to [a] */
}
Your code has lots of other problems, though, including the fact that the global variables CPI and Count that SelectTwo() appear to be using are not the same ones that SelectOne() is writing to, because in SelectOne() you create local variables of the same name which hide them.
EDIT: You edited your question to show the definitions of your global arrays:
int CPI[];
int Count[];
What this is actually doing is declaring an incomplete type, because you're not providing a size. Once you get to the end of the translation unit, if the array still has an incomplete type, then it's assumed to have one element, which is here set to zero on program startup. So you're effectively creating one-element arrays, so attempting to loop over more than one element in SelectTwo() is just undefined and nonsensical behavior.
As mentioned, the CPI and Count that SelectOne() is using are not the same ones that you are defining globally, so SelectTwo() is not reading from what SelectOne() is writing to.
If you want to use global arrays like this, you have to provide a size, e.g.
int CPI[3];
int Count[3];
If you don't want to provide a size (for instance, because here you want the user to choose the size), then you'll have to either use malloc() or define a variable length array within a function and pass it to the functions that need it.
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:
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 2 years ago.
Improve this question
For example, if I want to call switch statement in for loop, I got an error.How can I correct this issue?If I want to move my switch statement outer part in determined condition which is to be using more than calling switch statement. Thanks in advance.
#include<stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#define SIZE 50
int i = 0;
int main() {
char usertxt[SIZE], myoperator[SIZE];
printf("addition='+',subtraction='-',multiplication='*',division='/'\n");
usertxt[0] = 0;
int x, myarray[SIZE];
printf("How many numbers should be entered? ");
scanf_s("%d", &x);
for (i = 0; i < x; i++) {
scanf_s(" %c", &myoperator[i], 1);
switch (myoperator[i]) {
case '+':printf("Addition operation\n");
printf(" Enter your number: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '-':printf("Subtraction operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '*':printf("Multiplication operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '/':printf("Division operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
default :if (myoperator[i] == '\0') {
break;
};
}
}
}
As #Gerhardh said, welcome to SO.
But I really think that the logic behind your code isn't good enough.
I take some time to understand your goal and I make a new clearer version.
While testing and understanding your code, I've encountered the following problems:
Implicit declaration of function 'scanf_s' is invalid in C99
Declarations of global variables as counters and their usage inside the loop were the main reason why your code doesn't work as expected.
The printf() function is used for printing the output. It returns the number of characters that are printed. If there is some error then it returns a negative value. You used it like it returns a char or even a string.
Switch statement is useless if you have to do always the same operations.
Char reading doesn't work correctly.
I'm gonna attach here the updated code. Hope that it could be helpful and that actually it has the same "goal" that your code has.
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#define SIZE 500
#define nOperator 4
int main() {
char usertxt[SIZE], myoperator[nOperator];
printf("addition='+',subtraction='-',multiplication='*',division='/'\n");
usertxt[0] = 0;
int nOperations;
int x, myarray[SIZE];
printf("How many numbers should be entered? ");
scanf("%d", &x);
printf("How many operations would you like to try? ");
scanf("%d", &nOperations);
for (int i = 0; i < nOperations; i++) {
fseek(stdin, 0, SEEK_END);
printf("\n\nEnter operation #%d: ", i + 1);
myoperator[i] = getchar();
for (int j = 0; j < x; j++) {
printf("Enter number #%d: ", j + 1);
scanf("%d", &myarray[j]);
}
int k = 0;
for (int m = 0; m < x; m++) {
if (m == x - 1) {
usertxt[k] = myarray[m];
printf("%d", myarray[m]);
} else {
usertxt[k] = myarray[m];
usertxt[k + 1] = myoperator[i];
printf("%d%c", myarray[m], myoperator[i]);
}
k++;
}
printf("\n\n");
}
}
As you can see, I tried to stay as much as next to your code idea and implementation.
For instance, I've not deleted the initial pragma and define. Probably you are going to use them later.
I've used fseek(...) as suggested here:
How to clear input buffer in C?
in order to read correctly char and integers together.
First thing first, it reads the numbers that you want to use and the number of operations that you want to do. After that, it takes the numbers associated with a certain operation, and at the end, it prints the expression as you are doing in your own code.
If you want to add the result, you just need a little edit in the code to sum all the numbers in the array or counting them while reading from input.
Variable Counters Description:
i is for 'myoperator' array
k is for 'usertxt' array
m is for 'myarray' array
Next steps:
Add the result variable to display the result of the operation
Use dynamic memory
Note that:
fseek(...) works on some systems; if not, then it is not surprising as nothing guarantees that it will work when standard input is an interactive device (or a non-seekable device like a pipe or a socket or a FIFO, to name but a few other ways in which it can fail).
If you need that it has to be portable, then check the link that I've placed before.
Hope that it was helpful.
Cheers,
Denny
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Not doing anything special. Just taking a user's input between 1 - 500, and then printing the number using for loop for each iteration. It crashes at the for loop. It does not print anything at all.
#include <stdio.h>
int forCounter() {
int num;
int count = 0;
printf("Pick a positive number (1 - 500): ");
scanf("%d", &num);
while (num < 1 || num > 500) {
printf("Out of range, try again (1 - 500): ");
scanf("%d", &num);
}
int i = num;
for (i; count <= i; count++) {
printf(count);
}
getchar();
return 0;
}
I take first input applied to 'num' and check if it's above or below allowed amount with the while loop.
When that's done it leaves and should start the for loop with i taking over for num. I tried using num in the place of i but it didn't work so I tried using a separate variable to see if it'd work.
I get two warnings seen in the image providedTwo warnings
You have to specify the format of output in printf.
int printf(const char *format, ...)
Your code:
#include <stdio.h>
int forCounter(void) {
int num;
printf("Pick a positive number (1 - 500): ");
scanf("%d", &num);
while (num < 1 || num > 500) {
printf("Out of range, try again (1 - 500): ");
scanf("%d", &num);
}
for (int i = 1; i <= num; i++) {
// printf(count); --> Bad
printf("Value = %d\n", i);
}
getchar(); // this will return immediately
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having a problem setting a variable entered by the user. I entered something in and it stores another value. Pretty frustrating. So any guidance would be great.
Be advised, there are quite a few printf(), as I was trying to pinpoint the problem. Also I am still trying to get a hold of C.
#include <stdio.h>
int vehicletype, in, out; // User Entered Info
int vehicleID[5000];
float vehicleCharge[5000];
int i;
// Variables for Main Function
int q; // Loop Control
float z;
int main (){
for(q = 1; q != 1518944; q++) {
printf("Enter your position in the parking queue: ");
// Take the queue entered by the user and assign it to i
scanf("%d\n", &i);
// Take the user input(which is being held in the variable i) and place it into the 'i'
//position of the ID array
vehicleID[q] = i;
printf("Enter the time(past 0600) you wish to start parking: \n");
//take the time and pass it to the time function to determine roundup
scanf("%d\n", &in);
printf("Enter the time(before 2200) you wish to leave: \n");
scanf("%d\n", &out);
printf("Time in: %d\nTime out: %d\n", in, out);
}
return 0;
}
#M.M I should be able to enter 0617 into the "in" variable and 1547 for the "out" (I use this later to find out how much they parked) but the output I get when checking the variables by printing "in" and "out" is 1 and 399 respectively.
Here is some more or less working code. I don't understand the 1518944 limit, but the code takes steps to ensure that regardless of how many entries you make, the code won't write out of bounds of the array vehicleID. It also checks some numbers for validity, and echoes its inputs. The leading newlines on some of the outputs makes the output appear semi-sane when the data is written via another program (a random number generator was what I used to generate numbers 1-5000 and two times 0600-2200).
#include <stdio.h>
static int vehicleID[5000];
int main(void)
{
for (int q = 1; q != 1518944; q++)
{
int in, out;
int i;
printf("\nEnter your position in the parking queue: ");
if (scanf("%d", &i) != 1)
break;
vehicleID[q % 5000] = i;
printf("Enter the time (past 0600) you wish to start parking: ");
if (scanf("%d", &in) != 1)
break;
printf("Enter the time (before 2200) you wish to leave: ");
if (scanf("%d", &out) != 1)
break;
if (in < 600 || in > 2200 || out < 600 || out > 2200 || in >= out)
printf("Invalid times (in %.4d, out %.4d)\n", in, out);
else
printf("\nPosition: %d; Time in: %.4d; Time out: %.4d\n", i, in, out);
}
putchar('\n');
return 0;
}
Note that inputs are checked, and echoed. Checking is a crucial programming technique; printing (echoing) is a basic debugging technique.
I'm trying to write a simple program that'll prompt the user to enter N numbers, store them in an array, then just sum them all up
I understand I can just do this with a recursion but I'm trying to learn how array works
Example:
1 (hit enter)
2 (hit enter)
...
10 (hit enter)
Expected output: 55
#include <stdio.h>
int main (void){
int n;
int a[n];
int counter;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
printf("OK! now enter your number: \n");
for (int i = 0; i <= n; i++){
scanf("%d", &a[i]);
counter =+ a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
Right now there's no error message, no output, just the standard windows error message
"scanner.exe has stopped working..."
I'm using Win8 and GCC compiler
First of all, you can't create an static array without first knowing its size. You first need to ask the user for the "n" variable and then declare your array.
You also need to explicitly initialize your counter variable to be zero before you start counting. In C, variables don't default to 0 when you declare them.
The operator "=+" doesn't exist AKAIK, change it to "+=".
Last but not least, the limit in your loops is a little off, you're asking for 11 values ;)
(I edited this post, I was wrong about only asking for 9 values. I tend to confuse that sort of stuff)
#include <stdio.h>
int main (void){
int n;
int counter = 0;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
int a[n];
printf("OK! now enter your number: \n");
for (int i = 0; i < n; i++){
scanf("%d", &a[i]);
counter += a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
You are using variable length arrays. At run time the value of n must be known. Place the declaration
int a[n];
after taking input for n, i.e, after scanf("%d", &n); and initialize counter to zero before using it otherwise you will get garbage value (because of undefined behavior).
Also change the for loop condition from i <= n to i < n.
After this line:
int n;
What do you think the value of n is?
Now go to the next line:
int a[n];
How big is this array?
Can you access it properly?