So I'm trying to make an array with multiple values.
However, I want the user to be able to not only decide each value, but how many values are in the array itself.
The program doesn't seem to work, though.
Issue at hand is that every time I run my code it runs just fine until it gets to the for loop. The code allows me to input one value but then just exits with the following message:
Process returned 5 (0x5) execution time : 2.656 s
I've tried a couple of other methods but none of them seem to work.
Here's my latest attempt
// Initiate variable
int iterations;
printf("Input amount of values: ");
scanf("%d",&iterations);
fflush(stdin);
int listOfValues[iterations];
fflush(stdin);
int i;
int tempvar;
printf("Input values in order: ");
for (i = 0; i < iterations; i++);
{
scanf("%d",&tempvar);
fflush(stdin);
listOfValues[i] = tempvar;
}
What am I doing wrong here?
Please keep in mind I'm still in the stage of learning C and programming in general, so be gentle!
it a small mistake just remove the semicolon after the for loop.
like this:
// Initiate variable
int iterations;
printf("Input amount of values: ");
scanf("%d",&iterations);
fflush(stdin);
int listOfValues[iterations];
fflush(stdin);
int i;
int tempvar;
printf("Input values in order: ");
for (i = 0; i < iterations; i++)
{
scanf("%d",&tempvar);
fflush(stdin);
listOfValues[i] = tempvar;
}
if we put a semicolon after the for statement it will run just once
hope this helped
Related
I know this seems a very easy problem but till I am not getting the required output. Please correct any mistakes on asking the question as i am posting question on this site for the first time.
The code I tried is as follows:
#include<stdio.h>
int main()
{
int i, n;
char name[20][80];
printf("\nEnter the number of students: ");
scanf("%d", &n);
printf("\nEnter the name of the students: ");
for(i=0; i<n; i++)
{
fgets(name[i], 80, stdin);
}
printf("\nThe name of the students are: \n");
for(i=0; i<n; i++)
{
puts(name[i]);
}
return 0;
}
But the output is like:
Enter the number of students: 3
Enter the name of students: Park Jimin
Jeon Jungkook
The name of the students are:
Park Jimin
Jeon Jungkook
I can't understand why the number of students became 2 though I mentioned 3.
Please help.
Don't use the scanf family of functions - in my experience they cause more problems than they solve. In this case the issue is that scanf leaves the newline (\n) character in the buffer after you entered the number of students, so a blank line was read the first time your program tried to get a student name. The following should solve your homework problem successfully:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i, n;
char buf[20];
char name[20][80];
printf("Enter the number of students: ");
fgets(buf, sizeof(buf), stdin);
n = atoi(buf);
for(i=0; i<n; i++)
{
printf("Enter student name #%d: ", i+1);
fgets(name[i], 80, stdin);
name[i][strlen(name[i])-1] = '\0'; /* overwrite the trailing \n */
}
printf("\nThe names of the students are:\n");
for(i=0; i<n; i++)
printf("name[%d] = \"%s\"\n", i, name[i]);
return 0;
}
OnlineGDB test here
Instead of using fgets and puts use scanf and printf as shown in below code. Below code is working I checked it. You can change it as you want show like with carriage return etc.
int i, n;
char name[20][80];
printf("\nEnter the number of students: ");
scanf("%d", &n);
printf("\nEnter the name of the students: ");
for(i=0; i<n; i++)
{
//fgets(name[i], 80, stdin);
scanf("%s",name[i]);
printf("%d",i);
}
printf("\nThe name of the students are: \n");
for(i=0; i<n; i++)
{
//puts(name[i]);
printf("%d%s",i,name[i]);
}
return 0;
From my pov, the issue here is an unexpected newline character in the input buffer. While this behaviour is known, there are two different approaches to resolve this.
1. Sanitize your inputs:
Simply reading data and working on this data is often a bad idea. Therefore you may want to check, if the data you just got makes sense and is within your expectation. In your example you should never accept an empty name, no matter if comes from buffer artifacts or real user input.
int j = 0;
while(j<n)
{
printf("Write to index: %d", j);
fgets(name[j], 80, stdin);
if (name[j][0] != '\n')
{
j++;
}
}
https://onlinegdb.com/Hy5ZDWq0U
Restructuring your input loop to something like this already gets rid of empty entries. Yet it is not even close to a fully sanitized input as there are numbers, printable and non-printable special characters and length limitations to consider.
The printf("Write to index: %d", j) easily shows you, that the evil newline is still there, but due to our input check it is overridden within the next loop execution. The output loop can remain unchanged and will not print any empty entries anymore.
2. Try to clear the buffer:
Another approach is to clear the buffer in order to get known preconditions before calling fgets or similar functions. Within Using fflush(stdin) you can find a nice discussion on how this can go wrong and why it is rather brittle to do so.
Personally I would always prefer the first over the second solution, as your code should be responsible to handle unexpected inputs according to its needs. Relying on others easily goes wrong, if they do not exactly know, what your expectations are.
I've been trying to convert my python to C code and it's my first time using C.
Basically I want it to ask how many grades I will input and then put them in an array. The problem is that the amount keeps putting in the array. I thought that I could declare the size of the array after asking how many grades I was inputting but I think that's the problem. I am not sure how else to do it. I have a lot of printfs I was using for debugging.
Any Suggestions?
double enter_quiz_grades()
{
int quiz_amount,loop,i;
printf("Enter number of quiz grades to enter:");
scanf(" %d \n", &quiz_amount);
printf("You typed %d students\n",quiz_amount);
double temp=0;
double grades[quiz_amount];
for (loop = 0; loop<quiz_amount;loop++)
{
printf("loop is %d", loop);
i = loop+1;
printf("Enter grade for quiz %d: ",i);
scanf("%lf\n", &temp);
grades[loop] = temp;
printf("%lf",grades[loop]);
}
return 0.0;
}
The problem is you are using '\n' inside scanf. Also you can get rid of additional variables.
Here is the modified code:
double enter_quiz_grades() {
int quiz_amount, i;
printf("Enter number of quiz grades to enter:");
scanf("%d", &quiz_amount);
printf("You typed %d students\n",quiz_amount);
double temp = 0;
double grades[quiz_amount];
for (i = 0; i < quiz_amount; i++)
{
printf("loop is %d\n", i);
printf("Enter grade for quiz %d: ", i + 1);
scanf("%lf", &grades[i]);
printf("%lf\n",grades[i]);
}
return 0.0;
}
Just a small detail, not strictly related to the original question:
double grades[quiz_amount];
This creates an array, sized at runtime, from a variable. If this variable is read from somewhere, this can lead to a malicious user giving it a very high (or ngative!) value, and you are in big problems. The linux kernel is removing them from the source for this exact reason (as this syntax creates the array in the stack - attacker can modify the return address). Make this a dynamic array allocated on the heap (malloc()).
https://www.phoronix.com/scan.php?page=news_item&px=Linux-Kills-The-VLA
I need my code to print out
Input the number of values: Input the values between 0 and 9 (separated by space):
your histogram:
0-3
1-2
2-0
etc.
but it looks nothing like that? help
#include<stdio.h>
void printStars(int n){
int i;
for(i = 0;i<n;i++){
printf("*");
}
printf("\n");
}
int main() {
int i,n = 10;
int input[100];
int hist[10] = {0};
printf("Input the amount of values: ");
scanf("%d",&n);
printf("Input the values between 0 and 9 (separated by space): ");
for(i = 0;i<n;i++){
scanf("%d",&input[i]);
}
for(i = 0;i<n;i++){
hist[input[i]]++;
}
printf("\n\nYour histogram: ");
for(i = 0;i<10;i++){
printf("%d - %d\n",i,hist[i]);
}
return 0;
}
I'm assuming the printStars(int n) method is supposed to replace count of each number,
e.g. instead of 0 - 3 you would see 0 - * * *
If this is the case, you will want to change the for loop on line 25 to this:
for(i = 0; i < 10; i++){
printf("%d - ",i);
printStars(hist[i]);
}
Also, on line 24, you need an additional \n at the end of the printf to put your 0-count for the histogram on its own line: printf("\n\nYour Histogram: \n");
Don't forget to make sure your input is within bounds as well, as you never check if int n is within bounds of input[]. Speaking of this, why is n instantiated to 10, then immediately scanned into for input without use of n = 10?
If you aren't seeing any output on run, try typing input immediately. It's possible that requesting input is clearing the current line printed to.
printf("Input the amount of values: ");
scanf("%d",&n);
In this case, since there is no \n at the end of the printf and a scanf is immediately called, the input request might be clearing the output line and requesting input. Adding a \n to the end of printf might correct this, if it is the problem you're having.
Other than this, there doesn't seem to be any major problems.
your code is working. What format do you get and what format do you expect ? Personally, I have the
0-3
1-2
2-0
format
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?
I need to make a C program to read the number of students(1<=students<=25) in a class and for every student to read his exam score ex 10/20 15/20 etc(1<=score<=20) and print the max and the max score of students and the average score of class.
I made the program but it performs the for loop only once for some reason.
Can you please help me understand why?
here is the code :
#include <stdio.h>
int main(void) {
int m,i,b,sum,min,max,mo;
sum=0;
while (m<1 || m>25) {
printf("give number of students ");
scanf("%d",&m);
}
for (i=1; i<(m+1); i++) {
while (b<1 || b>20) {
printf("give score of %d student",i);
scanf("%d",&b);
}
if(i==1) {
min=b;
max=b;
}
else {
if(b<min) min=b;
if(b>max) max=b;
}
sum=sum+b;
}
mo=sum/m;
printf("max is %d and min is %d and avg is %d",max,min,mo);
}
First - initialize your variables:
int m,i,b,sum,min,max,mo; // these are declared and uninitialized
m = 0; // now it's initialized to 0
i = 0;
...
If you don't initialize them to something, you don't know what they are to start with.
Second - You need to change the value of b:
for (i=1; i<(m+1); i++) {
while (b<1 || b>20) { <-- here you're checking for b being valid
printf("give score of %d student",i);
scanf("%d",&b);
}
So the first time in b will be between 1 and 20, if you don't reset it to something invalid you'll never get here again. After you record the value of b:
sum=sum+b;
b = 0; // we're done with b for now, set it to something invalid for the while()
}
Not initialized the m and using in while condition
It is undefined behaviour using uninitialized local variable in conditon
Want to implement the same
use
do
{
printf("give number of students ");
scanf("%d",&m);
}
while(m<1 || m>25);
for (i=1; i<(m+1); i++) change the condition as i<=m It's the good technique rather < and then adding 1
Inside this loop use the same do while loop
You forgot to initialize the B variabkle, so it loops m times, never asking you to insert a score!
1. You initialize 'm' here, without any prior value
int m,i,b,sum,min,max,mo;
2. Without a value, you check for this condition. Which means, a garbage value would be used. (May/May not fulfill your condition)
while (m<1 || m>25) {
3. The crucial scanf for m is inside the previous while. Without which your FOR would run for a basic i=1 and stop.
for (i=1; i<(m+1); i++) {
You need to understand about Garbage Values in C and vital step of initializing a variable to an initial value before using it.
You may read more on this link:
What is a garbage value/How does it occur in C