I have written a c code to generate random numbers(each time generate a different set of random numbers) and need to ask the user if want to generate another random number. If the user reply yes, the program need to generate another random number; if the user replies No, the program needs to calculate the total and average of the random numbers.
My problem is I don't know how to store the random number and there is a problem with my loops.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
main()
{
int sum=0, i, num[100], arr[100];
float avg;
char choice;
srand(time(0));
for(i=0; i<100; i++)
{
arr[i] = rand();
printf("Random number generated: %d", arr[i]);
fflush(stdin);
printf("\nGenerate another random number(y/n)? ");
scanf("%c", &choice);
if(choice == 'n' || choice == 'N')
{
sum += arr[i];
avg = sum / i;
printf("\n::TOTAL : %d", sum);
printf("\n::AVERAGE : %.2f", avg);
}
}
system("PAUSE");
}
The correct output should be like this:
Correct output
There are several issues with your code:
Add a break at the end of your "No"-condition to get out of the loop in that case.
Accumulate your sum (for the average) outside the "No"-condition.
To store you could simply run another loop for(int j=0; j<=i; ++j) printf("%d\t", arr[j]); and copy the output from the command line - or get yourself familiar with file IO.
By the way: sum is likely to overflow if you accumulate several numbers of the same data type.
Related
i am new to programing, i want to know that how we can find the odd digits in a number.
the condition in this program is we should only use concept of arrays.I tried a code for this as follows:
#include <stdio.h>
int main()
{
int A[50],i,x,y,n,sum=0;
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
for(i=0;i<n;i++){
x=A[i]%10;
if(x%2!=0)
sum=sum+x;
A[i]=A[i]/10;
printf("the sum of odd numbers is %d\n",sum);
}
return 0;
}
but in this the code is checking for only one digit of the first number in the loop and then next time it is going to check the digit of second number.
so, i need to write a code to check all digits in the number and then it goes to next number and check all digits and should continue the same process in the loop.So, for this how should i modify my code?
You were missing a loop that would iterate through every digit of A[i] - the inner while loop below,
#include <stdio.h>
int main()
{
int A[50], i, x, y, n, sum=0;
printf("How many numbers will you input?\n");
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0; i<n; i++) {
scanf("%d",&A[i]);
}
for(i=0; i<n; i++) {
sum = 0;
while (A[i] > 0) {
x = A[i]%10;
if(x%2 != 0) {
sum = sum + x;
}
A[i] = A[i]/10;
}
printf("the sum of odd numbers is %d\n",sum);
}
return 0;
}
The exact algorithm for iterating through each digit in a nice form can be found in this post - although for a different language. Here, apart from the while loop, you also need to reset the sum each time unless you want a cumulative sum over all provided numbers.
Note that I changed the formatting a bit - more space, extra braces, and a message about what you're prompting the user to input.
int temp;
int sum = 0;
temp = number;
do {
lastDigit = temp % 10;
temp = temp / 10;
sum += (lastDigit %2 != 0) ? lastDigit : 0;
} while(temp > 0);
i am really stuck with this been trying to solve it for quite a time now.
i have to write a program where i should input 5 numbers between 1 to 10 and then calculate the average, USING ONLY WHILE LOOP, but it does not have to exit when the number does not meet the requirement. then, i have to write a variation of the same code but this time you can enter all the numbers you want, and when 0 is entered it has to calculate the average and exit
this is where i have gotten so far
#include <stdio.h>
int main(void)
{
int n, i = 1;
float add;
float avg;
do
{
printf("enter the number %d:\n", i++);
scanf("%d", &n);
add = add + n;
} while(n > 0 && n < 11);
avg= (add / 5);
printf("%.1f", avg);
return 0;
}
it will keep asking for numbers after 5 have been entered. and the average is not right anyways
First, you're using nas your while condition variable, but also as the variable to scan the input. If I start your program by scanning 20, for example, your while loop will exit on the first interaction. Use your i variable instead and also increment it every time your loop executes.
do{
...
}while(i <= 5);
Second, if you want only numbers between 1 and 10, then you should write a condition for it. For example:
printf("enter the number %d:\n", i); //do not increment it here!
scanf("%d",&n); //assuming "n" as your variable to scan
if(n > 0 && n < 11){
add += n;
i++; //increment it here instead!
}
Third, initialize your variables in order to not get thrash values
float add = 0;
float avg = 0;
int i = 1;
Finally, assign your result (not mandatory, but since you're using it I'll keep it):
avg = add/5.0f
and display:
printf("%.1f", avg);
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
average=(sum/20);
printf("Average = %.2f", average);
if (ray[i] < average)
{
printf("The followiing values are less than the average: %d", ray[i]);
}
system("pause");
}
The code runs fine and gives the correct average of the integers entered but the values that are less than the average comes out as -858993460
You are trying to print out ray[i], but i is currently 20which is outside the index of your array. Did you mean to copy your for loop around that if statement?
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d: ",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
average=(sum/20);
if (ray[i] < average)
{
printf("The followiing values are less than the average: %d", ray[i]);
}
}
printf("Average = %.2f", average);
system("pause");
}
This gives the "the following integers are below the average" part after each value that is lower than the then average, but I need it to show the values which are below the average together at the end.
The out-of-index issue
As the others have already pointed, your index is out of bounds.
That happens because you've iterated for (i=0; i < 20; i++), which means once you left the for statement you were at i == 20. Your array was allocated with 20 positions, so you can access it from index 0 to 19. The awkward value you get is given because you are accessing "trash", or in other words, invalid positions with unpredictable (or almost) values.
The algorithm issue
Ok, once you got that index thing right, you still need an algorithm that displays the numbers that are lower than the average. You can't just copy your if statement into the loop because you only know the true average value once you've iterated through all of the values (which you are doing just fine).
So what you want is another loop that iterates throughout the array and that if statement inside of it (well, there are other ways to do it without running all of the values again, like sorting the array)
So, this is the algorithm I'll propose you
#include <stdio.h>
#include <stdlib.h>
#define array_size 20
void main()
{
int i;
int ray[array_size];
int sum=0;
float average;
for (i=0; i<array_size; i++)
{
printf("Enter integer #%d: ",i+1);
scanf ("%d", &ray[i]);
sum += ray[i];
}
average=(sum/(float)array_size);
printf("Average = %.2f\n", average);
printf("The following values are less than the average: ");
for (i = 0; i < array_size; i++)
{
if (ray[i] < average)
{
printf("%d ", ray[i]);
}
}
system("pause");
}
This Part in Your Code:
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
//Now i = 20,that is why it left loop
average=(sum/20);
printf("Average = %.2f", average);
if (ray[i] < average) //You are saying if ray[20]<average
{
printf("The following values are less than the average: %d", ray[i]);
}
Now ray[20] is outside the scope because there are 20 elements and array index starts from 0 and goes on to 19, so ray[20] is out of bound access.
I highly recommend you to see this question for better understaning How dangerous is it to access an array out of bounds?.
Secondly You want to print all ray[i] where ray[i] < average so you should run a loop like
printf("The following values are less than the average:");
for(i = 0; i<20; i++) // i starts from 0 and increase with run of loop
// and loop stops when i>19 so you are not
// accessing forbidden area.
{
if (ray[i] < average){ //check if ray[i] is less than average
printf("%d\n", ray[i])
}
}
All That makes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
average=(sum/20);
printf("Average = %.2f", average);
printf("The following values are less than the average:");
for(i = 0; i<20; i++) // i starts from 0 and increase with run of loop
// and loop stops when i>19 so you are not
// accessing forbidden area.
{
if (ray[i] < average){ //check if ray[i] is less than average
printf("%d\n", ray[i]);
}
}
system("pause");
}
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i , n , sum=0, rem;
clrscr();
for(i=1;i<=1000;i++)
{
while(i!=0)
{
rem = i%10;
sum = sum + pow(rem,3);
i = i / 10;
}
if(i == sum)
printf("\n %d", i);
}
getch();
}
I tried the above code for printing Armstrong Numbers upto 1000 . The output that I got was a list of zeros. I am not able to find the error in the code. Thanks in advance :)
You should keep a copy of i, so that it could be kept for comparison with the sum variable.
As of now, you compare sum and i, at every step when i has become 0.
You should use a temp variable to store value of i(before performing i/=10).
Also, you can't keep i in the while-loop as it would always be 0, and hence post increment will have no effect on it. You should need another temporary variable, say div.
And, you should finally print temp.
Also, an Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.
So, for 1000, you need to caclculate the 4th power.
int temp,div;
for(i=1;i<=1000;i++)
{
temp = i;
div = i;
while(div!=0)
{
rem = div%10;
sum = sum + pow(rem,3);
div = div / 10;
}
if(temp == sum)
printf("\n %d", temp);
}
NOTE :- Probably you're using Turbo C compiler(check that header <conio.h>), which you shouldn't(you should avoid it). You should use GCC(on Linux system), CodeBlocks IDE(on Windows).
You can also use this code to print Armstrong number in given range.
#include<stdio.h>
int main()
{
int num,r,sum,temp;
int min,max;
printf("Enter the minimum range: ");
scanf("%d",&min);
printf("Enter the maximum range: ");
scanf("%d",&max);
printf("Armstrong numbers in given range are: ");
for(num=min;num<=max;num++)
{
temp=num;
sum = 0;
while(temp!=0)
{
r=temp%10;
temp=temp/10;
sum=sum+(r*r*r);
}
if(sum==num)
printf("%d ",num);
}
return 0;
}
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?