input and Output with math in C - c

Example
Input: 12345
Output: (1+2+3+4+5=15)--> (1+5=6) Output is 6
(It shoud be only one number (1-9)
Please tell me how to make sure that when you enter a number, for example 12345, the output is equal to the sum 1 + 2 + 3 + 4 + 5 = 15 and then 1 + 5 = 6. C language. Thank you very much for your answer!
#include <stdio.h>
int main(){
int isicc;
scanf ("%d", &isicc);
while (isicc>0){
int d = isicc%10;
isicc=isicc /10;
}
printf ("Your number ", d);
}

After the command
scanf ("%d", &isicc);
You can use this code to get the sum of digits of the number:
int sum_digits = 0;
while (isicc > 0) {
sum_digits += isicc % 10;
isicc = isicc / 10;
}
isicc = sum_digits;
Now, you just need to repeat this process in another loop , that will continue as long as isicc is bigger than 9.

#include <stlib.h>
#include <stdio.h>
int main(){
int isicc;
scanf ("%d", &isicc);
isicc = abs(isicc);
printf ("Your number %d\n", isicc?isicc%9?isicc%9:9:0 );
}

Try this program, it will add digits and print sum
#include <stdio.h>
int main ()
{
int num,n,sum=0;
printf ("Enter number:");
scanf (" %d",&num);
while (num!=0){
n=num%10;
sum += n;
num = num/10;
}
printf ("%d",sum);
return 0;
}

Related

Why did I get different answers in vscode?

My code:
#include <stdio.h>
#include <math.h>
int main (void)
{
int n = 0;
int sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
for (int power = 1; power <= n; power++)
{
printf("%d %s ", (int)pow(10, power) - 1, power == n ? "=" : "+");
sum += (int)pow(10, power) - 1;
}
printf ("%d", sum);
return 0;
}
Output in Vs Code with gcc:
Enter a number: 5
9 + 98 + 999 + 9998 + 99999 = 111103
Output in online compilers:
Enter a number: 5
9 + 99 + 999 + 9999 + 99999 = 111105
My question: Why? is this happening?
Possibly an issue with pow and its implementation, perhaps due to different platform or compilers.
Instead of using pow which relies on floating point arithmetic and leads to compounding rounding errors (and possibly contains bugs), why not use simple multiplication? If you start the loop with 10, then you could multiply that by 10 each iteration to get the result you want.
Perhaps something like this:
unsigned sum = 0;
for (unsigned power = 0, value = 10; power < n; ++power, value *= 10)
{
sum += value - 1;
}
[Printing left out]
I just use the function "round" which returns the integer rounding closest to the value specified in parameter
#include <stdio.h>
#include <math.h>
int main (void)
{
int n = 0;
int sum=0;
printf("Enter a number: ");
scanf("%d", &n);
for (int power = 1; power <= n; power++)
{
sum += (int)round (pow(10, power)) - 1;
}
printf ("%d", sum);
return 0;
}

C Program won't read input from STDIN

I'm writing a basic statistics program as my first in pure C, and for the life of me cannot figure out this one problem. When taking input manually from the command line, it works perfectly. However, when putting in those numbers from an input file, it doesn't read any of them. Here's the source code:
statistics.c:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]){
// Create global variables, introduce program
int minimum = INT_MAX;
int maximum = INT_MIN;
int i = 0;
int count = 0;
double total = 0.0;
printf("%s\n", "Program1");
printf("%s\n", "Enter nums (0 terminates):");
scanf("%d", &i); // Scan in number
while (i!=0)
{
printf("%d\n", i); // Print the number just entered
count++; // Increment counter
total += i; // Add to total
if (i > max) {max = i;} // Check for maximum
if (i < min) {min = i;} // Check for minimum
scanf("%d", &i); // Read in the next number
}
printf("%s%d\n", "Nums entered: ", counter);
printf("%s%d%s%d\n", "range: ", min, ", ", max);
printf("%s%f\n", "mean: ", total/counter);
return EXIT_SUCCESS;
}
input.txt:
2 3 5 0
When I run ./program in the terminal, and enter those numbers manually, it gives me the expected output. But when I run ./program < input.txt, nothing happens and it gets stuck so that I have to use ^C to kill the process. Any thoughts??
The original code posted defined variables minimum, maximum, count and used variables min, max, counter respectively. Since the original code doesn't compile because of that, all we can be sure of is that your running code was not created from the source originally shown. Please do not post an approximation to the code that is causing you trouble — make sure that the code you post causes the trouble you describe (it compiles; it runs; it produces the claimed output, at least on your machine).
Here's a spell-corrected version of the code:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int min = INT_MAX;
int max = INT_MIN;
int i = 0;
int count = 0;
double total = 0.0;
printf("%s\n", "Program1");
printf("%s\n", "Enter nums (0 terminates):");
scanf("%d", &i);
while (i!=0)
{
printf("%d\n", i);
count++;
total += i;
if (i > max) {max = i;}
if (i < min) {min = i;}
scanf("%d", &i);
}
printf("%s%d\n", "Nums entered: ", count);
printf("%s%d%s%d\n", "range: ", min, ", ", max);
printf("%s%f\n", "mean: ", total/count);
return EXIT_SUCCESS;
}
When run on the file input.txt containing:
2 3 5 0
it generates the output:
Program1
Enter nums (0 terminates):
2
3
5
Nums entered: 3
range: 2, 5
mean: 3.333333
Consequently, I cannot reproduce your claimed problem, but that may be because I can't see your real code, or perhaps not your real data. If I omit the 0 from the file, then I get an infinite loop with 5 being printed each time.
Here's an alternative version with more robust input handling; it checks the return value from scanf() and avoids repeating the call, too.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int min = INT_MAX;
int max = INT_MIN;
int i = 0;
int count = 0;
double total = 0.0;
printf("%s\n", "Program1");
printf("%s\n", "Enter nums (0 terminates):");
while (scanf("%d", &i) == 1 && i != 0)
{
printf("%d\n", i);
count++;
total += i;
if (i > max)
max = i;
if (i < min)
min = i;
}
printf("Nums entered: %d\n", count);
printf("Range: %d to %d\n", min, max);
printf("Mean: %f\n", total / count);
return EXIT_SUCCESS;
}
This code works correctly on the data file without a 0 as the last number.

