C Programming sum of all integer numbers between two integers - c

I'm a newbie!
I'm supposed to get 2 integers from the user, and print the result(sum of all numbers between those two integers).
I also need to make sure that the user typed the right number.
The second number should be bigger than the first one.
And if the condition isn't fulfilled, I have to print "The second number should be bigger than the first one." and get the numbers from the user again until the user types right numbers that meet the condition.
So if I programmed it right, an example of the program would be like this.
Type the first number(integer) : 10
Type the second number(integer) : 1
The second number should be bigger than the first one.
Type the first number(integer) : 1
Type the second number(integer) : 10
Result : 55
End
I think that I have to make two loops, but I can't seem to figure out how.
My English is limited, to help your understanding of this quiz, I'll add my flowchart below.
I tried many different ways I can think of, but nothing seems to work.
This is the code that I ended up with now.
But this doesn't work either.
#include <stdio.h>
void main(void)
{
int a = 0;
int b = 0;
int total_sum = 0;
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
while (a > b) {
printf("The second number should be bigger than the first one.\n");
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
}
while (a <= b) {
total_sum += a;
a++;
}
printf("Result : \n", total_sum);
}

Instead of using loop to sum the numbers, we can use mathematical formula.
Sum of first N integers= N*(N+1)/2
#include <stdio.h>
int main(void)
{
int a = 0;
int b = 0;
int sum;
//Run infinite loop untill a>b
while(1)
{
printf("Type the first number : ");
scanf("%d", &a);
printf("Type the second number : ");
scanf("%d", &b);
if(a>b)
{
printf("The second number should be bigger than the first one.\n");
}
else
{
break;
}
}
//Reduce comlexity of looping
sum=((b*(b+1))-(a*(a-1)))/2;
printf("Result : %d " , sum);
return 0;
}

After corrections your code should run. The community has pointed out many mistakes in your code. Here's an amalgamated solution:
#include <stdio.h>
int main(void)
{
int a = 0;
int b = 0;
int correctInput=0;
int total_sum = 0;
do
{
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
if(a<b)
correctInput=1;
else
printf("The second number should be bigger than the first one.\n");
}
while (correctInput ==0) ;
while (a <= b) {
total_sum += a;
a++;
}
printf("Result : %d \n" , total_sum);
return 0;
}

Factorials are used frequently in probability problems. The factorial of a positive integer n (written n! and pronounced "n factorial") is equal to the product of the positive integers from 1 to n: n! = 1 x 2 x 3 x x n Write a program that takes as input an integer n and computes n!.

Related

Similar approaches to taking user input showing completely different output

