How do I use Do While to stop a loop? - c

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;
}

Related

Factorial program in c

Trying to make a code that gets the factorial of the inputted number.
int factorial(int number, int i)
{
int endval;
for(i = number - 1; i>0; i--){
endval = number * i;
}
if (endval == 0){
printf("1");
}
return endval;
}
int main()
{
int endvalue, numA, numB;
char userchoice[1];
printf("Enter a choice to make (f for factorial): \n");
scanf("%s", userchoice);
if(strcmp(userchoice, "f")== 0){
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA, numB);
printf("%d", endvalue);
return 0;}
getch();
return 0;
}
For some reason the whole for loop doesn't do anything in the function when I set the answer (number*i)= endval. It just prints out the same number I inputted and gives me an absurd answer for 0!.
int factorial(int number, int i)
{
int endval;
for(i = number - 1; i>0; i--){
endval = number * i;
}
if (endval == 0){
printf("1");
}
return endval;
}
However the code works perfectly fine when I remove endval variable entirely (with the exception that it gets 0! = 10)
int factorial(int number, int i)
{
for(i = number - 1; i>0; i--){
number = number * i;
}
if (number == 0) {printf("1");}
return number;
}
Is there anything I missed in the code that's causing these errors?
A definiton of factorial is:
factorial(0) = 1
factorial(n) = n * factorial(n-1)
Note: Factorial is legal only for number >= 0
In C, this definition is:
int factorial(int number)
{
if (number < 0)
return -1;
if (number == 0)
return (1);
/*else*/
return (number * factorial(number-1));
}
#include <stdio.h>
#include <string.h>
int factorial(int number)
{
int endval=1;
for(int i = number ; i>0; i--){
endval *= i;
}
return endval;
}
int main()
{
int endvalue=0;
int numA=0;
char userchoice[1];
printf("Enter a choice to make (f for factorial): ");
int ret=scanf("%s", userchoice);
if (!ret){
printf("Error in scanf: %d", ret);
}
if(strcmp(userchoice, "f")== 0){
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA);
printf("%d", endvalue);
return 0;
}
getchar();
return 0;
}
Code with some changes will work
factorial() function can get only one argument.
As a good habit all variables must be initialized.
Add include statement to source and be explicit not rely on compiler.
As we use strcmp() we must include string.h
use standard getchar() instead of getch()
Also can check return value of library function scanf() to ensure reading is correct or not.
You can use warnings from compiler to get most of above notes. In gcc: gcc -Wall code.c
Use a debugger to run program line by line and monitor variables value in each steps or use as many printf() to see what happens in function call.
There are possibly few things to correct. See please attached code.
int factorial(int number)
{
if (number == 0){ return 1; }
int endval=1, i;
for(i = 1; i<=number; i++) { endval *= i; }
return endval;
}
int main() {
int endvalue, numA;
char userchoice[1];
printf("Enter a choice to make (f for factorial): \n");
scanf("%s", userchoice);
if(strcmp(userchoice, "f")== 0) {
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA);
printf("%d", endvalue);
return 0;
}
getch();
return 0;
}

the code here works perfectly in codeblocks but in codechef IDE it gives SIGTSTP (runtime error and shows a lot of 0s in the output)

LINK TO QUESTION : https://www.codechef.com/problems/LUCKFOUR
#include <stdio.h>
#include<stdlib.h>
int main() {
int T,ans;
scanf("%d",&T);
while(T) {
int num,count = 0;
scanf("%d",&num);
while(num) {
ans = num % 10;
num = num/10;
if( ans == 4) {
count++;
}
}
printf("%d\n",count);
T--;
}
return 0;
}
Runs normally for codeblocks:it takes T first and then takes input from the user and prints the no. of 4s in that input and repeats the process of taking inputs and printing out the no. of 4s T times
I did a little modification in your solution, and it passed. Just pay attention to the constraints, because sometimes int can cause an overflow. Take a look:
#include <stdio.h>
#include <stdlib.h>
int main() {
long long int T;
scanf("%lld", &T);
while(T--) {
long long int num, count=0;
int ans;
scanf("%lld",&num);
while(num) {
ans = num % 10;
num = num/10;
if( ans == 4) {
count++;
}
}
printf("%d\n",count);
}
return 0;
}
Submission image

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

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;
}

Newbie math checker for C. Why won't it work?

#include <stdio.h>
int main(void)
{
printf("What is the sum of 5 + 5?\n");
GetInt();
if int == 10;
printf("Correct.\n");
}
#include <stdio.h>
int main(void)
{
printf("What is the sum of 5 + 5?\n");
GetInt();
if(int == 10){
printf("Correct.\n");
}
return 0;
}
GetInt() is undefined, you also have some very basic syntax errors(that I've corrected) for example if int == 10; int is a data type you can't compare it to a number and even if you could by putting a ; at the end you basically putting and empty conditional, it won't do anything.
#include <stdio.h>
int main(void)
{
int a;
printf("What is the sum of 5 + 5?\n");
scanf("%d", &a);
if(a == 10){
printf("Correct.\n");
}
return 0;
}
This is what you want, now you should really read back the basics of C.
I never use ; with if statement but If I write this code I will write like this
int main(void)
{
int res;
printf("What is the sum of 5 + 5?\n");
scanf("%d",&res)
if (res == 10)
{
printf("Correct.\n");
}
return 0;
}

Hailstone Sequence in C

I'm taking a course in C (it's my first week) and I need to write a program that prints out sequences of hailstone numbers.
I'm expected to build a function to do that.
The next number gets printed out but that's it. For example when I enter 58, I get 29. But I'd like to print out a whole sequence of 9 next numbers.
Please, if you could guide in the right direction, I'd be eternally grateful.
#include <stdio.h>
#include <stdlib.h>
int Hailstone (int n)
{
if (n % 2 == 0) {
return n /= 2;
}
else {
return n = 3 * n + 1;
}
return n;
}
int main (void)
{
int start, result;
printf("Input a number: ");
scanf("%d", &start);
result = Hailstone(start);
printf("%d\n", result);
return 0;
}
What you want is to iterate. You don't need the result variable; you just plug in the new value:
while (start > 1) {
start = Hailstone(start);
printf ("%d\n", start);
}
There's a bit more that could be improved, e.g. the return n; is unreachable and the assignments to n are useless:
int Hailstone (int n)
{
if (n % 2 == 0) {
return n / 2;
}
else {
return 3 * n + 1;
}
}
If you want to hand in a pro C version of Hailstone() you could even write it as
int Hailstone (int n)
{
return n % 2 ? 3 * n + 1 : n / 2;
}
see, in your program, you are trying to return only a single value to the main..Hence to print all the numbers just write a loop as below..
#include <stdio.h>
#include <string.h>
int Hailstone(int n)
{
if(n % 2 == 0) {
return n /=2;
}
else {
return n = (3 * n) + 1;
}
}
int main (void)
{
int start;
printf("Input a number: ");
scanf("%d", &start);
while(start!=1)
{
start = Hailstone(start);
printf("%d\n", start);
}
}

Resources