C Programming While Loop Assignment - c

Question: Take n as input. Then take n numbers as input and print the summation of those n numbers. But this time output as the format below.
Example:
Input:
4
1 5 3 -4
output 1 + 5 + 3 – 4 = 5
I got the output value correctly, but I do not know how am I going to show the actual summation sequence, especially in one line....
My Code:
main ()
{
int n,m,cnt=0,sum=0;
printf("Input: ");
scanf("%d", &n);
while(cnt<n)
{
scanf("%d\b", &m);
sum=sum+m;
cnt=cnt+1;
if(m>0 && m!=n)
{
printf("\b+",m);
}
else if (m<0)
{
printf("%d",m);
}
}
printf("=%d\n\n",sum);
}

Here's a sample solution that I came up with:
#include <stdio.h>
int main() {
int n = 0,
count = 0,
sum = 0;
int first = 1;
printf("How many numbers do you wish to sum? " );
scanf("%d", &n);
while (count < n) {
int m;
scanf("%d\b", &m);
if (!first) {
if (m < 0) {
printf("- %d ", -m);
} else {
printf("+ %d ", m);
}
} else {
first = !first;
printf("%d ", m);
}
sum += m;
count++;
}
printf("= %d\n\n", sum);
return 0;
}
Here's a sample execution:
$ gcc stackoverflow.c -o stackoverflow
$ ./stackoverflow
How many numbers do you wish to sum? 5
1 -2 -3 4 10 -40
1 - 2 - 3 + 4 + 10 = 10

If the summation sequence is to be printed after the input, the problem could be solved by using a dynamically allocated array int[] of length n in which the input is read. After the input is read, the actual summation can be done and the summands can be printed, as they have been stored in the array. The dynamic allocation can be done with the malloc function; you would also have to use the free function after the summation.

Catch!:)
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
unsigned int n = 0;
printf( "Enter number of items (0-exit): " );
scanf( "%u", &n );
if ( n != 0 )
{
int items[n];
printf( "Enter %u numbers: ", n );
unsigned int i = 0;
while ( i < n && scanf( "%d", &items[i] ) == 1 ) ++i;
int sum = 0;
_Bool first = 1;
n = i;
for ( i = 0; i < n; i++ )
{
sum += items[i];
if ( !first || items[i] < 0 )
{
printf( "%c ", items[i] < 0 ? '-' : '+' );
}
if ( first ) first = 0;
printf( "%u ", ( unsigned int )abs( items[i] ) );
}
printf( "= %d\n", sum );
}
return 0;
}
The output might look like
Enter number of items (0-exit): 4
Enter 4 numbers: 1 5 3 -4
1 + 5 + 3 - 4 = 5

#include <stdio.h>
int main()
{
int num;
int answer=0;
do
{
printf("\nEnter the number(s) to be added: (enter 0 to quit) ");
scanf("%d", &num);
answer=answer + num;
}
while (num!=0);
printf("Answer is %d", answer);
return 0;
}
Advantage of above approach is that you don't require an array and don't have to declare the no. of values that you are adding. Sort of like adding using a calculator where you simply press the "=" button when you are done.

Related

Count times digits appear in a number C

