C Programming: Removing Unnecessary Commas From Result of Prefix Sum Code - c

I recently made code in C that reads a set of numbers until zero (zero ends the number set) and prints its prefix sum:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, sum;
sum = 0;
while(x)
{
scanf("%d", &x);
sum += x;
if(x != 0)
{
printf("%d,", sum);
}
else{
break;
}
}
return 0;
}
If I were to type 2 3 5 7 11 0: It would print the following:
2,5,10,17,28,
I was wondering how to remove the comma by the number 28 or to add commas to numbers until the last number?

My preferred solution, adapted to the code in the question, is:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int sum = 0;
int x;
const char *pad = ""; /* Or put a prefix here */
while (scanf("%d", &x) == 1 && x != 0)
{
sum += x;
printf("%s%d", pad, sum);
pad = ","; /* Or use ", " if you prefer */
}
putchar('\n');
return 0;
}
Note that this code does not test the uninitialized variable x on the first iteration (unlike the code in the question), and it checks that the scanf() succeeds before using the value (unlike the code in the question). These are routine precautions you should be taking. It would be possible to adapt the code to keep track of how many bytes have been printed on the line (what's the return value from printf()?) and arrange for pad to contain "\n" (instead of a comma, or ",\n" if you want a comma at the end of all lines except the last) when the line gets 'too long'.
Note too that if you type the numbers at the program, the output gets messy. If the program is reading from a built-in list of numbers, or reading from a file, then you get good outputs.

You could use the following approach:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 0;
int sum = 0;
int i = -1;
int ret;
while(1)
{
i++;
ret = scanf("%d", &x);
if(ret != 1)
break;
sum += x;
if(x != 0)
{
if(i == 0)
printf("%d", sum);
else
printf(",%d", sum);
}
else
{
break;
}
}
printf("\n");
return 0;
}
Output:
1
2
3
0
1,3,6

Print the comma before all but the first value. It's not elegant but it works.
if(x != 0)
{
if(sum == x) // On the first pass, sum == x
printf("%d", sum);
else
printf(",%d", sum);
}
Of course, this could break if you have negative values. In that case, keeping a counter or bool would be better.

print comma only after the first iteration (use a custom flag) , print result no matter what:
int first_iteration = 1;
...
if (!first_iteration)
{
printf(",");
}
sum += x;
first_iteration = 0;
printf("%d", sum);

There is always a clumsy but tried-and-true method:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, sum;
sum = 0;
comma = 0;
while(x)
{
scanf("%d", &x);
sum += x;
if(x != 0)
{
if (comma != 0)
{
printf(",");
}
printf("%d", sum);
comma = 1;
}
else{
break;
}
}
return 0;
}

Related

How do I use Do While to stop a loop?

I am writing a simple program that takes an input and adds it to a sum and then prints it, but then asks for another input and also adds that to the sum. However when 0 is in the input, the program should stop. That part is not working, here is what I have tried.
#include <stdio.h>
int main(){
int n, summa, t;
summa = 0;
t=1;
do{
scanf("%d", &n);
if(n==0){t=0;
}
summa = n + summa;
printf("%d\n", summa);
}
while(t == 0);{return 0;}
return 0;}
I believe you intended your conditional to be t != 0.
Here's a reformatted version of your code with the new conditional, see if that functions as you expected.
#include <stdio.h>
int main() {
int n, summa, t;
summa = 0;
t = 1;
do {
scanf("%d", &n);
if (n == 0) {
t = 0;
}
summa = n + summa;
printf("%d\n", summa);
}
while(t != 0);
return 0;
}

how to extract the even number from user input, and combine them as a new number in C program

