#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.
Related
Program takes an integer input num from the keyboard and computes the sum of square of i for all I from 1 to num (inclusive).
#include <iostream>
#include <math.h>
int main()
{
int num;
int total;
printf("Please enter a number:");
scanf("%d", &num);
for (double i = 1; i <= num; i++) {
total += (i*i);
printf("%d", total);
}
}
The code above compiles correctly, but when inputting 5 it prints 15143055. Why is it doing this?
#include <iostream> is c++. #include <math> is not used. total is uninitialized. Comparing floating point values may not behave the way you want, so using a (unsigned) integer type instead as a loop counter. Loop values by convention start at 0 instead of 1 in c (you could increment i fist thing in the loop to avoid the double (i+1) but this will be optimized out anyways). Also, your loop not run for a negative value so just require unsigned values. As you sum integers the result ought to be an integer, but double would give you a larger range so I left it as such. Missing return:
#include <stdio.h>
int main() {
unsigned num;
printf("Please enter a number: ");
scanf("%u", &num);
double total = 0.0;
for (unsigned i = 0; i < num; i++) {
total += (i+1)*(i+1);
}
printf("%lf\n", total);
return 0;
}
and the resulting output:
Please enter a number: 3
14.000000
I am learning C on my own with a book and I cannot for the life of me figure out how to solve this exercise. I'm obviously looking at it in the wrong way or something. Here is an explanation below.
Listed below are some functions and the main function at the bottom. This program is compiled to generate a certain number of random numbers and determine the min and the max of the random numbers. If you copy and paste this code, you will see how it works. Anyways, an exercise asks me to go to the function "prn_random_numbers()" and change the for loop from "for (i = 1; i < k; ++i)" to for (i = 2; i <= k; ++i). This causes the first line format to print incorrectly. The exercise is to further modify the program in the body of the for loop to get the output to be formatted correctly.
To sum it up, the "prn_random_numbers()" function is written to print out 5 random numbers before moving to the next line. Hence the" i % 5" if statement. Now, for some reason, when you make the slight adjustment to the for loop, as the exercise asks above, it causes the first line to only print 4 numbers before moving to the next line. I have tried a number of things, including trying to force it to print the 5th number, but it only duplicated one of the random numbers. I even tried "i % 4" to see if it would print 4 numbers for each row, but it only prints 3 numbers for the first row instead of 4! So it always prints one less number on the first line than it is supposed to. I have n clue why it is doing that and the book does not give an exercise. Do you have any idea?
Bear with me if you think this is a stupid question. I am just learning on my own and I want to make sure I have a good foundation and understand everything as I learn it, before moving forward. I appreciate any help or advice!
prn_random_numbers(k) /* print k random numbers */
int k;
{
int i, r, smallest, biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 1; i < k; ++i)
{
if (i % 5 == 0)
printf("\n");
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main()
{
int n;
printf("Some random numbers are to be printed.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
while (n < 1)
{
printf("ERROR! Please enter a positive integer.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
}
prn_random_numbers(n);
return (EXIT_SUCCESS);
}
the following proposed code:
properly initializes the random number generator
cleanly compiles
properly checks for and handles errors
performs the desired functionality
avoids having to list instructions twice
follows the axiom: Only one statement per line and (at most) one variable declaration per statement.
does not use undefined functions like: max() and min()
and now the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void prn_random_numbers(int k)
{
int count = 1;
int r;
int smallest;
int biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for ( int i = 2; i <= k; i++, count++)
{
if (count % 5 == 0)
{
count = 0;
printf("\n");
}
r = rand();
smallest = (r < smallest)? r : smallest;
biggest = (r > biggest)? r : biggest;
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main( void )
{
int n;
srand( (unsigned)time( NULL ) );
do
{
printf("Please enter a positive integer, greater than 0.\n");
printf("How many would you like to see? ");
if( scanf("%d", &n) != 1 )
{
fprintf( stderr, "scanf for number of random numbers failed\n" );
exit( EXIT_FAILURE );
}
} while( n < 1 );
prn_random_numbers(n);
// in modern C, if the returned value from `main()` is 0 then no `return 0;` statement needed
}
a typical run, no input problems is:
Please enter a positive integer, greater than 0.
How many would you like to see? 20
98697066 2110217332 1247184349 421403769 1643589269
1440322693 985220171 1915371488 1920726601 1637143133
2070012356 541419813 1708523311 1237437366 1058236022
926434075 1422865093 2113527574 626328197 1618571881
20 random numbers printed.
Minimum: 98697066
Maximum: 2113527574
Try to use a debugger to solve your problem, it's easy to use and really helpfull :)
SOLUTION:
Your i variable don't count the number of numbers because it is initialize at 1 (in the for statement), so you need to declare a new variable to count properly.
If you have still a problem:
void prn_random_numbers(int k)
{
int count = 1;
int i, r, smallest, biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 2; i <= k; i++, count++) {
if (count % 5 == 0) {
count = 0;
printf("\n");
}
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.
#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;
}
it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr ยง6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}