In this file I am trying to make something that adds all numbers up to a number entered by a user. Such as, 4: 1 + 2 + 3 + 4 = 10. So if they enter 4 it returns 10.
When I run the code I get an error message saying my file has stopped working. Do i have an endless loop?
#include "biglib.h"
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
// Asking them for their number
int num;
scanf("%i", num);
// then I run a loop, if num == 0 then the program should break from the loop and return 0 in the main function if not run the code inside the program.
int i;
while(num != 0)
{
// I define "i" to be one less than that of num then as long as "i" is greater than 0 keep running the loop and subtract one at the end of it.
for(i = num - 1; i > 0; i--)
{
// in here I do the addition.
num = num + i;
}
// finally I print out the answer.
printf("%i\n",num);
continue;
}
return 0;
}
Yes, you have an infinite loop. Also the input is not stored in the num variable.
#include "stdio.h"
int main(void) {
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
scanf("%i", &num);
int sum = 0;
while(num>0){
sum += num;
num -= 1;
}
printf("%i\n",sum);
return 0;
}
Some lines of your code seem odd to me.
Why do you use a while loop to test the value of num ?
Why do you put a continue statement as last while loop instruction ?
Remarks:
Your code does not work for negative number, is it the expected behaviour?
You are not testing the scanf return value, which could cause trouble.
I am pretty sure that you should check the scanf prototype.
Hope these questions will lead you to improve your code.
Thank you yadras fro informing me that I had the scanf outside of the while loop that was the problem and now it works when I do this.
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
int i;
while(num != 0){
scanf("%i", &num);
for(i = num - 1; i > 0; i--)
{
num = num + i;
}
printf("%i\n",num);
}
return 0;
}
Related
Something is wrong. I'm trying to make a cade which can count number count of any natural number. Like number count of 2 is 1, 30 is 2, 456 is 3. My code is running for 1 digit numbers but not for two digit numbers.
#include<stdio.h>
void main(void)
{
int num,count,check;
float div;
printf("Enter a natural number\n");
scanf("%d", &num);
while (num<=0)
{
printf("Error\n");
printf("Enter a number\n");
scanf("%d", &num);
}
while(num>1)
{
count=1;
check=10;
div=num/check;
if(div<=1)
{
printf("Number count is\n%d", count);
break;
}
check = check*10;
count = count+1;
}
}
The problem with your solution is that after check and count are modified at the end of the loop, they are re-declared to 1 and 10 respectively at the beginning of the loop at every passage.
You need to move the declaration just before the while loop.
Also div doesn't need to be a float given that the decimal part of this number is irrelevant.
You could also use less variables by replacing check by 10 and
using num directly instead of temporarily storing results in div.
I think this might be a simpler solution
#include <stdio.h>
int main(){
int num = 0, digits = 0;
while (num <= 0)
{
printf("Enter a natural number\n");
scanf("%d", &num);
num == 0 ? printf("Error\n") : 0;
}
for( ; num > 0; digits++)
num /= 10;
printf("number of digits: %d\n", digits);
}
As num is continuously divided by 10, the decimal of the result gets truncated since num is an int while digits steadily increases.
It is time to learn to use a debugger. Using it would have immediately shown the major problem in your code: you reset the value of count and check inside the loop. So if you enter a number greater or equal to 10, you enter an infinite loop because you will consistently divide that number by 10 and find that the result is >= 1!
There is another less important problem: you use if(div<=1) when it should be if(div<1). Because 10/10 is 1 and has 2 digits...
After those fixes you should have:
...
check = 10;
count = 1;
while (num > 1)
{
div = num / check;
if (div < 1)
{
printf("Number count is\n%d", count);
break;
}
check = check * 10;
count = count + 1;
}
return 0; // main shall return an int value to its environment...
}
Which correctly gives the number of decimal digit on positive integers. But as you were said in comments, you should always test the return value of scanf (what is the user inadvertently types a t instead of 5 for example?).
That being said, this answer intends to show you what the problems were, but Keyne's solution is better...
So today I am learning the "while" loop in c#,
the task was simple:
you can keep input score between 0~100;
when you in put "-1", the program ends;
it'll output the sum and the average.
here is our teacher's answer:
#include <stdio.h>
int main(void) {
int score = 0;
int sum = 0;
int count = 0;
while(score != -1) {
printf("輸入分數(-1結束):");
scanf("%d", &score);
count++;
sum =sum + score;
}
printf("加總:%d 平均:%f\n",sum+1, (double) sum / count );
return 0;
}
here is my code:
#include <stdio.h>
int main(void)
{
int score = 0;
int sum = 0;
int count = -1;
while ( score > 0 || score <=100)
{
printf("輸入一個介於0~100的整數(-1結束):");
scanf("%d", &score);
count++;
sum = sum + score;
if ( score == -1)
{
break;
}
}
printf("加總: %d 平均: %f", sum+1, (double)sum / count);
return 0;
}
I know I'm just learning from the beginning,
my teacher said that let's not think too much about the user could input score over 100 or less than -1,
But I just can't help to think about we should first examine whether the input score is within 0~100, if it is then proceed the program,
and then the program will keep asking the user to input more, until the user input -1 and print the result of sum and the average.
so that's why I choose to wrote
while ( x >= 0 || x <= 100)
I can't figure out what is missing in the thought process.
Am I thinking the right direction?
How can I better fix the code?
I think you were on the right path, but you did miss something
#include <stdio.h>
int main(void)
{
int score = 0;
int sum = 0;
int count = -1;
while ( 1 )
{
printf("輸入一個介於0~100的整數(-1結束):");
scanf("%d", &score);
if ( score == -1 || score > 100 )
{
break;
}
count++;
sum = sum + score;
}
printf("加總: %d 平均: %f", sum+1, (double)sum / count);
return 0;
}
The important thing is to immediately exit the loop, without using the value of score, if it is not a valid score. Note that the while loop just runs indefinitely. It is only the break that stops looping. Also, note the logic in the if statement: we want to exit if the value is too low OR too high. This is the opposite of the way you'd written the code, because you wanted the loop to continue as long as the value was less than 100 AND more than -1.
You need to update your while loop condition.
while (score > 0 && score <= 100)
This is C code not C#
you can try this:
int main()
{
int score;
do {
printf("Enter a number between 0 and 100: ");
scanf("%d", & score);
} while (score > 0 && score <=100);
return 0;
}
Even though this question has been asked a million times I just haven't found an answer that actually helps my case, or I simply can't see the solution.
I've been given the task to make a program that takes in a whole number and counts how many times each digit appears in it and also not showing the same information twice. Since we're working with arrays currently I had to do it with arrays of course so since my code is messy due to my lack of knowledge in C I'll try to explain my thought process along with giving you the code.
After entering a number, I took each digit by dividing the number by 10 and putting those digits into an array, then (since the array is reversed) I reversed the reverse array to get it to look nicer (even though it isn't required). After that, I have a bunch of disgusting for loops in which I try to loop through the whole array while comparing the first element to all the elements again, so for each element of the array, I compare it to each element of the array again. I also add the checked element to a new array after each check so I can primarily check if the element has been compared before so I don't have to do the whole thing again but that's where my problem is. I've tried a ton of manipulations with continue or goto but I just can't find the solution. So I just used **EDIT: return 0 ** to see if my idea was good in the first place and to me it seems that it is , I just lack the knowledge to go back to the top of the for loop. Help me please?
// With return 0 the program stops completely after trying to check the digit 1 since it's been checked already. I want it to continue checking the other ones but with many versions of putting continue, it just didn't do the job. //
/// Tried to make the code look better. ///
#include <stdio.h>
#define MAX 100
int main()
{
int a[MAX];
int b[MAX];
int c[MAX];
int n;
int i;
int j;
int k;
int counter1;
int counter2;
printf("Enter a whole number: ");
scanf("%i",&n);
while (1)
{
for (i=0,counter1=0;n>10;i++)
{
a[i] = n%10;
n=n/10;
counter1+=1;
if (n<10)
a[counter1] = n;
}
break;
}
printf("\nNumber o elements in the array: %i", counter1);
printf("\nElements of the array a:");
for (i=0;i<=counter1;i++)
{
printf("%i ",a[i]);
}
printf("\nElements of the array b:");
for (i=counter1,j=0;i>=0;i--,j++)
{
b[j] = a[i];
}
for (i=0;i<=counter1;i++)
{
printf("%i ",b[i]);
}
for (i=0;i<=counter1;i++)
{
for(k=0;k<=counter1;k++)
{
if(b[i]==c[k])
{
return 0;
}
}
for(j=0,counter2=0; j<=counter1;j++)
{
if (b[j] == b[i])
{
counter2+=1;
}
}
printf("\nThe number %i appears %i time(s)", b[i], counter2);
c[i]=b[i];
}
}
The task at hand is very straightforward and certainly doesn't need convoluted constructions, let alone goto.
Your idea to place the digits in an array is good, but you increment counter too early. (Remember that arrays in C start with index 0.) So let's fix that:
int n = 1144526; // example number, assumed to be positive
int digits[12]; // array of digits
int ndigit = 0;
while (n) {
digits[ndigit++] = n % 10;
n /= 10;
}
(The ++ after ndigit will increment ndigit after using its value. Using it as array index inside square brackets is very common in C.)
We just want to count the digits, so reversing the array really isn't necessary. Now we want to count all digits. We could do that by counting all digits when we see then for the first time, e.g. in 337223, count all 3s first, then all 7s and then all 2s, but that will get complicated quickly. It's much easier to count all 10 digits:
int i, d;
for (d = 0; d < 10; d++) {
int count = 0;
for (i = 0; i < ndigit; i++) {
if (digit[i] == d) count++;
}
if (count) printf("%d occurs %d times.\n", d, count);
}
The outer loop goes over all ten digits. The inner loop counts all occurrences of d in the digit array. If the count is positive, write it out.
If you think about it, you can do better. The digits can only have values from 0 to 9. We can keep an array of counts for each digit and pass the digit array once, counting the digits as you go:
int count[10] = {0};
for (i = 0; i < ndigit; i++) {
count[digit[i]]++;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
(Remember that = {0} sets the first element of count explicitly to zero and the rest of the elements implicitly, so that you start off with an array of ten zeroes.)
If you think about it, you don't even need the array digit; you can count the digits right away:
int count[10] = {0};
while (n) {
count[n % 10]++;
n /= 10;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
Lastly, a word of advice: If you find yourself reaching for exceptional tools to rescue complicated code for a simple task, take a step back and try to simplify the problem. I have the impression that you have added more complicated you even you don't really understand instead.
For example, your method to count the digits is very confused. For example, what is the array c for? You read from it before writing sensible values to it. Try to implement a very simple solution, don't try to be clever at first and go for a simple solution. Even if that's not what you as a human would do, remeber that computers are good at carrying out stupid tasks fast.
I think what you need is a "continue" instead of a return 0.
for (i=0;i<=counter1;i++) {
for(k=0;k<=counter1;k++) {
if(b[i]==c[k]) {
continue; /* formerly return 0; */
}
for(j=0,counter2=0; j<=counter1;j++)
if (b[j] == b[i]){
counter2+=1;
}
}
Please try and see if this program can help you.
#include <stdio.h>
int main() {
unsigned n;
int arr[30];
printf("Enter a whole number: ");
scanf("%i", &n);
int f = 0;
while(n)
{
int b = n % 10;
arr[f] = b;
n /= 10;
++f;
}
for(int i=0;i<f;i++){
int count=1;
for(int j=i+1;j<=f-1;j++){
if(arr[i]==arr[j] && arr[i]!='\0'){
count++;
arr[j]='\0';
}
}
if(arr[i]!='\0'){
printf("%d is %d times.\n",arr[i],count);
}
}
}
Test
Enter a whole number: 12234445
5 is 1 times.
4 is 3 times.
3 is 1 times.
2 is 2 times.
1 is 1 times.
Here is another offering that uses only one loop to analyse the input. I made other changes which are commented.
#include <stdio.h>
int main(void)
{
int count[10] = { 0 };
int n;
int digit;
int elems = 0;
int diff = 0;
printf("Enter a whole number: ");
if(scanf("%d", &n) != 1 || n < 0) { // used %d, %i can accept octal input
puts("Please enter a positive number"); // always check result of scanf
return 1;
}
do {
elems++; // number of digits entered
digit = n % 10;
if(count[digit] == 0) { // number of different digits
diff++;
}
count[digit]++; // count occurrence of each
n /= 10;
} while(n); // do-while ensures a lone 0 works
printf("Number of digits entered: %d\n", elems);
printf("Number of different digits: %d\n", diff);
printf("Occurrence:\n");
for(n = 0; n < 10; n++) {
if(count[n]) {
printf(" %d of %d\n", count[n], n);
}
}
return 0;
}
Program session:
Enter a whole number: 82773712
Number of digits entered: 8
Number of different digits: 5
Occurrence:
1 of 1
2 of 2
1 of 3
3 of 7
1 of 8
I want user to enter 8 numbers.
If they enter less than 8 numbers, the program will exit.
What if statement should I use?
Should I put in my loop sum += i then if sum not 8 then exit?
This is what I got so far but it doesn't work out:
int main() {
int i, numb;
int sum = 0;
// the loop to enter 8 numb
printf("enter 8 numbers");
if (i=0;i<8;i++) {
scanf("%d", &numb);
sum =+i;
if (sum < 8)
exit(1);
}
return (0);
}
You want the user to enter 8 numbers and since you have not mentioned anything about the sum, I'll assume it doesn't matter what it is. Remove the inner if condition altogether and replace the outer if with a loop.
Here is the code:
for (i = 0; i < 8; i++) {
scanf("%d", &numb);
//Do whatever you want to do with the number here
Because of the way the console works you can't tell where the EOF is. You can achieve what you want by checking the separators between the numbers. If you want the numbers to be no less than 8 on the same line, you can do it this way
int main() {
int i, numb;
int sum = 0;
char separator=' ';
// the loop to enter 8 numb
printf("enter 8 numbers");
for (i = 0; i<8; i++)
{
if (separator == '\n')//enter character encountered
break;
scanf("%d%c", &numb,&separator);
}
if (i < 8)
exit(1);
return (0);
}
Here is an algorithm which does exactly what you want:
1. Set a counter to 0
2. While not end of file (EOF) do
1. Read a number
2. Increase counter by 1
3. If sum counter equals 8, return 1, else return 0
and your code repaired (since you've finally posted what you tried to do):
int main()
{
int i, numb, counter = 0;
printf("enter 8 numbers");
while(scanf("%d", &numb) != EOF)
{
counter++;
}
if (counter < 8)
{
printf("not enough numbers\n");
exit(1);
}
return (0);
}
Live demo: http://ideone.com/iiOl1A
I'm trying to figure out a homework assignment in C. The instructions state to have the user input integers in a loop until they enter a negative number, and then to output the sum of all the numbers. The second part seems pretty straight forward to me, but I can't wrap my head around the first part. How do you store a user input integer with a loop?
This is all I have so far.
int main(void)
{
int i = -1;
while(i > -1)
{
printf("Please enter a number %i. When finished, enter a negative number.", i);
scanf("%i", &i);
}
return 0;
}
int main(void)
{
int i = 0,sum = 0;
do
{
sum +=i; // use sum here if you don't want to add -ve value
printf("Please enter a number i. When finished, enter a negative number. ");
scanf("%i",&i);
//sum +=i; // use sum here if you want to add -ve value also to the sum
}
while(i > -1);
printf("Sum = %d", sum);
return 0;
}
You have assigned i = -1 and checking if i is greater than -1 which is false. So, the loop isn't executing.
You can try this.
#include<stdio.h>
int main()
{
int i=0,sum=0;
while(true)
{
scanf("%d",&i);
if(i < 0) break;
sum+=i;
}
printf("%d\n",sum);
return 0;
}
#include <iostream>
int main () {
int number = 0;
int accumulator = 0;
do {
accumulator += number;
std::cout << "Enter numbers to accumulate. Use negative number to finish: " << std::endl;
std::cin >> number;
} while (number > 0); //as you can also use -1 as the ending loop
std::cout << accumulator;
return 0;
}
AN EXTRA VERSION FOR C++ and using understandable variable names if someone needs it.