I'm trying to figure out a homework assignment in C. The instructions state to have the user input integers in a loop until they enter a negative number, and then to output the sum of all the numbers. The second part seems pretty straight forward to me, but I can't wrap my head around the first part. How do you store a user input integer with a loop?
This is all I have so far.
int main(void)
{
int i = -1;
while(i > -1)
{
printf("Please enter a number %i. When finished, enter a negative number.", i);
scanf("%i", &i);
}
return 0;
}
int main(void)
{
int i = 0,sum = 0;
do
{
sum +=i; // use sum here if you don't want to add -ve value
printf("Please enter a number i. When finished, enter a negative number. ");
scanf("%i",&i);
//sum +=i; // use sum here if you want to add -ve value also to the sum
}
while(i > -1);
printf("Sum = %d", sum);
return 0;
}
You have assigned i = -1 and checking if i is greater than -1 which is false. So, the loop isn't executing.
You can try this.
#include<stdio.h>
int main()
{
int i=0,sum=0;
while(true)
{
scanf("%d",&i);
if(i < 0) break;
sum+=i;
}
printf("%d\n",sum);
return 0;
}
#include <iostream>
int main () {
int number = 0;
int accumulator = 0;
do {
accumulator += number;
std::cout << "Enter numbers to accumulate. Use negative number to finish: " << std::endl;
std::cin >> number;
} while (number > 0); //as you can also use -1 as the ending loop
std::cout << accumulator;
return 0;
}
AN EXTRA VERSION FOR C++ and using understandable variable names if someone needs it.
Related
i have a homework but i cant get the answer
I need to write a program in C...
Here is what is needed: You need to enter "n" natural number as input , and from all the natural numbers smaller than "n" , its needed to print the number which has the highest sum of devisors.
For exp: INPUT 10 , OUTPUT 8
Can anyone help me somehow?
I would really appreciate it !
i tried writing a program for finding the devisor of a number but i cant get far from here
#include <stdio.h>
int main() {
int x, i;
printf("\nInput an integer: ");
scanf("%d", &x);
printf("All the divisor of %d are: ", x);
for(i = 1; i < x; i++) {
if((x%i) == 0){
printf("\n%d", i);
}
}
}
I have implemented using function which will takes input number from user and then return the sum of divisor. hope this is one you looking for
/* function to return of sum of divisor
** input: x: integer number from user input
** return sum: sum of divisor of x
*/
int sum_of_divisor(int x)
{
int sum = 0;
for(int i = 1; i < x; i++)
{
if((x%i) == 0)
{
printf("%d\n", i);
sum = sum+i;
}
}
return sum;
}
int main() {
int x, i;
printf("\nInput an integer: ");
scanf("%d", &x);
printf("All the divisor of %d are: ", x);
printf("the sum of divisor is %d ", sum_of_divisor(x));
return 0;
}
Output:
Input an integer: 10
All the divisor of 10 are: 1
2
5
the sum of divisor is 8
After checking if i is a divisor of x, you should then store that value in another variable, for example m.
Repeat until a new divisor i is higher than that number. Add this new value to m.
In this file I am trying to make something that adds all numbers up to a number entered by a user. Such as, 4: 1 + 2 + 3 + 4 = 10. So if they enter 4 it returns 10.
When I run the code I get an error message saying my file has stopped working. Do i have an endless loop?
#include "biglib.h"
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
// Asking them for their number
int num;
scanf("%i", num);
// then I run a loop, if num == 0 then the program should break from the loop and return 0 in the main function if not run the code inside the program.
int i;
while(num != 0)
{
// I define "i" to be one less than that of num then as long as "i" is greater than 0 keep running the loop and subtract one at the end of it.
for(i = num - 1; i > 0; i--)
{
// in here I do the addition.
num = num + i;
}
// finally I print out the answer.
printf("%i\n",num);
continue;
}
return 0;
}
Yes, you have an infinite loop. Also the input is not stored in the num variable.
#include "stdio.h"
int main(void) {
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
scanf("%i", &num);
int sum = 0;
while(num>0){
sum += num;
num -= 1;
}
printf("%i\n",sum);
return 0;
}
Some lines of your code seem odd to me.
Why do you use a while loop to test the value of num ?
Why do you put a continue statement as last while loop instruction ?
Remarks:
Your code does not work for negative number, is it the expected behaviour?
You are not testing the scanf return value, which could cause trouble.
I am pretty sure that you should check the scanf prototype.
Hope these questions will lead you to improve your code.
Thank you yadras fro informing me that I had the scanf outside of the while loop that was the problem and now it works when I do this.
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
int i;
while(num != 0){
scanf("%i", &num);
for(i = num - 1; i > 0; i--)
{
num = num + i;
}
printf("%i\n",num);
}
return 0;
}
My assignment is to check if a number is prime, but I have to use three sections to do it. The first is the main body of code and that is followed by two functions. The first checks if the number is even, and the second checks if it is prime. I know this is a rather tedious way to check if a number is prime but it is meant to get us introduced to functions and function calls!
UPDATE
I have gotten it all to work besides printing the smallest divisor of a non prime number. I thought using i from the second function would work but it will not output. I have copied by code below -- please help if you have any suggestions!
#include <stdio.h>
#include <math.h>
int even (int);
int find_div (int);
int main() {
int num, resultEven, resultPrime, i;
printf("Enter a number that you think is a prime number (between 2 and 1000)> \n");
scanf("%d", &num);
while (num < 2 || num > 1000) {
if (num < 2) {
printf("Error: number too small. The smallest prime is 2.\n");
printf("Please reenter the number > \n");
scanf("%d", &num);
}
else if (num > 1000) {
printf("Error: largest number accepted is 1000.\n");
printf("Please reenter the number > \n");
scanf("%d", &num);
}
else {
}
}
resultEven = even(num);
resultPrime = find_div(num);
if (resultEven == 1) {
printf("2 is the smallest divisor of %d. Number not prime\n", num);
}
else if (resultPrime == 1) {
printf("%d is the smallest divisor of %d. Number not prime\n", i, num);
}
else {
printf("%d is a prime number.\n", num);
}
return 0;
}
int even(int num) {
if (num % 2 == 0) {
return 1;
}
else {
return 0;
}
}
int find_div(int num) {
int i;
for (i = 2; i <= (num/2); i++) {
if (num % i == 0) {
return 1;
}
if (num == i) {
return 0;
}
}
return i;
}
I would create a function for Wilsons theorem (p-1)! = 1 (mod p) iff p is prime, first off, to make the functions nice and easy you will only need the one. for numbers less than 1000 it should work fine.
something like,
//it will return 1 iff p is prime
int wilson(int p)
{
int i, result = 1;
for (i = 0; i < p; i++)
{
result *= i;
result = result % p;
}
return result;
}
however if your not printing check that you have included, at the top of your file
#include <stdio.h>
your
resultEven = even(num)
needs a ; at the end but that was mentioned in the comments, besides that your methodology though odd is correct, also you do not need the empy else, that can simply be removed and your good
UPDATE:
//if return value == 1 its prime, else not prime, and
//return value = smallest divisor
int findDiv(int p)
{
int i= 0;
for (; i <= n/2; i++)
{
//you number is a multiple of i
if (num % i == 0)
{
//this is your divisor
return num;
}
}
//1 is the largest divisor besides p itself/smallest/only other
return 1;
}
your function call is correct but you need a semi colon (;) at the end of:
resultEven = even(num)
otherwise this program effectively checks for evenness. To check for prime one way is to ensure the number has no factors other than one and itself. This is done by finding the div of every whole number from 2 to half of the number being tested using a for loop. If a number produces a div of 0 then it is not prime because t has a factor other than 1 and itself.
I am taking an online C class, but the professor refuses to answer emails and I needed some help.
Anyways, our assignment was to write a program that takes an integer from the user and find the largest even digit and how many times the digit occurs in the given integer.
#include <stdio.h>
void extract(int);
void menu(void);
int main() {
menu();
}
void menu() {
int userOption;
int myValue;
int extractDigit;
do {
printf("\nMENU"
"\n1. Test the function"
"\n2. Quit");
scanf("%d", &userOption);
switch (userOption) {
case 1:
printf("Please enter an int: ");
scanf("%d", &myValue);
extractDigit = digitExtract(myValue);
break;
case 2:
printf("\nExiting . . . ");
break;
default:
printf("\nPlease enter a valid option!");
}
} while (userOption != 2);
}
void digitExtract(int userValue) {
int tempValue;
int x;
int myArr[10] = { 0 };
tempValue = (userValue < 0) ? -userValue : userValue;
do {
myArr[tempValue % 10]++;
tempValue /= 10;
} while (tempValue != 0);
printf("\nFor %d:\n", userValue);
for (x = 0; x < 10; x++) {
printf("\n%d occurence(s) of %d",myArr[x], x);
}
}
I have gotten the program to display both odd & even digit and it's occurrences.
The only part that I am stuck on is having the program to display ONLY the largest even digit and it's occurrence. Everything I've tried has either broken the program's logic or produces some weird output.
Any hints or ideas on how I should proceed?
Thanks ahead of time.
Run a loop from the largest even digit to smallest even digit.
for (x = 8; x >=0; x-=2)
{
if(myArr[x]>0) //if myArr[x]=0 then x does not exist
{
printf("%d occurs %d times",x,myArr[x]);
break; //we have found our maximum even digit. No need to proceed further
}
}
Note:To optimize you should count and store occurrences of only even digits.
Why do you even use the extra loop? To find the largest even digit in an integer and the number of its occurences, a modification to the first loop would suffice.
Consider the following (untested, but I hope you get the idea):
int tempValue;
int x;
int myArr[10] = { 0 };
int maxNum = 0;
tempValue = (userValue < 0) ? -userValue : userValue;
do {
int currNum = tempValue % 10;
myArr[currNum]++;
tempValue /= 10;
if (currNum % 2 == 0 && currNum > maxNum)
maxNum = currNum;
} while (tempValue != 0);
After this, maxNum should contain the largest even digit, and myArr[maxNum] should be the number of its occurences.
so my task is as follows: Construct a do-while() loop, which continues to prompt the user for an integer, and determines the sum of integers entered, until a prime number is encountered. The prime number should not be included in the sum. Show all variable declarations.
I have all of the variable add up correctly however cannot seem to get the function to stop on a prime number. To try to correct this I made the variable "primecheck" and set it to 2++ thinking that it would be every integer above 2 (obviously not possible but one could hope). any assistance would be much appreciated!
int main (void)
{
int sum = 0, num = 0, i = 0, primecheck = 0, two = 2;
primecheck = two++;
do
{
printf ("Enter an integer: ");
scanf ("%d", &num);
if (num % primecheck == 0 && primecheck != num)
{
sum += num;
}
} while (num % primecheck == 0 && primecheck != num);
i = sum;
printf("%s%d%s", "Sum = ", i, "\n");
}
One possibility would be to introduce a function which performs the primality check, which could be done by using check divisions by all smaller numbers and terminate the loops as soon as a prime number is found. An implementation can be found following this link; the code can be refactored to the follwing function for primality testing. The function returns 1 if n is prime and 0 otherwise. The implementation uses an explicit while loop as the requirements apparently demands it.
int is_prime(int n)
{
int i=3;
int flag=0;
if (n%2==0)
{
return 0;
}
do
{
if (n%i==0)
{
flag=1;
break;
}
i+=2;
}
while (i*i<=n);
return flag;
}