test case:
input: 1234
output: 24
input: 2468
output: 2468
input: 6
output: 6
I have this code:
#include <stdio.h>
#include <math.h>
int main() {
int num;
printf("Enter a number: \n");
scanf("%d", &num);
int numberLength = floor(log10(abs(num))) + 1;
int inputNumberArray[numberLength];
int evenNumberCount = 0;
int even[10];//new even no. array
int i = 0;
do {
inputNumberArray[i] = num % 10;
num = num / 10;
i++;
} while (num != 0);
i = 0;
while (i < numberLength) {
if (inputNumberArray[i] % 2 == 0) {
evenNumberCount ++;
even[i] = inputNumberArray[i];
}
i++;
}
printf("array count %d\n", evenNumberCount);
i = 0;
for (i = 0; i < 8; i++) {
printf(" %d", even[i]);//print even array
}
i = 0;
int result = 0;
for (i = 0; i < 10; i++) {
if (evenNumberCount == 1) {
if (even[i] != 0) {
result = even[i];
} else {
break;
}
} else {
if (even[i] != 0) {
result = result + even[i] * pow(10, i);
} else
break;
}
}
printf("\nresult is %d", result);
/*
int a = 0;
a = pow(10, 2);
printf("\na is %d", a);
*/
}
when I enter number 1234, the result/outcome is 4, instead of 24.
but when I test the rest of test case, it is fine.
the wrong code I think is this: result = result + even[i] * pow(10, i);
Can you help on this?
Thanks in advance.
why do you have to read as number?
Simplest algorithm would be
Read as text
Validate
loop through and confirm if divisible by 2 and print live
next thing, have you try to debug?
debug would let you know what are doing wrong. Finally the issue is with indexing.
evenNumberCount ++; /// this is technically in the wrong place.
even[i]=inputNumberArray[i]; /// This is incorrect.
As the user Popeye suggested, an easier approach to accomplish this would be to just read in the entire input from the user as a string. With this approach, you can iterate through each letter in the char array and use the isdigit() method to see if the character is a digit or not. You can then easily check if that number is even or not.
Here is a quick source code I wrote up to show this approach in action:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char input[100] = { '\0' };
char outputNum[100] = { '\0' };
// Get input from user
printf("Enter a number: ");
scanf_s("%s", input, sizeof(input));
// Find the prime numbers
int outputNumIndex = 0;
for (int i = 0; i < strlen(input); i++)
{
if (isdigit(input[i]))
{
if (input[i] % 2 == 0)
{
outputNum[outputNumIndex++] = input[i];
}
}
}
if (outputNum[0] == '\0')
{
outputNum[0] = '0';
}
// Print the result
printf("Result is %s", outputNum);
return 0;
}
I figured out the solution, which is easier to understand.
#include <stdio.h>
#include <math.h>
#define INIT_VALUE 999
int extEvenDigits1(int num);
void extEvenDigits2(int num, int *result);
int main()
{
int number, result = INIT_VALUE;
printf("Enter a number: \n");
scanf("%d", &number);
printf("extEvenDigits1(): %d\n", extEvenDigits1(number));
extEvenDigits2(number, &result);
printf("extEvenDigits2(): %d\n", result);
return 0;
}
int extEvenDigits1(int num)
{
int result = -1;
int count = 0;
while (num > 1) {
int digit = num % 10;
if (digit % 2 == 0) {
result = result == -1 ? digit : result + digit * pow(10, count);
count++;
}
num = num / 10;
}
return result;
}
}
You are overcomplicating things, I'm afraid.
You could read the number as a string and easily process every character producing another string to be printed.
If you are required to deal with a numeric type, there is a simpler solution:
#include <stdio.h>
int main(void)
{
// Keep asking for numbers until scanf fails.
for (;;)
{
printf("Enter a number:\n");
// Using a bigger type, we can store numbers with more digits.
long long int number;
// Always check the value returned by scanf.
int ret = scanf("%lld", &number);
if (ret != 1)
break;
long long int result = 0;
// Use a multiple of ten as the "position" of the resulting digit.
long long int power = 1;
// The number is "consumed" while the result is formed.
while (number)
{
// Check the last digit of what remains of the original number
if (number % 2 == 0)
{
// Put that digit in the correct position of the result
result += (number % 10) * power;
// No need to call pow()
power *= 10;
}
// Remove the last digit.
number /= 10;
}
printf("result is %lld\n\n", result);
}
}

How to remove the last comma in comma separated prime numbers within a range?

