This is a question that I have found on this site but the responses were not directly related to what I believe my problem is. I am a little embarrassed because I'm still very much an amateur. I am asking the user for how many GPAs they would like to enter. Then I am asking for input for each index. The problem is each index is returning 0. So I'm pretty sure I am messing up either the variable type or possibly the way I am incrementing the index. This is a homework problem and I am looking more for guidance than a complete give away.
#include<stdio.h>
main()
{
char Rspns;
int i, toCount, Total;
float GPA[toCount];
printf("\n\tYou can average up to 30 GPAs.");
printf("\n\tPlease choose how many GPAs you would like to average:");
scanf(" %d" , &toCount);
//assign how many indexes array should have
for(i = 0; i<toCount; i++)
GPA[i] = i++;
do
{
system("cls");
printf("\n\nEnter a GPA:");
scanf(" %f" , &GPA);
printf(" %f" , GPA[i]);
Total += GPA[i];
getch();
system("cls");
printf("\n\n\tWould you like to average the current amount of GPA's?");
printf("\n\nY/N: ");
scanf(" %c" , &Rspns);
if(Rspns == 'y' || Rspns == 'Y')
{
Total = Total / toCount;
printf("The average of those GPAs is %.1f" , Total);
getch();
}// end response
}while(i<=toCount);//end forCount
Total = Total / toCount;
}
int i, toCount, Total;
float GPA[toCount];
toCount is not initialized at this point.
Total += GPA[i];
same here, Total starts with an indeterminate value.
This
scanf(" %f" , &GPA);
is absolutely not what you want to do: remember, arrays and pointers are closely related in C - see this SO answer.
scanf(" %f" , &(GPA[i]) );
will scan the value into the i'th element of the array
I think you should be scanning into the specific float as opposed to scanning into the whole array
scanf("%f", &GPA[i]);
also, check your types for printf, the compiler is spewing out warnings.
Either initialise your GPA array to be a fixed size and validate toCount to be between 1 and the maximum, or use the memory allocation functions malloc or calloc to dynamically allocate your GPA array once you know the size (and free when finished with it).
I can't work out what you are trying to do where you say "assign how many indexes array should have", but there's no need to enter values into the array that you are going to subsequently overwrite (you can use calloc as described above to initialise them all to zero). Note that you should scan into the ith element of the GPA array (&GPA[i]), not into &GPA which is always the first element.
Also, be careful about the i++ because you are incremementing i twice each loop. Although that part of your code is unnecessary, it's a trap to watch out for in general.
Related
Im trying to make a program which says how many times a specific digit appears on a 100 numbers sequence.
Meanwhile I got this error and I can´t understand what is the solution to this. I´d appreciate if you could get me some tip or the solution.
#include <stdio.h>
int main() {
int i, m, digit, val[99], count=0;
printf("Enter a number:");
scanf("%d", &val[0]);
while (val[0] < 0) {
printf("Enter a number:");
scanf("%d", &val[0]);
}
for (i=1;i<101;i++) {
val[i]=val[0]++;
printf("%d\n", val[i]);
}
printf("Enter a digit:");
scanf("%d", &m);
while (m<0||m>9) {
printf("Enter a digit:");
scanf("%d", &m);
}
do {
digit=val[i]%10;
val[i]=val[i]/10;
if (digit==m) {
count++;
}
}while (val[i]>0);
printf("The digit %d is printed %d times in this sequence.", m, count);
}
In the for loop you step outside of the array val of which the last index is 98. Instead of hard-coding the length of the array in several places it is more convenient to use a length macro, like this:
#define LEN(anArray) (sizeof (anArray) / sizeof (anArray)[0])
...
for (i = 1; i < LEN(val); i++) {
...
Also, in the do-while loop the index i is outside of the array bounds of val. You also need to check the return value of scanf to make sure the input is valid. The last printf statement also needs a trailing newline.
Edit: Note that LEN only handles "real" arrays; arrays passed to functions are received as pointers.
You allocated only int /* ... */ val[99] (only val[0] to val[98] are available) and accessed upto val[100] because the loop condition is i<101.
This will lead to dangerous out-of-range write (undefined behaior).
Allocate enough elements like int /* ... */ val[101] or fix the loop condition not to cause out-of-range access.
Also you didn't set value of i after the for (i=1;i<101;i++) loop, so value of uninitialized element will be used in the do ... while loop. Values of uninitialized elements of non-static local variables are indeterminate and using the value invokes undefned behavior.
Set i to proper value before the loop or change the indice i to proper thing.
I am a beginner to C language and also computer programming. I have been trying to solve small problems to build up my skills. Recently, I am trying to solve a problem that says to take input that will decide the number of series it will have, and add the first and last number of a series. My code is not working and I have tried for hours. Can anyone help me solve it?
Here is what I have tried so far.
#include<stdio.h>
int main()
{
int a[4];
int x, y, z, num;
scanf("%d", &num);
for (x = 1; x <= num; x++) {
scanf("%d", &a[x]);
int add = a[0] + a[4];
printf("%d\n", a[x]);
}
return 0;
}
From from your description it seems clear that you should not care for the numbers in between the first and the last.
Since you want to only add the first and the last you should start by saving the first once you get it from input and then wait for the last number. This means that you don't need an array to save the rest of the numbers since you are not going to use them anyway.
We can make this work even without knowing the length of the series but since it is provided we are going to use it.
#include<stdio.h>
int main()
{
int first, last, num, x = 0;
scanf("%d", &num);
scanf("%d", &first);
last = first; //for the case of num=1
for (x = 1; x < num; x++) {
scanf("%d", &last);
}
int add = first + last;
printf("%d\n", add);
return 0;
}
What happens here is that after we read the value from num we immediately scan for the first number. Afterwards, we scan from the remaining num-1 numbers (notice how the for loop runs from 1 to num-1).
In each iteration we overwrite the "last" number we read and when the for loop finishes that last one in the series will actually be the last we read.
So with this input:
4 1 5 5 1
we get output:
2
Some notes: Notice how I have added a last = first after reading the first number. This is because in the case that num is 1 the for loop will never iterate (and even if it did there wouldn't be anything to read). For this reason, in the case that num is 1 it is reasonably assumed that the first number is also the last.
Also, I noticed some misconceptions on your code:
Remember that arrays in C start at 0 and not 1. So an array declared a[4] has positions a[0], a[1], a[2] and a[3]. Accessing a[4], if it works, will result in undefined behavior (eg. adding a number not in the input).
Worth noting (as pointed in a comment), is the fact that you declare your array for size 4 from the start, so you'll end up pretending the input is 4 numbers regardless of what it actually is. This would make sense only if you already knew the input size would be 4. Since you don't, you should declare it after you read the size.
Moreover, some you tried to add the result inside the for loop. That means you tried to add a[0]+a[3] to your result 4 times, 3 before you read a[3] and one after you read it. The correct way here is of course to try the addition after completing the input for loop (as has been pointed out in the comments).
I kinda get what you mean, and here is my atttempt at doing the task, according to the requirement. Hope this helps:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first, last, num, x=0;
int add=0;
printf("What is the num value?\n");//num value asked (basically the
index value)
scanf("%d", &num);//value for num is stored
printf("What is the first number?\n");
scanf("%d", &first);
if (num==1)
{
last=first;
}
else
{
for (x=1;x<num;x++)
{
printf("Enter number %d in the sequence:\n", x);
scanf("%d", &last);
}
add=(first+last);
printf("Sum of numbers equals:%d\n", add);
}
return 0;
}
First, I am a total beginner, so the question is probably very obvious for all of you, but i don't get what's wrong with the while loop in this program. Te aim of the program is to calculate the average between numbers where the user inputs 0 when he wants to continue putting numbers in and inputs 1 when he wants to stop, so the loop is supposed to stop when the user puts 1 and to compute a sum of the values when he enters 0 at the end. So this is what i wrote, i used stdio.h and stdlib.h as libraries :
int decision;
int value;
int sum = 0;
float av;
int order = 1;
printf ("for continue press: 0\n ");
printf ("for stopping press: 1\n ");
while (decision == 0) {
printf("input value:");
scanf("%d", &value);
sum = sum + value;
printf ("continue?");
scanf("%d", &decision);
order = order + 1;
}
av = (float) sum / (float) order;
printf("the average is: %.2f", av);
return EXIT_SUCCESS;
what the terminal displays is just "the average is:0.00", it skips the whole operation above.
You should initialize decision to 0
int decision = 0;
so that the while loop is true
while (decision == 0) {
on the first iteration.
In C, simply declaring a variable does not assign it a value of 0. You have to do that. In fact, actually using a variable that has not been initialized is undefined behavior. Most likely, the variable contains whatever contents was in the memory location assigned to it.
The solution is to actually define decision.
int decision = 0;
In C, declaring a variable does not initialize it. So the initial value of decision is more or less random. If it's not zero (and it likely is not), the cycle is never entered.
Perversely, when in "debug mode" or using some instrumentation such as valgrind, memory might be either zeroed or initialized consistently, leading to "unreproducible" bugs that may be difficult to track. That is why you really want to always initialize your variables
Try with:
int decision = 0;
Also, turn on all compiler warning flags. You want to be warned when such things happen, and the compiler can do so if you tell it to.
Another way
You do not need decision anywhere else, so it's good to have one less variable in the outer scope:
for (;;) {
int decision; /* The variable only lives inside this loop */
printf("input value:");
scanf("%d", &value);
sum = sum + value;
printf ("continue?");
scanf("%d", &decision);
if (0 == decision) {
break;
}
order = order + 1;
}
Notice
If you start order from 1, and enter only one value, order will be increased to 2, and this will get your calculation off. Either start from 0 or increase the value after decision confirmation.
You have not initialized the decision variable and that is why the error.
int decision = 0;
I'm working on a project at the moment where I have to allow a user to enter an infinite amount of numbers and reverse the order of those entered numbers and end the program if 0 is entered. I did something similar, except the one I did set the amount of numbers the user could enter, so for example in the code below, I allowed the user to enter only three numbers, reverse the order and end when -1 is entered.
#include <stdio.h>
#define MAX 3 // Defining max amount of numbers to be entered to 3
main()
{
int numbers[MAX], i, end;
printf ("Please enter %d integers:\n", MAX);
for (i = 0; i < MAX; i++){
scanf("%d", &numbers[i]);
if (numbers[i]==-1){ // Loop ends when -1 is entered
for (end=i; end<MAX; end++)
numbers[end]='\0'; // Nulls the value of blank locations in the array
i=MAX;
}
}
printf ("\nThe values in reverse order are:\n");
for (i = MAX-1; i >= 0; i--)
{
if(numbers[i]!='\0') // Will not print null values in the array
printf("\n%d ", numbers[i]);
}
return 0;
}
How can I go about achieving this? I'm guessing I won't be able to use an array, and I'm pretty new to this so...
No, arrays can't be grown dynamically (not without some extra tinkering, see comment below) so they can't hold an infinite amount of items.
You'll need some structure you can grow, C doesn't provide one so you'll have to use a third party implementation or write your own. A stack fits your problem the best.
Also, your loop will have to go on until -1 is entered. Either an infinite loop with a break statement, or a do-while loop that checks the entered number.
EDIT: The original question targeted C++, my original answer, below, is no longer relevant.
You want to look into C++'s STL. std::vector, std::deque or std::stack for example, would be useful in your case.
You can use a std::vector to do this.
Here's the declaration of your std::vector. Where the tells the vector you want it to be a vector of type int
std::vector<int> numbers;
Then to add to the end of the std::vector you use push_back(), which puts the integer onto the back of the array. The size of the vector will dynamically increase as you push more elements on to the back.
int input;
numbers.push_back(input);
Then to iterator through it you can use a reverse iterator or just iterate the same way you have been doing it using numbers.size() to find out how many elements are in the vector.
I am learning array and just wrote this small program to see how it works. but its crashing with segmentation faul which i understand mean i am writing my variable / function to an memory place not allotted to it. But I cant figure how. Can anyone let me know please?
i am calling introArray from my main().
int introArray (void)
{
int total, ctr;
printf("enter how many students \n");
scanf("%d", &total);
int students[total];
ctr = 0;
while ( students[ctr] <= total)
{
printf("enter student %d DOB in mmddyy \n", ctr );
scanf("%d", students[ctr]);
ctr++;
}
return 0;
}
In your code, there is one implementation logic issue. The total number of students is total and hence, your while loop should be
while(ctr < total)
The data to be read also should scanf("%d", &students[ctr]); There is an ampersand missing
ctr goes beyond total. This way you are going out of bound
Change the loop to
while (ctr < total)
{
printf("enter student %d DOB in mmddyy \n", ctr );
scanf("%d", &(students[ctr]));
ctr++;
}
I think
scanf("%d", students[ctr]);
should be
scanf("%d", &students[ctr]);
This line
while ( students[ctr] <= total)
is not protection against reading past your array bounds inside the loop. This will stop you reading past the end of your array provided you use ctr as your index
while ( ctr < total)
you need the strict inequality as array indices are zero based.
In addition, your scanf call inside your while loop is wrong - the second argument should be a pointer and currently you pass an integer. It should be
scanf("%d", &students[ctr]);