Programming while loop in C - c

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;

Related

How to add the first number and last number of a series of number in C?

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;
}

I cant write this factorial codes

I have some problem with that. I am trying to learn C programming. Please help me
#include<stdio.h>
int main()
{
int a, factorial;
printf("Please enter a value :" );
scanf("%d", &a);
for (int i = 1; i<=a; i++)
{
a = (a - 1)*a;
}
printf("%d", factorial);
return 0;
}
Well in your code line a = (a - 1)*a; you actually changed your input for getting the factorial. It also will blow your loop. See your for loop will continue as long as your i is less than a, lets say you choose a=3 after first iteration the a itself will become 6, so the for loop will continue until it reach the integer limit and you will get overflow error.
What you should do?
First of all you should use a second variable to store the factorial result, you introduced it as factorial, the way that #danielku97 said is a good way to write a factorial since if you present 0 as input it will also give the correct result of 1. so a good code is:
factorial = 1;
for (int i = 1; i<=a; i++)
{
factorial *= i;
}
But lets say you insist of subtraction, the way you just tried to use, then you need to change the code like:
scanf("%d", &a);
if (a==1 || a==0){
printf("1");
return 0;
}
factorial = a;
for (int i = 1; i<a; i++)
{
factorial *= (a - i)*factorial;
}
You can see that the code just got unnecessarily longer. An if included to correct the results for 1 and 0. Also you need to make sure that i never become like i =a since in that case a-i will be equal to zero and will make the factorial result equal to zero.
I hope the explanations can help you on learning C and Algorithm faster.
Your for loop is using your variable 'a' instead of the factorial variable and i, try something like this
factorial = 1;
for (int i = 1; i<=a; i++)
{
factorial *= i;
}
You must initialize your factorial to 1, and then the for loop will keep multiplying it by 'i' until 'i' is greater than 'a'.
You are modifying the input a rather than factorial and also wrong (undefined behaviour) because you are using factorial uninitialized. You simply need to use the factorial variable you declared.
int factorial = 1;
...
for (int i = 1; i<=a; i++) {
factorial = i*factorial;
}
EDIT:
Also, be aware that C's int can only hold limited values. So, beyond a certain number (roughly after 13! if sizeof(int) is 4 bytes), you'll cause integer overflow.
You may want to look at GNU bugnum library for handling large factorial values.

C - Can't stop program using while and logical operator

I'm just starting learning C but I really don't know what am I doing wrong. I wrote this code, and it was supposed to stop reading numbers when it receives a negative number. I have wasted a lot of time trying to figure out what it is wrong, and I still don't know what it is.
#include<stdio.h>
int main(){
const int qtd = 3;
float ent[qtd];
int i = qtd;
printf("Digite os numeros\n");
do{
scanf("%f", &ent[i]);
i--;
}while (ent[i] >= 0 && i >= 1);
printf("\n\n\n\nPressione 'Enter' para sair");
fflush(stdin);
getchar();
return 0;
}
The problem is with the index of ent that you check for being negative. It's ent[i], but it is after i has been decremented, so you are reading the location that has not been written yet by scanf.
To fix the problem, change the code to use the prior location, i.e.
do {
...
} while (ent[i+1] >= 0 && ...);
There are several other problems with your code, all coming from the assumption that array indexes start at 1. In C, however, the initial index is zero, not one, so the correct check should be
do {
...
} while (ent[i+1] >= 0 && i >= 0);
In addition, i should be initialized to int i = qtd-1; to avoid writing past the end of allocated array.

Pascal's Triangle returning nonsense values

This is a homework project I was assigned some time ago... I've been successful in getting this far on my own, and the only hiccup I have left is (I believe) an issue with data types and overflow.
I've tried changing over to unsigned and double, and the code complies and still accepts input in the terminal, but it seems to hang up after that... nothing is printed and it looks like it's caught in a loop.
Here is the code...
/* pascaltri.c
* A program that takes a single integer as input and returns the nth line of
* Pascal's Triangle. Uses factorial() function to help find items of
* individual entries on a given row.
*/
#include <stdio.h>
#include <stdlib.h>
long factorial(long i)
{
long fact = 1;
while(i > 1)
{
fact = fact * i;
i = i - 1;
}
return fact;
}
main(void)
{
long n;
long *nPtr;
nPtr = &n;
scanf(" %i", nPtr);
if (n >= 0)
{
long k;
long *kPtr;
kPtr = &k;
for(k = 0; k <= n; k++)
{
long ans;
long *ansPtr;
ansPtr = &ans;
ans = factorial(n) / (factorial(k) * factorial(n - k));
printf("\n %i", ans);
}
return 0;
}
return 0;
}
It's not perfect or pretty, but it works up to an input of 13 (that is, row 14) of the triangle. Beyond that I start getting gibberish and even negative values sprinkled throughout the returns... much larger values break the code and return nothing but an exit error message.
Any ideas on how I can correct this problem? I've been staring at the screen for much to long to really see anything myself. Also, it's not essential, but I would like to print my return values on one line, rather than having them separated by a newline character.
1 5 10 10 5 1
Would the easiest way be to load the values into an array as they are computed, and then print the array? Or is there a built-in way I can tell the print statement to occur on only one line?
You are suffering from integer overflow. You may need to find a different approach to the algorithm to avoid having to calculate the large numbers.
In answer to your other point about the newline, you are explicitly printing the newline with the \n in your print statement. Remove it, and you will get answers printed on one line. You probably want to inlucde a final printf("\n"); at the end so the whole line is terminated in a newline.
Some other observations:
You don't need the first return 0; - the control will drop out of
the bottom of the if block and on to the second (should be only)
return 0; and not cause any problems.
You're declaring kPtr but not using it anywhere
You don't need to declare a separate variable nPtr to pass to scanf; you can pass &n directly.
For the garbage, you are most likely running into an integer overflow, that is, your calculated values become too large for the long data type. You should correct it by calculating your factorial function without explicitely calculating n!.
Change scanf(" %i", nPtr); to
scanf(" %ld", nPtr);
and printf("\n %i", ans); to
printf("\n %ld", ans);
to get printout on one line, use:
printf(" %ld", ans);
If you are using gcc, turn on warnings, i.e. use -Wall.

Compound conditions using while loop in C.

The program is ignoring Stop when amt is 0 until after 10 numbers have been entered. The program also doesn't stop after 10 numbers have been entered. Where is my error?
main() {
int amt;
int tot = 0; /* running total */
int i = 0; /* counts number of times in loop */
while (amt!=0 || i < 10)
{
printf("Enter a number (enter 0 to stop): ");
scanf("%d", &amt);
tot = tot + amt;
i++;
}
printf("The sum of those %d number is %d.\n", i, tot);
}
Your test is happening before amt is assigned. Thus its results are undefined. This test should be moved to the end of the iteration, i.e. a do/while. Whilst you could assign amt to some non-zero value this feels slightly untidy to me.
And surely you mean to use logical AND rather than logical OR? You only want to continue iterating if both amt is non-zero AND i<10.
Of course, if you did move the test to the end of the iteration then you would have to account for the fact that i had been incremented inside the loop.
In order to stop after 10 numbers or amt=0 (whichever first is met) you'll have to change the loop condition to while (amt!=0 && i < 10)
int amt;
Since you do not initialize it. It has some random value and that causes the Undefined Behavior in your program.
You should always initialize local variables with values.

Resources