I have the code for finding prime numbers within a range.
The problem is to remove the last comma.
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
}
But the output contains an extra comma in the last.
For example
2,3,5,7,
whereas the expected output is
2,3,5,7
Instead of flag you can decide directly what you want to print between numbers
And note that you can break out of the internal loop as soon as f is set to 1
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
const char* delim = "";
scanf("%d%d",&a,&b);
for(x=a; x<=b; (x++,f=0))
{
for(i=2; i<x; i++)
{
if(x%i==0)
{
f=1;
break; //no need to continue the checking
}
}
if(f==0) {
printf("%s%d",delim,x);
delim = ", ";
}
}
putchar('\n');
}
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
char backspace = 8;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
printf("\b"); // or printf("%c", backspace);
}
Add another flag, just a simple counter that tells you if you are printing the first time then check the flag to decide what to print, e.g.
#include<stdio.h>
int main()
{
int a,b,i,x,c,first=0,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
{
if(first==0){
printf("%d",x);
}else{
printf(",%d",x);
}
first++
}
}
}
Use a flag to detect the first occurrence of printf() and print the first number as such without any ,. For consecutive number printing precede with ,
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1,flag=0;//Flag to mark first occurrence
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
break;// Once the condition fails can break of the for loop as it fails for the prime number condition at the first case itself
}
}
if(f==0)
{
if(flag==0)
{//Check if it is first time
printf("%d",x);
flag = 1;//If so print without ',' and set the flag
}
else
printf(",%d",x);// On next consecutive prints it prints using ','
}
}
}
This method also avoids the , when only one number is printed.
Eg: When input is 2 and 4. It prints just 3 and not 3,
Simply you need odd number best practice for minimum loop is given below;
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
while (a < b)
{
if ( (a%2) == 1) {
printf("%d", a);
if ( (a + 1) < b && (a + 2) < b)
printf(",");
}
a = a + 1;
}
}
please check from the site
http://rextester.com/MWNVE38245
Store the result into a buffer and when done print the buffer:
#include <stdio.h>
#include <errno.h>
#define RESULT_MAX (42)
size_t get_primes(int * result, size_t result_size, int a, int b)
{
int i, x, f = 1;
size_t result_index = 0;
if (NULL == result) || (0 == result_size) || ((size_t) -1 == result_size))
{
errno = EINVAL;
return (size_t) -1;
}
for (x = a; x <= b; (x++, f = 0))
{
for (i = 2; i < x; i++)
{
if (x % i == 0)
{
f = 1;
break;
}
}
if (f == 0)
{
result[result_index] = x;
++result_index;
if (result_size <= result_index)
{
fprintf(stderr, "Result buffer full. Aborting ...\n");
break;
}
}
}
return result_index;
}
int main(void)
{
int a = 0, b = 0;
int result[RESULT_MAX];
scanf("%d%d", &a, &b);
{
size_t result_index = get_primes(result, RESULT_MAX, a, b);
if ((size_t) -1 == result_index)
{
perror("get_primes() failed");
}
else if (0 == result_index)
{
fprintf(stderr, "No primes found.\n");
}
else
{
printf("%d", result[0]);
for (size_t i = 1; i < result_index; ++i)
{
printf(", %d", result[i]);
}
}
}
return 0;
}
This example uses a simple fixed-size buffer, if this does not suite your needs replace it by a dynamic one.
This is more of a "language-agnostic" problem: "How do I output a comma-separated list without a final comma?" It is not specifically about prime numbers.
You seem to be thinking of you list as a series of [prime comma] units. It isn't. A better way to think of it is as a single prime as the head of the list, followed by a tail of repeated [comma prime] units.
Some pseudocode to illustrate the general idea:
outputList(theList)
separator = ", "
output(theList.firstItem())
while (theList.hasMoreItems())
output(separator)
output(theList.nextItem())
endwhile
return
/* this is just logic */
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
c++;
c++;
}
}
System.out.println(c);
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
System.out.print(i);
b++;
if(b!=c-1)
{
System.out.print(",");
b++;
}
}
}
}
}
//comma separated values
#include <bits/stdc++.h>
using namespace std;
int Prime(int a, int n){
bool prime[n+1];
memset(prime,true,sizeof(prime));
for(int p=2;p*p<=n;p++){
if(prime[p]==true){
for(int i=p*p ; i<=n; i+=p ){
prime[i] = false;
}
}
}
for(int i = 2;i<= n;i++){
if(i==2) cout<<i; // here is the logic first print 2 then for other numbers first print the comma then the values
else if(prime[i]) cout<<","<<i;
}
}
int main(){
int a =2 ;
int n = 30;
Prime(a , n);
}
#include <stdio.h>
int main()
{
int i, j, n, count;
scanf("%d", &n);
for(i=2; i<n; i++)
{
count=0;
for(j=2; j<n; j++)
{
if(i%j==0)
count++;
}
if(count==1)
printf("%d," i);
}
printf("\b \b");
}
\b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there, it replaces it. For a a destructive backspace,
use "\b \b" i.e. a backspace, a space, and another backspace.
This Program prints all the prime number up to given number with comma separated

