I have created a code that writes out the sum of all even numbers.
But every time it loops the sum of the last run is saved and added in the sum of the new run. how do i make it have a new loop?
sorry for my bad english, and thx in advance
int main()
{
int number = 0;
int sum = 0;
printf("Welcome to\"Sum Evens\"!");
do
{
printf("\ninput a number: ");
scanf(" %d", &number);
if (number == 0)
{
printf("Goodbye, have a nice day!\n");
break;
}
printf("\nSum:");
if (number % 2 != 0)
{
number -= 1;
}
for (int i = 0; i <= number; i += 2)
{
printf(" %d ", i);
if (i != number)
{
printf("+");
}
sum += i;
}
printf("= %d\n", sum);
} while (number != 0);
system("pause");
return 0;
}
Watch these sort of problems melt away if you declare your variables as close to their first use as possible.
In your case, move int sum = 0; to just before the for loop.
Related
I'm pretty new in programming and I making a decimal to binary converter. I need help to make the print output starts from right to left (reversed).(Sorry if my code is messy)
int main()
{
int num, form;
printf("Decimal to Binary\n\n");
printf(" Value : ");
scanf("%d", &num);
printf(" Expected Format (Type 2 for binary): ");
scanf("%d", &form);
if (form == 2)
printf(" %d base 10 is ", num);
if (form == 2)
do {
if (num % 2 == 0) {
printf("0");
num = num / 2;
}
else {
printf("1");
num = num / 2;
}
} while (num > 0);
else
printf("Invalid input!");
return 0;
}
If I input the value to 25,I expected the output will be "11001", but the actual output is "10011"
Some recursion.. It's looks much more better, for my opinion
#include <stdio.h>
void rec(int num)
{
if (num==0) return;
rec(num>>1);
printf("%d", num%2);
}
int main()
{
int n;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is: ", n);
rec(n);
printf("\n");
return 0;
}
One possibility would be recursion as Jean-Francois Fabre said. Since you mentioned you are a beginner, recursions are sometimes hard to understand at the beginning, so another possibility that I didn't find in his link would be something like this
#include <stdio.h>
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is:\n", n);
for (c = 8; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("\n");
return 0;
}
You can use c to specify the length of your output, or calculate in advance to have a perfect output.
I'm basically done with this, the only problem is when it loops to check for the prime number, it prints out prime numbers that are not in the Fibonacci sequence as well. Here is my code:
int main()
{
int no1,no2,newno,pno,i,terms,j;
no1 = 0;
no2 = 1;
printf("**Fibonacci and Prime Numbers**\n\n");
printf("Enter number of terms: \n");
scanf("%d", &terms);
printf("\nAmong the first %d terms of Fibonacci series that are also prime number: \n", terms);
for(i=0; i<terms; i++){
if(i<=no2){
newno = i;
}
else{
newno = no1+no2;
no1 = no2;
no2 = newno;
}
}
for(pno=2;pno<=newno;pno++){
for(j=2;j<=pno;j++){
if(pno%j==0){
break;
}
}
if(pno==j){
printf("%d \n", pno);
}
}
getch();
return 0;
}
I'm guessing its because of the pno++ , Am i right?
Try this
for(i=0; i<terms; i++){
newno = no1+no2;
no1 = no2;
no2 = newno;
for(j=2;j<=newno;j++){
if(newno%j==0){
break;
}
}
if(newno==j){
printf("%d prime\n", newno);
}
}
This is because you are checking only last number. You should check every number you generate. Consider creating function e.g. is_prime and check every fibonnaci number you compute. Result could look like this (taken from C - how to test easily if it is prime-number?)
int is_prime(int num)
{
if (num <= 1) return 0;
if (num % 2 == 0 && num > 2) return 0;
for(int i = 3; i < num / 2; i+= 2)
{
if (num % i == 0)
return 0;
}
return 1;
}
And your main loop that calls is_prime for every number:
for (i = 0; i<terms; i++) {
if (i <= no2) {
newno = i;
}
else {
newno = no1 + no2;
no1 = no2;
no2 = newno;
if (is_prime(newno)) {
printf("%d\n", newno);
}
}
}
This is just a rough try of what you are trying to achieve .
#include<stdio.h>
int main()
{
int no1,no2,newno,pno,i,terms,j;
no1 = 0;
no2 = 1;
printf("**Fibonacci and Prime Numbers**\n\n");
printf("Enter number of terms: \n");
scanf("%d", &terms);
printf("\nAmong the first %d terms of Fibonacci series that are also prime number: \n", terms);
for(i=0; i<terms; i++)
{
newno = no1+no2;
no1 = no2;
no2 = newno;
for(pno = 2; pno <= newno ;pno++)
{
if(pno == newno)
printf("%d\n",newno);
if(newno%pno == 0)
break;
}
}
return 0;
}
You were only trying to check only the last term and that to in incorrect way.
The for loop you used
for(pno=2;pno<=newno;pno++){
for(j=2;j<=pno;j++){
if(pno%j==0){
break;
}
}
if(pno==j){
printf("%d \n", pno);
}
}
was applying check on local counter pno that does not make any sense.
You can further optimize your program using a better way to find if a number is prime as it will take huge time for large inputs.
I'm working on this program that should output 10 prime numbers. So my problem is that I dont know how to tell the program to stop as soon as 10 prime numbers have been stored in the array. I tried to do sizeof(primes)/siseof(int) == 10 , but its not working.
Help me please. Thanks in advance
int ar[100],primes[10],j,n,i,var;
printf("Enter a prime ,\n");
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
if (IsPrime(ar[i])) {
primes[i] = ar[i];
if( sizeof(primes) / sizeof(int) == 10) break;
} else {
printf("%d is not a prime number\n", ar[i]);
}
}
printf("\narray :\n");
I'm going to pitch something a bit more in line with your stated intention:
#define MAX_PRIMES 10
int main(int argc, char * argv[])
{
int inval;
int primes[MAX_PRIMES];
int count = 0;
printf("Enter a prime number,\n");
while (count < MAX_PRIMES)
{
scanf("%d", &inval);
if (IsPrime(inval))
{
primes[count] = inval;
count++;
}
else
{
printf("%d is not a prime number\n", inval);
}
}
printf("\nThe elements of the array are:\n");
for (int i = 0; i < MAX_PRIMES; i++)
{
printf(" %d", primes[i]);
}
}
int ar[100] was replaced with int inval because there doesn't seem to be any need to store the input values.
for(i=0;i<n;i++) replaced with while (count < MAX_PRIMES) because the previous version would stop at n whether 10 primes had been found or not.
printf(" %d",ar[i]) was replaced with printf(" %d", primes[i]) because the stated desired output is 10 primes, not the input array.
Could be a stupid tyop or two in there because I haven't run it.
Use a counter variable. Use this as the index of the primes array, because otherwise you'll write outside the bounds of the array if the user enters more than 10 numbers to try.
int ar[100],primes[10],j,n,i,var;
int primesFound = 0;
printf("Enter a prime number,\n");
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
if (IsPrime(ar[i])) {
primes[primesFound] = ar[i];
primesFound++;
if( primesFound == 10) break;
} else {
printf("%d is not a prime number\n", ar[i]);
}
}
printf("\nThe elements of the array are:\n");
for(i=0;i<n;i++)
{
printf(" %d",ar[i]);
}
Just add a counter
int ar[100],primes[10],j,n,i,var;
printf("Enter a prime number,\n");
int counter = 0; // here you declare a counter
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
if (IsPrime(ar[i])) {
counter++ // here you increase your counter
primes[i] = ar[i];
if (counter == 10) break;
} else {
printf("%d is not a prime number\n", ar[i]);
}
}
printf("\nThe elements of the array are:\n");
for(i=0;i<n;i++)
{
printf(" %d",ar[i]);
}
Now, why the if( sizeof(primes) / sizeof(int) == 10) break; doesn't work? Because your primes is an array, which is declared statically and so its size is always a constant, which is equal to 10 * sizeof(int).
I need to create a simple program which asks for 10 numbers from user and then shows the sum of those numbers or, if the user gives 0 as input, stops and immediately displays the sum of those numbers, and I need to create it only by using a "for" condition. Here is the code:
#include <stdio.h>
int main(){
int num = 0;
for(num = 0; num < 10; num++){
printf("Input a number: \n");
scanf("%d", &num);
if(num == 0){
printf("Sum: %d\n", num);
}
}
printf("Sum: %d\n", num);
getchar();
getchar();
}
It stops only when the number is greater than "10".Whats wrong?
I think you want to do this kind of work with your code.
#include <stdio.h>
int main(){
int num = 0;
int sum=0;
for(num = 0; num < 10; num++){
int i;
printf("Input a number: \n");
scanf("%d", &i);
sum = sum+i;
if(i == 0){
printf("Sum: %d\n", sum);
getchar();
return 0;
}
}
printf("Sum: %d\n", sum);
getchar();
return 0;
}
You are changing the value of the counter inside the for loop. That's why, when you read a value greater than or equal to 10, it will abandon the for loop, since you have the condition num < 10.
Let me tweak the code for you:
#include <stdio.h>
int main(){
int sum = 0;
int i;
int num;
for(i = 0; i < 10; i++){
printf("Input a number: \n");
scanf("%d", &num);
sum += num;
if(num == 0){
break; //means leave the loop
}
}
printf("Sum: %d\n", sum);
getchar();
return 0;
}
I'm using 3 variables:
sum, which is used to store the overall sum.
i, which is used as the for loop counter.
num, which is used to store the current number given by the user.
First of all, I'm waiting for an input:
printf("Input a number: \n");
scanf("%d", &num);
Now, the input is stored in num, so I'm upgrading the sum, to add the new value:
sum += num;
The I check if the current number is zero; in that case I'll just leave the loop:
if(num == 0){
break;
}
The problem in your code is, you're using the same variable num both as counter and for taking user input which is breaking the logic in for loop.
Use another variable for taking user input.
Also, you've to have a break statement to discontinue the for loop once you've got the breaking criteria.
Note: as I mentioned in my comments, there is no logic for Sum.
Check the below code.
#include <stdio.h>
int main(){
int num = 0;
int sum = 0; //to hold the sum
int input = 0;
for(num = 0; num < 10; num++){
printf("Input a number: \n");
scanf("%d", &input);
sum += input; // yoo-hoo, time to add-up
if(input == 0){
printf("Sum: %d\n", sum);
break; // time to say bye-bye to for loop
}
}
if (num == 10) //only print if not printed previously
printf("Sum: %d\n", sum);
return 0;
}
In the main method below I'm trying to call a sort function and after function selects that latter from the user input it has to print the sort accordingly with the for loop at the end. But I have a warning that reads "loop will run at most once (loop increment never executed)" pointing at the array[arraySize]. Does it have to do with the return type or the other for loop above? What's happening here? Can anyone point out and explain please. Thanks much! Here's the code below:
int main()
{
long array[100], arraySize;
char sort;
long maxi = 100;
for(arraySize = 0; arraySize < maxi; arraySize++)
{
printf("Enter any positive integer, enter 0 to stop: ");
scanf("%li", &num);
if(num < 0) {
arraySize--;
printf("I said positive!");
count++;
}
else if(num == 0) {
maxi = arraySize;
}
else {
array[arraySize]=num;
arraySize--;
}
}
printf("Please enter A for ascending or D for descending order\n");
scanf("%s", &sort);
bubble_sort(array, arraySize, sort); //calling the sort function
printf(" Sorted list in the selected order:\n");
for (arraySize = 0; arraySize < num; arraySize++) {
printf("%ld \n", array[arraySize]);
puts("");
return 0;
}
}
EDIT: Thanks everyone for all your suggestions. I did make a few changes and here's what I have so far. Now it's skipping the A/D user input along with the bubble_sort function logic. Here's what it does as a final output: Note: long num is declared as a global variable!
int main()
{
long array[100], arraySize;
char sort;
long maxim = 100;
for(arraySize = 0; arraySize < maxim; arraySize++)
{
printf("Enter any positive integer, enter 0 to stop: ");
scanf("%li", &num);
if(num < 0)
{
arraySize--;
printf("I said positive! \n");
count++;
}
else if(num == 0)
{
maxim = arraySize;
}
else
{
array[arraySize]=num; //arraySize--;
}
}
printf("Please enter A for ascending or D for descending order: \n");
scanf("%c", &sort);
bubble_sort(array, maxim, sort); //calling the sort function
printf("Sorted list in the selected order:\n");
for (arraySize = 0; arraySize < maxim; arraySize++)
{
printf("%ld \n", array[arraySize]);
}
puts("");
return 0;
}
Any more suggestions will be appreciated!
There are a few other problems, but let's talk about your warning. You have this code:
for (arraySize = 0; arraySize < num; arraySize++) {
printf("%ld \n", array[arraySize]);
puts("");
return 0;
}
The corrected indentation should make it obvious why that loop will run at most once.
It seems your print loop has a typo, and should be corrected to:
for (arraySize = 0; arraySize < maxi; arraySize++) {
Also the call to bubble_sort() should use maxi rather than arraySize.
The last character entered gets stored in sort and that character is most probably \n.
Changing scanf("%c", &sort); to scanf(" %c", &sort); should solve the problem.
Note the space before %c.