I am trying to make a code in C that takes a number as an input, counts how many times 0-9 appears in the given number.
The code as nooby as it might is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,dig,dat[9],mod;
printf("Give a number: ");
scanf("%d",&num);
mod = num % 10;
while(mod != 0)
{
if(mod > 1)
{
dig = mod / 10;
while(dig >= 0 )
{
++dat[dig];
}
}
else if(mod =1)
{
dig = mod/1;
while(dig >= 0 )
{
++dat[dig];
}
}
--mod;
}
printf("%d appears %d\n",dig,dat[dig]);
return 0;
}
Thanks in advance
Nothing really works, i dont even get any response from printf.
#include <stdio.h>
int main(void) {
int n = 12334268;
int digits[10] = {0};
while(n)
{
++digits[n%10];
n/=10;
}
for(int i=0; i<10; ++i)
{
if (digits[i])
{
printf("Digit %d appears %d times\n", i, digits[i]);
}
}
return 0;
}
Output
Success #stdin #stdout 0s 5512KB
Digit 1 appears 1 times
Digit 2 appears 2 times
Digit 3 appears 2 times
Digit 4 appears 1 times
Digit 6 appears 1 times
Digit 8 appears 1 times
For starters the array dat shall have 10 elements because there are 10 digits 0-9.
dat[10],
And moreover you are using the uninitialized array
++dat[dig];
If the entered number is divisible by 10 then the while loop is skipped
mod = num % 10;
while(mod != 0)
{
//...
So the code does not make sense.
Pay attention to that you should deal with unsigned integers. Otherwise the program shall take into account the sign of the entered number.
Also the user can enter 0 that is a valid number containing one digit 0.
The program can look the following way.
#include <stdio.h>
int main( void )
{
enum { N = 10 };
unsigned int digits[N] = { 0 };
unsigned int num;
printf( "Give a number: " );
if ( scanf( "%u",&num ) == 1 )
{
const unsigned int Base = 10;
do
{
++digits[num % Base];
} while ( num /= Base );
puts( "The number contains the following digits:" );
for ( unsigned int i = 0, j = 0; i < N; i++ )
{
if ( digits[i] != 0 )
{
if ( j != 0 ) printf( ", " );
printf( "%u: %u", i, digits[i] );
j = 1;
}
}
}
}

How to get sequence of numbers and then print the last 5?

Im trying to make a program that will get sequence from the user that end with 0, and then i want to print the last 5 numbers (not including the 0).
I can assume that the user will input all the numbers in one line and will end it with 0.
I wrote that code but something is wrong with it, I think its something about the scanf line.
Input:
1 6 9 5 2 1 4 3 0
Output: no output
#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;
printf("please enter more than %d number and than enter 0: \n", N);
last_input = 0;
while (last_input<N) {
scanf(" %d", &j);
if (j == '0') {
last_input = N;
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}
printf("The last %d numbers u entered are:\n", N);
for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);
}
for (j=0; j<last_input; ++j) {
printf(" %d", arr[j]);
}
return 0;
}
This comparison
if (j == '0') {
does not make a sense because the user will try to enter the integer value 0 instead of the value (for example ASCII 30h or EBCDIC F0h) for the character '0'.
You need to write at least
if (j == 0) {
Due to these sub-statements of the if statement
last_input = N;
break;
this for loop
for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);
}
is never executed and does not make a sense.
This statement
last_input=-1;
results in breaking the order of the N last elements in its output. And moreover the result value of the variable last_input will be incorrect.
You need to move elements of the array one position left. For this purpose you can use a loop of standard C function memmove.
The program can look the following way.
#include <stdio.h>
#include <string.h>
int main( void )
{
enum { N = 5 };
int arr[N];
printf( "Please enter at least not less than %d numbers (0 - stop): ", N );
size_t count = 0;
for (int num; scanf( "%d", &num ) == 1 && num != 0; )
{
if (count != N)
{
arr[count++] = num;
}
else
{
memmove( arr, arr + 1, ( N - 1 ) * sizeof( int ) );
arr[N - 1] = num;
}
}
if (count != 0)
{
printf( "The last %zu numbers u entered are: ", count );
for (size_t i = 0; i < count; i++)
{
printf( "%d ", arr[i] );
}
putchar( '\n' );
}
else
{
puts( "There are no entered numbers." );
}
}
The program output might look like
Please enter at least not less than 5 numbers (0 - stop): 1 2 3 4 5 6 7 8 9 0
The last 5 numbers u entered are: 5 6 7 8 9
I made some changes based on ur comments and now its work fine!
#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;
printf("please enter more than %d number and than enter 0: \n", N);
last_input = 0;
while (last_input<N) {
scanf("%d", &j);
if (j == 0) {
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}
printf("The last %d numbers u entered are:\n", N);
for (j=(last_input); j<N; ++j) {
printf("%d ", arr[j]);
}
for (j=0; j<last_input; ++j) {
printf("%d ", arr[j]);
}
return 0;
}
thank u guys <3.

How to separate the number with spaces in between using while loop and power function