How do i print all the odd numbers?

I want to print all the odd numbers from 14 to 156 using an infinite loop, break and continue. But, when i run it does not display anything!!
int main()
{
int x;
int y = 14;
while(x) {
if(y % 2 == 0) {
continue;
}
else if(y % 3 == 0) {
printf("%d\n", y);
}
if(y == 156) {
break;
}
y++;
}
return 0;
}
The problem with your code is that it uses an operation with unpredictable results. Specifically, declaring int x; without initializing it, and then using it as your termination condition in while(x) is the problem. On many platforms and compilers, this will retain whatever value was already in the memory occupied by x. In that case, you may see no print statements because x starts with the value zero and the loop never runs.
You should make your loop into an infinite loop:
int main()
{
int x;
for(x = 14; ; x++) {
if(x % 2 == 0) {
continue;
}
if(x >= 156) {
break;
}
printf("%d\n", x);
}
return 0;
}
[IDEOne link]
This will print the values excluding 156 itself. To include 156, put the break condition after the printf call:
printf("%d\n", x);
if(x >= 156) {
break;
}
Alternatively you can change >= to just >.
You do not need else if you have break or continue.
If you have to use a while loop, the situation is a tad more complex because you have to increment before you continue to avoid an infinite loop:
int main() {
int x = 14;
while(1) {
if(x % 2 == 0) {
x++;
continue;
}
if(x >= 156) {
break;
}
printf("%d\n", x++);
}
return 0;
}
[IDEOne Link]
You can avoid the extra increment if you can forgo the continue:
int main() {
int x = 14;
while(1) {
if(x % 2) {
printf("%d\n", x);
}
if(x++ == 156) {
break;
}
}
return 0;
}
[IDEOne Link]
I have also removed your check for x % 3 == 0 since it is not clear what the purpose of that is within the constraints of your problem.
With an infinite loop:
#include <stdio.h>
#include <stdlib.h>
int main() {
int y=14;
while(1){
if(y & 1){
printf("%d\n",y);
}
if(y>=156){
break;
}
y++;
}
return 0;
}
Preferred method, with for loop:
#include <stdio.h>
#include <stdlib.h>
int main() {
int start=14;
start |= 1; //This will increment by one if your start value is even
for (start; start<=146; start+=2) {
printf("%d\n", start);
}
return 0;
}
An infinite loop with a break is not the right way to do this. Use a "for" loop and your code will be much clearer. Start it at 15 and increment by 2 until 156.
There are several problems in your logic.
1. Variable `x` is of no use. You can use variable `y` to terminate the loop.
2. No need to check if the number is a multiple of 3.
3. No need to check for even numbers is either.
I have modified the code and it is giving correct results but I'll urge you to read the above points and try to get the code right.
int main()
{
int y = 14;
while(y) {
if (y==156)
break;
if(y % 2 != 0) {
printf("%d ",y);
}
y++;
}
return 0;
}
A better and faster way would be to start with 15 and increment variable y's value by 2 till its <=156.
int main()
{
int y = 15;
while(y) {
if (y==157)
break;
printf("%d ",y);
y+=2;
}
return 0;
}
Your code has undefined behavior because the variable x is uninitialized and used as the condition in the while statement. You could fix this with while (1) but there would indeed be an infinite loop in your program because the test for evenness occurs before the test for termination on 156.
The problem is solved simply with a standard for loop:
#include <stdio.h>
int main(void) {
for (int y = 14; y < 156; y++) {
if (y % 2 != 0) {
printf("%d\n", y);
}
}
return 0;
}
Which can be simplified as this, only enumerating odd numbers:
#include <stdio.h>
int main(void) {
for (int y = 15; y < 156; y += 2) {
printf("%d\n", y);
}
return 0;
}
If you are required to use break, continue and a infinite loop, you can indeed use the classic forever C loop, a for loop without a termination condition:
#include <stdio.h>
int main(void) {
for (int y = 14;; y++) {
if (y == 156)
break;
if (y % 2 == 0)
continue;
printf("%d\n", y);
}
return 0;
}
Well ...
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
/* Prints even or add numbers between to and from.
Works for negative numbers.
Works up and down.
*/
int print_even_or_odd(long long from, long long to, int even)
{
if (((INT32_MAX < from) || (INT32_MIN > from)) ||
((INT32_MAX < to) || (INT32_MIN > to)))
{
fprintf(stderr, "Invalid input.\n");
errno = EINVAL;
return -1;
}
printf("from=%d to %d\n", (int) from, (int) to);
int sign = (to < from) ?-1 :1;
/* Adjust "from" to next even/odd number. */
if ((!even && !(from & 1)) || (even && (from & 1)))
{
from += sign;
}
/* Adjust "to" to the previous even/odd number. */
if ((!even && !(to & 1)) || (even && (to & 1)))
{
to -= sign;
}
{
size_t steps = (size_t) (sign * ((to - from) / 2)) + 1;
if (0 == steps)
{
printf("Nothing to do.\n");
return 0;
}
while (1)
{
if (0 >= steps)
{
break;
}
--steps;
printf("%d\n", (int) (to - sign * 2 * (int) steps));
continue; /* as having continue is a requirement ... ;-) */
}
}
return 0;
}
int main(void)
{
print_even(14, 156, 0);
print_even(156, 14, 0);
print_even(-14, -156, 0);
print_even(-156, -14, 0);
}