Calculating the average of user inputs in c

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.

Write a program in C that will take a base and n digits and will output a decimal number represented by those digits

I have to write a program in C that will take a base b from the user (assuming b is between 2 and 10), a natural number n and then n numbers that represent the digits of some number m in base b. The program should print out what decimal number m was input. For example, if you put b=5 and n=4 and then the numbers 3 ,4, 2 and 1 the program should output 486 because m=3*5^3+4*5^2+2*5^1+1*5^0=486
Note: You can assume that the digits will be the numbers between 0 and b-1.
So here's what I've done:
#include<stdio.h>
#include<math.h>
int main(void) {
int x,n,b,k=0,num=0,i,j;
scanf("%d", &b);
scanf("%d", &n);
for(i=1; i<=n; i++) {
scanf("%d", &x);
for(j=1; j<b; j++){
if(j>k){
num=num+x*(pow(b,n-j));
k=j;
break;
}
}
}
printf("m=%d", num);
return 0;
}
Can you tell me why this doesn't work for the numbers given in the example above? It outputs 485 instead of 486, while if I take for example b=7, n=3 and then numbers 5, 6 and 1, I get the correct solution m=288.
I suggest checking the return value of scanf(), Something like this is the right idea:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int
main(int argc, char *argv[]) {
int base, n, i, x, sum = 0, power;
printf("Enter base: ");
if (scanf("%d", &base) != 1) {
printf("Invalid base.\n");
exit(EXIT_FAILURE);
}
printf("Enter n: ");
if (scanf("%d", &n) != 1) {
printf("Invalid n.\n");
exit(EXIT_FAILURE);
}
power = n-1;
printf("Enter numbers: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &x) != 1) {
printf("Invalid value.\n");
exit(EXIT_FAILURE);
}
sum += x * pow(base, power);
power--;
}
printf("Sum = %d\n", sum);
return 0;
}
Input:
Enter base: 5
Enter n: 4
Enter numbers: 3 4 2 1
Output:
Sum = 486
You need some small change to your logic.
#include <stdio.h>
#include <math.h>
int main(void) {
int x, n, b, num = 0, i;
scanf("%d", &b);
scanf("%d", &n);
for (i = 1; i <= n; i++) {
scanf("%d", &x);
num += x * pow(b, n - i);
}
printf("m=%d", num);
return 0;
}
Test
gcc -Wall main.c -lm
$ ./a.out
5
4
3
4
2
1
m=486
Test 2
./a.out
7
3
5
6
1
m=288
OK, so given a binary number, we can output a decimal number very easily. Just printf("%d%\n", x);
Next job is to convert a number given digits and base into a binary (machine representation) number.
int basetointeger(const char *digits, int b)
{
assert(b >= 2 && b <= 10);
// code here
return answer;
}
Now hook it all up to main
int main(void)
{
int x;
int base;
char digits[64]; // give more digits than we need, we're not worrying about oveflow yet
/* enter base *?
code here
/* enter digits */
code here
x = basetointger(digits, base);
printf("Number in decimal is %d\n, x);
}

Creating table for Fibonacci Sequence

Thank you in advance. I appreciate any and all feedback. I am new to programming and i am working on an assignment that prints the Fibonacci Sequence based on how many numbers the user asks for. I have most of the code complete, but there is one remaining piece I am having difficulty with. I would like my output in a table format, but something is off with my code and I am not getting all of the data I would like in my output. In grey is my code, my output, and my desired output.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n;
int sequence = 1;
int a = 0, b = 1, c = 0;
printf("How many Fibonacci numbers would you like to print?: ");
scanf("%d",&n);
printf("\n n\t\t Fibonacci Numbers\n");
printf(" %d \t\t\t%d\n \t\t\t%d\n ", sequence, a, b);
for (i=0; i <= (n - 3); i++)
{
c = a + b;
a = b;
b = c;
sequence++;
printf("\t\t\t%d\n ", c);
}
return 0;
}
Here is my output:
How many Fibonacci numbers would you like to print?: 8
n Fibonacci Numbers
1 0
1
1
2
3
5
8
13
Here is my desired output:
How many Fibonacci numbers would you like to print?: 8
n Fibonacci Numbers
1 0
2 1
3 1
4 2
5 3
6 5
7 8
8 13
I am not getting all of the data
That's because you are not printing the sequence in printf() of the for loop.
printf("\t\t\t%d\n ", c);
and even before 2nd number before for loop
printf(" %d \t\t\t%d\n \t\t\t%d\n ", sequence, a, b);
try making the below changes to your code :
printf(" %d \t\t\t%d\n %d\t\t\t%d\n ", sequence, a, sequence+1, b);
sequence++; //as you've printed 2 values already in above printf
for (i=0; i <= (n - 3); i++)
{
c = a + b;
a = b;
b = c;
printf("%d\t\t\t%d\n ",++sequence, c);
//or do sequence++ before printf as you did and just use sequence in printf
}
sample input : 5
sample output :
How many Fibonacci numbers would you like to print?: 5
n Fibonacci Numbers
1 0
2 1
3 1
4 2
5 3
Edit : you can do it using functions this way... it's nearly the same thing :)
#include <stdio.h>
void fib(int n)
{
int i,sequence=0,a=0,b=1,c=0;
printf("\n n\t\t Fibonacci Numbers\n");
printf(" %d \t\t\t%d\n %d\t\t\t%d\n ", sequence, a, sequence+1, b);
sequence++;
for (i=0; i <= (n - 2); i++)
{
c = a + b;
a = b;
b = c;
printf("%d\t\t\t%d\n ",++sequence, c);
}
}
int main()
{
int n;
printf("How many Fibonacci numbers would you like to print?: ");
scanf("%d",&n);
fib(n);
return 0;
}
You forgot to print sequence in the for loop. Print sequence along with c in the for loop after giving proper number of \t!
This would work, also it is better to properly indentate your code:
int main() {
int i, n;
int sequence = 1;
int a = 0, b = 1, c = 0;
printf("How many Fibonacci numbers would you like to print?: ");
scanf("%d",&n);
printf("\n n\t\tFibonacci Numbers\n");
printf(" %d\t\t\t%d\n", sequence, a);
printf(" %d\t\t\t%d\n", ++sequence, b); // <- and you can use pre increment operator like this for your purpose
for (i=0; i <= (n - 3); i++) {
c = a + b;
a = b;
b = c;
sequence++;
printf(" %d\t\t\t%d\n",sequence, c);
}
return 0;
}
Output:
How many Fibonacci numbers would you like to print?: 4
n Fibonacci Numbers
1 0
2 1
3 1
4 2

Resources