As a beginner, I was trying different approaches to code in C(vs code) to learn better. 1st approach went well, but in 2nd approach I got the different output than what i was expected. I was coding to get the sum of two digits. So in 1st approach I got the sum of two digits as output.
#include <stdio.h>
int main()
{
int first_number, second_number;
printf("Enter First Number: ");
scanf("%i", &first_number);
printf("Enter Second Number: ");
scanf("%i", &second_number);
int sum = first_number + second_number;
printf("Your Sum is %i.", sum);
}
But in 2nd approach, instead of getting sum of two digits in output I got number of two digits.
#include <stdio.h>
int main()
{
printf("Enter First Number: ");
int first_number = scanf("%i", &first_number);
printf("Enter Second Number: ");
int second_number = scanf("%i", &second_number);
int sum = first_number + second_number;
printf("Your Sum is %i.", sum);
Please tell why is it happening?
Thank you in advance for answering my question. Have a great day!
The scanf() function returns the number of fields(variables) that were successfully converted and assigned. In your case it's one for each. So 1 is assigned to first_number and second_number, and the sum of both is 2. Remember that first_number and second_number are modified before scanf has returned, so both of these values will be overridden by the scanf return values, which are 1 in your case.
Let's visualize what is happening:
Input
5
10
What Is Happening
// when scanf is still running
first_number = 5;
// after scanf has completed
first_number = 1;
// when scanf is still running
second_number = 10;
// after scanf has completed
second_number = 1;

Printing the number with highest sum of devisors

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.

Finding the Factorial of range between 1 to N

trying to write a program that would find the factorial of range of numbers starting from 1 to N,N being the final Number to find the factorial for, i have written a non-recursive program.it only works for integers 1 and 2 in the loop, i'm not sure how to fix it because the logic seems fine,also i'm somewhat still a beginner,so i know i'm probably missing something that's obvious,but in any case here's the code :
#include<stdio.h>
int main() {
int firstnumber;
int finalnumber;
printf("this is a program to calculate the factorial of numbers between 1 to N\n");
printf("please enter the final number : ");
scanf("%d",&finalnumber);
int i;
int factorial=1;
for (firstnumber=1;firstnumber<=finalnumber;firstnumber++) {
printf("the factorial of %d is : ",firstnumber);
for (i=1;i<=firstnumber;i++) {
factorial=factorial*i;
}
printf("%d \n ",factorial);
}
return 0;
}
You need to initialize factorial before each calculation.
int i;
// delete this
//int factorial=1;
for (firstnumber=1;firstnumber<=finalnumber;firstnumber++) {
printf("the factorial of %d is : ",firstnumber);
// move the declaration here
int factorial=1;
for (i=1;i<=firstnumber;i++) {
factorial=factorial*i;
}
printf("%d \n ",factorial);
}
Your two loops are redundant: you can calculate factorial for number from factorial of number - 1
This is the programme with one loop only. Complexity O(N).
Pay attention that you will get overflow rapidly by using int.
#include<stdio.h>
int main() {
int number;
int finalnumber;
printf("this is a program to calculate the factorial of numbers between 1 to N\n");
printf("please enter the final number : ");
scanf("%d",&finalnumber);
int factorial = 1;
for (number=1; number<=finalnumber; number++) {
printf("the factorial of %d is : ",number);
factorial *= number;
printf("%d \n",factorial);
}
return 0;
}

C Program to find prime number

Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.
EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.
EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
1. You never initialized i (it has indeterminate value - local variable).
2. You never call function is_prime.
And using a loop will be good idea .Comparing to what you have right now.
I just modified your function a little. Here is the code
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
Explanation-
In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don't want to check anymore. So, it will exit the loop.
In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).
If you have any doubts, let me hear them.
I suggest you start with trial division. What is the minimal set of numbers you need to divide by to decide whether a is prime? When can you prove that, if a has a factor q, it must have a smaller factor p? (Hint: it has a prime decomposition.)
Some errors your program had in your prime finding algorithm:
You start the loop with number 1 - this will make all numbers you test to be not prime, because when you test if the modulo of a division by 1 is zero, it's true (all numbers are divisible by 1).
You go through the loop until a, which modulo will also be zero (all number are divisible by themselves).
The condition for a number to be prime is that it must be divisible by 1 and itself. That's it. So you must not test that in that loop.
On main, the error you're getting (control reaches end of non-void function) is because you declare main to return an int.
int main(void)
And to solve that, you should put a return 0; statement on the end of your main function. Bellow, a working code.
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b;
for (b = 2; b < a; b++) {
if (a % b == 0)
return (0);
}
return 1;
}
int main(void)
{
int c, answer;
printf
("Please enter the number you would like to find is prime or not= ");
scanf("%d", &c);
answer = prime(c);
if (answer == 1) {
printf("%d is a prime number \n", c);
} else {
printf("%d is not a prime number\n", c);
}
return 0;
}
On a side note, don't use the CAPSLOCK to write full sentences. Seems like you're yelling.
Mathematically the maximum divisor of a number can be as a large as the square of it, so we just need to loop until sqrt(number).
A valid function would be:
//Function that returns 1 if number is prime and 0 if it's not
int prime(number) {
int i;
for (i = 2; i < sqrt(number); i++) {
if (a % i == 0)
return (0);
}
return 1;
}
#include<stdio.h>
int main()
{
int n , a, c = 0;
printf ("enter the value of number you want to check");
scanf ("%d", &n);
//Stopping user to enter 1 as an input.
if(n==1)
{
printf("%d cannot be entered as an input",n);
}
for(a = 2;a < n; a++)
{
if(n%a==0)
{
c=1;
break;
}
}
if(c==0 && n!=1)
{
printf("%d is a prime number \n",n);
}
else
{
if(c!=0 && n!=1)
{
printf("%d is not a prime number \n",n);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i;
printf("enter the number : ");
scanf("%d",&x);
for ( i=2; i<x;i++){
if ( x % i == 0){
printf("%d",x);
printf(" is not prime number ");
printf("it can be divided by : ");
printf("%d",i);
break;
}[this is best solution ][1]
}
if( i>=x) {
printf("%d",x);
printf(" is prime number");
}
}

C skip a "while" loop?

I have a problem, I tried to write a program to show the whole sum from 1 to 22 and after that, to do 2 while loops. The first one is supposed to perform the sum of some numbers given by the user, as an example: you type 10, 30 and 40 then as you enter a 0 the program sums the first three numbers. Unfortunetly the first while loop is not working. It goes directly to the last while loop where it is supposed to type a decimal numbers like (10.20 30.50 40.55) and after you type 0 again it sum those numbers and add and multipli every entry with 1.19. So far the last loop is working properly, unfortunately the second loop does not, if I move printf and scanf over the while it let me write but just start writing w/o stopping the number I wrote . Thank You in advance!
Here is the code :
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b;
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
return 0;
}
You don't initialise i to any value before entering the loop with
while(i != 0)
i might very well be zero at this point, so your loop won't be entered even once. Initialising i to a non-zero value should fix this particular problem. The same holds for the variable b.
You should turn on warnings in your compiler, so it can show you problems like this one.
The first time the condition of the second while is evaluated, b has undefined value, since it wasn't initialized. The same applies to the third while.
Whether or not both loops are executed is only a question of chance.
Initialize both variables with non-zero values to ensure both whiles are entering. Or use a do-while:
do {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
} while (b != 0);
Don't test b with while, test it after the user enters the number. Then you can use break to exit the loop.
while (1) {
printf("type a number:");
scanf("%i", &b);
if (b == 0) {
break;
}
sum += b;
printf("%i\n", b);
}
while(1) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
if (i == 0.0) {
break;
}
sum1 += i*1.19;
printf("%lf\n", i);
}
Your only issues are initialization: see edits in the code below. (it compiles and runs)
Did you get any compiler warnings for these? If not, you should change your settings so you do.
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b=-1; //initialize (any non-zero value will work)
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {//a initialized in for(...) statement, (this is good)
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) { //b Needs to be initialized before using (done above)
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
i=-1; //initialize i to any non-zero value
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
getchar();
return 0;
}

Resources