C program for Armstrong Number giving wrong output

This program is not showing 153 as Armstrong Number while for other numbers the output is correct. Like I checked for 407 it gave the right answer but when I checked 153 it showed not an Armstrong number.
#include <stdio.h>
#include <math.h>
int main() {
int no, copy, re, n = 0, ans = 0;
printf("\n\tEnter a new number: ");
scanf("%d", &no);
copy = no;
while (copy != 0) {
copy = copy / 10;
n++;
}
copy = no;
while (copy != 0) {
re = copy % 10;
ans = ans + pow(re, n);
copy = copy / 10;
}
if (ans == no) {
printf("\n\t %d is an Armstrong number", no);
} else {
printf("\n\t %d is not an Armstrong number", no);
}
getch();
return 0;
}
First of all You need to give proper name for variable
Try this code it works for me
#include <stdio.h>
#include <math.h>
int main()
{
int number, originalNumber, remainder, result = 0, n = 0 ;
printf("Enter an integer: ");
scanf("%d", &number);
originalNumber = number;
while (originalNumber != 0)
{
originalNumber /= 10;
++n;
}
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber%10;
result += pow(remainder, n);
originalNumber /= 10;
}
if(result == number)
printf("%d is an Armstrong number.", number);
else
printf("%d is not an Armstrong number.", number);
return 0;
}
In this program, the number of digits of an integer is calculated first and stored in n variable.
And the pow() function is used to compute the power of individual digits in each iteration of the while loop.
Your code has no problem. It works fine. Compiling your code gcc -o file filename.c -lm and run as ./file to avoid the linkage problems.
In my Visual Studio 2013 I got below image with your code.
You may try different compiler software , I think.
Built-in "pow" function cannot be used in this case. Instead you can use this:
int power(int n,int r)
{
int i,p=1;
for(i=1;i<=r;i++)
p=p*n;
return p;
}
and call it in your main function
result += power(remainder, n);
It will work for all cases.
Your algorithm is correct and your program performs as expected (except for the missing newlines) on my system. If your system reports 153 as not being an Armstrong number, it is broken, possibly because of the floating point operation for raising the digits to the n-th power. Try this alternative:
#include <stdio.h>
#include <math.h>
int main(void) {
int no, copy, re, i, d, n = 0, ans = 0;
printf("Enter a new number: ");
if (scanf("%d", &no) == 1) {
copy = no;
while (copy != 0) {
copy = copy / 10;
n++;
}
copy = no;
while (copy != 0) {
d = copy % 10;
for (re = d, i = 1; i < n; i++) {
re *= d;
}
ans = ans + re;
copy = copy / 10;
}
if (ans == no) {
printf("%d is an Armstrong number\n", no);
} else {
printf("%d is not an Armstrong number\n", no);
}
getch();
}
return 0;
}

Resources