How do I separate number with 5 spaces in between the numbers without reversing the number using while loop and pow function?
User can enter any number of numbers. It is not restricted to example just 3.
User will be asked to input n-number of numbers.
User will be asked to enter the numbers.
Print out the numbers without using arrays but only basic while loop and pow function.
Hope to get some help, thank you!
I've tried but below is my result
Please enter number of digit: 3
Please enter the 3 digit number: 123
Output:
3 2 1
Expected output:
1 2 3
int num;
int digit;
// int final;
int n;
int counter;
printf("Number of digits: ");
scanf("%d", &num);
printf("\nDigit number: ", num);
scanf("%d", &n);
counter = 0;
while (counter < n) {
digit = n % 10;
n = n / 10;
counter++;
printf("%d ", digit);
}
Use the %n specifier to confirm that the required number of digits are entered. With an int this may be about 10 digits.
Since the first effort produced a reversed result, reverse the number twice to get the desired output.
Pay attention to inputs such as 1000 and 0001 to print the correct leading and trailing zeros.
Check the return of scanf, an input of abc can't be parsed as an integer and scanf will return zero. scanf returns the number of items scanned.
#include <stdio.h>
int main( void) {
int num = 0;
int digits = 0;
int digit = 0;
int zeros = 0;
int temp = 0;
int reverse = 0;
int counter = 0;
int start = 0;
int stop = 0;
printf("Number of digits: ");
fflush ( stdout);
if ( 1 == scanf("%d", &digits)) {
printf("\nDigit number: ");
fflush ( stdout);
if ( 1 == scanf(" %n%d%n", &start, &num, &stop)) {
if ( digits != stop - start) {
fprintf ( stderr, "enter %d digit number\n", digits);
return 0;
}
counter = 0;
temp = num;
zeros = digits;
while (temp) {//reverse number
reverse *= 10;
reverse += temp % 10;
temp = temp / 10;
zeros--;//deduct for leading zeros
}
counter = 0;
while ( zeros) {//print leading zeros
counter++;
zeros--;
printf ( "0 ");
}
while (counter < digits) {//reverse again and print
digit = reverse % 10;
reverse = reverse / 10;
counter++;
printf("%d ", digit);
}
printf("\n");
}
else {
fprintf ( stderr, "could not parse number\n");
return 0;
}
}
else {
fprintf ( stderr, "could not parse number of digits\n");
return 0;
}
return 0;
}
Print out the numbers without using arrays but only basic while loop and pow function.
This specifies use of pow(), a floating point function, to solve an integer problem - not a good strategy to learn.
Further, "%d" is an array so "without using arrays" is unclear.
The following meets the restrictions imposed.
void foo(int count, int i) {
if (count > 1) {
foo(count - 1, i / 10);
for (int space = 0; space < 5; space++) {
putchar(' ');
}
}
putchar(i%10 + '0');
}
int main() {
foo(3, 123);
}
Output:
1 2 3

Simple C program is not storing the correct value of the input taken in the variable

Can anybody tell me where why the correct value of input is not being stored in this program?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, sum=0;
printf("Enter the number: ");
while(num!=0)
{
sum = sum+num;
scanf("%d", &num);
}
printf("Answerr = %d", sum);
return 0;
}
Here's the output:
Enter the number: 2
0
Sum = 10
Better do:
num= 0;
do
{
scanf("%d", &num);
sum = sum+num;
} while(num!=0);
Note the initialization of num is still needed as scanf could fail which would not affect num.
You cannot know what exactly this part will do :
while (num != 0)
{
sum = sum + num;
scanf("%d", &num);
}
because num is not initialized, so you are adding to sum a value which you do not know. Change it to :
while(num != 0)
{
scanf("%d", &num);
sum = sum + num;
}
so that num has a value when you add it, and also initialize num to something different than 0, for example :
int num = 2;
so that your while loop is executed at least one (in other words, so that you get the chance to read num).
A better approach would be to use a do-while loop like this :
int num = 0;
do
{
scanf("%d", &num);
sum = sum + num;
}while (num != 0);
so as to be sure that your loop will be executed at least once. Even with this approach you should still initialize num in case scanf fails (and therefore num does not get a value).
In order to check the return value of scanf, use this piece of code :
if ( scanf("%d", &num) == 1)
sum = sum + num;
Change your code to:
int main()
{
int num = 0, sum = 0;
printf("Enter the number: ");
do
{
scanf_s("%d", &num);
sum = sum + num;
} while (num != 0);
printf("Answer = %d", sum);
return 0;
}
I replaced the whileloop with a do while one. You've to initialize sum, otherwise you'll work with an undefined value in your first run ( if working with a while loop).
you are adding value of num before reading it
do like this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, sum=0;
printf("Enter the number: ");
do{
scanf("%d", &num);
sum = sum+num;
}
while(num!=0);
printf("Answerr = %d", sum);
return 0;
}
The variable num was not initialized. As result the loop has undefined behavior. Also you should check whether the input was valid before adding values. Take into account that neither declaration from the header <stdlib.h> is used. So you may remove the header.
The program can look the following way
#include <stdio.h>
int main( void )
{
long long int sum = 0;
while ( 1 )
{
int num;
printf( "Enter number (0 - exit): " );
if ( scanf( "%d", &num) != 1 || num == 0 ) break;
sum += num;
}
printf( "\nAnswer = %lld\n", sum );
return 0;
}
Or you could place the prompt before the loop as for example
#include <stdio.h>
int main( void )
{
long long int sum = 0;
printf( "Enter numbers (0 - exit): " );
while ( 1 )
{
int num;
if ( scanf( "%d", &num) != 1 || num == 0 ) break;
sum += num;
}
printf( "\nAnswer = %lld\n", sum );
return 0;
}
And according to the C Standard function main without parameters shall be declared like
int main( void )

