#include <stdio.h>
int main() {
int num;
int square;
int sum;
while (num) {
if (num > 0) {
scanf("%d", &num);
square = num * num;
sum = square + sum;
printf("%d \n", sum);
}
}
return 0;
I'm trying to produce the sum of squares for positive numbers, and when the first negative number is inputted, the loop ends. Result needs to be left justified by 10 spaces.
The code has undefined behavior: the first time you test the value of num, it is uninitialized. If by chance it happens to not be negative, you scan a new value and add its square to uninitialized variable sum, producing more undefined behavior, it the value input was negative, the next test fails and the loop repeats forever.
Left justifying in a 10 space width is obtained with the %-10d conversion format.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int num, square, sum = 0;
while (scanf("%d", &num) == 1 && num != 0) {
square = num * num;
sum = square + sum;
printf("%-10d\n", sum);
}
return 0;
}
If you want the number to be right justified in a 10 space width so all output values align properly, use the %10d format instead.
If you input large numbers or too many items, you will eventually exceed the range of type int. You can try and increase the range of variables square and sum by making them long long int or even as commented by PeterJ unsigned long long int, and allow for larger values to be computed:
int main(void) {
int num;
unsigned long long square, sum = 0;
while (scanf("%d", &num) == 1 && num != 0) {
square = (long long)num * num;
sum = square + sum;
printf("%21llu\n", sum);
}
return 0;
}
Note that (long long)num * num will be converted to unsigned long long that has a range at least as large in the positive values.
Using uninitialized variable leads to undefined behavior.You are using uninitialized local variable num in your while loop. num can have any value in it. If the value is smaller than 0 the loop will run forever. It will also loop for ever if the value smaller than 0 is entered using scanf.
For undefined behavior please check lines from standard
6.3.2.1 Lvalues, arrays, and function designators
If the lvalue designates an object of automatic storage duration that
could have been declared with the register storage class (never had
its address taken), and that object is uninitialized (not declared
with an initializer and no assignment to it has been performed prior
to use), the behavior is undefined.
I hope, this might help ending the loop
#include <stdio.h>
int main() {
int num = 0;
int sum = 0;
while (num >= 0) {
scanf("%d", &num);
if (num>=0) {
sum = ( num * num ) + sum;
printf(" %d\n", sum);
}
}
return 0;
}
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 trying to write this program:
Write a function digit(n, k) that returns the kth digit (from the right) in n (a positive integer). For example
digit(829, 1) returns 9
digit(829, 2) returns 2
digit(829, 3) returns 8
If k is greater than the number of digits in n, have the function return 0.
I get a warning message:
returning (int*)(int,int) from a fuction with return type int makes
integer from pointer without a cast
int digit(int a,int b);
int main (void){
int i, c;
printf("Enter the number");
printf("Enter the digit you want to check");
scanf("%d",&i);
scanf("%d",&c);
puts("\n");
printf("%d", digit(i,c));
}
int digit (int a, int b){
while(b>0)
{
int digit = a%10;
a/=10;
b--;
}
return digit;
}
What is illegal about that?
With
return digit;
you return a pointer to the function digit itself.
The variable digit is local inside the loop only.
You probably meant to have this variable be outside the loop, but then you should rename it to not confuse it with the function.
Perhaps something like
int get_digit(int number, int digit_number)
{
int one_digit = 0;
while(digit_number-- > 0)
{
one_digit = number % 10;
number /= 10;
}
return one_digit;
}
Note that I have changed the names of all symbols, hopefully they make much more sense now when their names describe what they are for.
The program takes an input, and should calculate the factorial of the number. However, after the number has been inputted there is a delay and the program stops
so far I haven't changed the code much from my initial attempt as I do not fully understand recursion and sunbroutines in C.
int calcFactorial(int n);
int input = 0, answer = 0;
int main()
{
int n = 0;
printf("Enter number:\n");
scanf("%d", &input);
answer = calcFactorial(input);
printf("The factorial of %d is %d.\n", input, answer);
system("pause");
return 0;
}
int calcFactorial(int n){
int factorial = 0;
if (n==0){
factorial = 1;
}
else{
factorial = n * calcFactorial(n-1);
printf(factorial);
}
return factorial;
}
This statement in the function calcFactorial
printf(factorial);
has undefined behaviour because the first parameter of the function printf is declared as const char * while you are supplying an object of the type int.
Remove the statement from the function.
Or if you want to get intermediate values then write
printf( "%d\n", factorial);
Also take into account that for the type int that usually has size of 4 bytes the maximum number for which you can get a valid value of the factorial is equal to 12.
You could use type unsigned long long int instead of the type int. In this case you can calculate the factorial for a number equal to 20.
Here is a demonstrative program
#include <stdio.h>
unsigned long long int calcFactorial( unsigned long long int n )
{
return n == 0 ? 1 : n * calcFactorial( n - 1 );
}
int main( void )
{
unsigned long long int input = 0, answer = 0;
printf( "Enter number: " );
scanf( "%llu", &input);
answer = calcFactorial( input );
printf( "The factorial of %llu is %llu.\n", input, answer );
}
Its output might look like
Enter number: 20
The factorial of 20 is 2432902008176640000.
The return statement in the function can be rewritten also the following way
unsigned long long int calcFactorial( unsigned long long int n )
{
return n < 2 ? 1 : n * calcFactorial( n - 1 );
}
However, after the number has been inputted there is a delay and the
program stops
As has already been pointed out by others, printf(factorial) has undefined behavior. It should be removed or it should be called properly (e.g. printf("%d\n", factorial)).
Not sure why you have system("pause") in there as it seems unnecessary.
Removing those two items from your code, I had no trouble running it and getting the correct answer for a factorial up to 12. Again, as has been pointed out by others, your function will only be valid up to 12! due to integer overflow.
Other than that, your code could be formatted better for the input, for example:
/* formats better than original */
printf("Enter number: ");
scanf("%d", &input);
printf("\n");
You can slim down your calcFactorial function as there is no need for the int factorial variable or the else clause. So you could make it look like this:
int calcFactorial(int n){
if (n == 0) return 1; //base case, 0! is 1
return n * calcFactorial(n - 1); //all other cases
}
I do not fully understand recursion and sunbroutines in C
Essentially, your function will be called over and over with n, and each time it is called we refer to that as an instantiation, and in each instantiation n is one less than it was in the previous instantiation. This will happen until the base case is reached (n == 0) then that instance will return to the instance before it, and this will happen until all instances have returned.
For simplicity sake, let's walk through calcFactorial(3). The base case is reached which is the instance that terminates further recursive calls and returns 1. In the instance before the base case was reached, n == 1 so that instance will return 1*1 since the instance before it returned 1. The instance before that was n == 2 so that instance returns 2*1. The instance before that was the first instance n == 3, so that instance returns 3*2. All instances have now returned and the result is 6 and that's what we expect for 3!.
You can learn more about recursion here
#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.
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;
}