How do I stop scanf loop after user enters specific amount of integers?

#include <stdio.h>
int main(void) {
double numbersEntered, sum = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &numbersEntered);
sum += numbersEntered;
}
while (/* ??? */);
printf("Sum = %.2lf", sum);
return 0;
}
What should I do in the while statement to stop the loop after the user enters 4 integers?
You need to introduce a counter:
double numbersEntered, sum = 0;
int count = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &numbersEntered);
sum += numbersEntered;
count++;
} while (count < 4);
Make sure you increment it otherwise your loop will never end.
Changing the 4 to a constant (or even a configurable) variable will make the program more flexible, but whether you actually need to do that depends on what your application needs to do.
I can suggest the following solution
#include <stdio.h>
int main( void )
{
const int N = 4;
double sum = 0.0;
for ( int i = 0, success = 1; success && i < N; i++ )
{
double numberEntered;
printf( "Enter a number: " );
if ( success = ( scanf( "%lf", &numberEntered ) == 1 ) ) sum += numberEntered;
}
printf( "\nSum = %.2lf", sum );
return 0;
}
The program output can look like
Enter a number: 1.1
Enter a number: 2.2
Enter a number: 3.3
Enter a number: 4.4
Sum = 11.00
Or the program can look like
#include <stdio.h>
int main( void )
{
const int N = 4;
double sum = 0.0;
printf( "Enter %d numbers\n\n", N );
for ( int i = 0, success = 1; success && i < N; i++ )
{
double numberEntered;
printf( "Enter number %d: ", i + 1 );
if ( success = ( scanf( "%lf", &numberEntered ) == 1 ) ) sum += numberEntered;
}
printf( "\nSum = %.2lf", sum );
return 0;
}
In this case its output might look like
Enter 4 numbers
Enter number 1: 1.1
Enter number 2: 2.2
Enter number 3: 3.3
Enter number 4: 4.4
Sum = 11.00
Instead of using the constant N equal to 4 you can ask the user to enter the number of entered values.
Hey you need to take the number of integers to be scanned as a input.
and then traverse continously.
#include
int main() {
double numbersEntered, sum = 0;
int numbersToBeEntered = 0;
scanf("%d",&numbersToBeEntered);
do
{
printf("Enter a number: ");
scanf("%lf", &numbersEntered);
sum += numbersEntered;
}while (--numbersToBeEntered);
printf("Sum = %.2lf", sum);
return 0;
}
Use a counter to end the loop when the specified number of double you have entered.
Also, remember to check scanf return value, otherwise, if you input something not a double, you will end up adding the old value of numbersEntered, which mostly is not what you want.
#include <stdio.h>
int main(void) {
double numbersEntered, sum = 0;
int cnt = 0;
int ret;
do
{
printf("Enter a number: ");
ret = scanf("%lf", &numbersEntered);
if (ret != 1) continue;
sum += numbersEntered;
cnt++;
} while (cnt < 4);
printf("Sum = %.2lf", sum);
return 0;
}

Resources