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;
Related
I'm coding in c and have been attempting to make an average calculator, as i am new to coding and only just starting and my code won't work after i input a number for it. the way it should work is you input a number, the code keeps track of the overall number and the amount of numbers entered and prints out the average, doing this all in "do while" loop
my code:
int main()
{
float overall = 0;
float entered = 0;
float times = 0;
float avg = 0;
printf("AVERAGE CALULATOR\n\npress 0 when complete\n\n");
do{
printf("current average: %.2f\n\n", avg);
printf("input number: ");
scanf("%f", entered);
overall += entered;
times++;
avg = overall / times;
}while(entered != 0);
return 0;
}
pleae inform me of incorrect code if you find it
You just forgot the (&) in scanf after the comma.
scanf("%f", &entered);
Scanf needs a pointer to your adress.
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!.
I am writing a C program to repeat a series of question specified times. I ask user to enter the number of attempts they want and then I run the following while loop based on their number, but the problem is the loop keeps repeating. It does not stop at the specified number of attempt. Here is the code:
#include <stdio.h>
int main(void){
int num1,num2,high,low,average,subtotal,total_aver;
printf("Enter number of tries you want:");
scanf("%d", &num1);
while (num1 < num1 + 1) {
printf("Try number: ");
scanf("%d", &num2);
printf("Enter high ");
scanf("%d", &high);
printf("Enter low ");
scanf("%d", &low);
subtotal = high + low;
total_aver = subtotal / 2;
printf("Average temperature is: %d", total_aver);
}
}
If user enters 3 for number of tries then the program should ask those question in inside the loop three times, but it keeps repeating without ending.
while (num1 < num1 + 1) // condition is never false
Well this is infinite loop . It will continue and continue.
Write loop like this if you want to iterate number of times -
int i=0;
while(i<num1){
// your code
i++;
}
Or without any extra variable -
while(num1>0){
// your code
num1--;
}
This happens because the condition in the while is wrong.
Infact, assigning to num1 to any value, it will exit when num1 will be equal to num1+1. Is this impossibile, isn't it? You have to use another variable to take count of times you repeat the loop.
Fix this way:
int count=0;
while(count<num+1){
//your code
count=count+1;
}
My friend and I are trying to build a program together, but it just doesn't seem to be working. Neither of us have much experience with C, so we just can't spot the issue... Any advice or help would be much appreciated!
Apologies for the slightly awkward lyrics?
[Edit] The problem is that when we input values, we get ridiculous figures like 4586368.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
void main()
{
int room[20] = {};
int i;
int rooms = 0;
char option = 0;
int lights = 0;
int hrsUsed = 0;
int Telly = 0;
int TVWatt =0;
int sumTV;
int TVuse = 0;
int Computer = 0;
int compWatt = 0;
int compUsed = 0;
int compTotal;
int kwH_lights;
int fridge = 0;
int washLoad = 0;
int dryerLoad = 0, dishLoad = 0, cookLoad = 0;
int showeruse = 0;
int total_kWh;
printf("Enter number of rooms");
scanf_s("%d", &rooms);
for(i=0;i<rooms;i++)
{
printf("input average wattage of lights");
scanf_s("%d", &lights);
lights=lights/1000;
printf("input number of hours use/day (average)");
scanf_s("%d", &hrsUsed);
kwH_lights=((lights*hrsUsed)*365);
printf("input number of TVs");
scanf_s("%d", &Telly);
printf("input average wattage");
scanf_s("%d", &TVWatt);
printf("input average use a day");
scanf_s("%d", &TVuse);
sumTV=((Telly*(TVWatt/1000))*TVuse)*365;
}
printf("Input number of fridge/freezer");
scanf_s("%d",&fridge);
fridge=(fridge*2)*365;
printf("input number of Computers and/or video game consoles in the house");
scanf_s("%d", &Computer);
for(i=0;i<Computer;i++) {
printf("input wattage");
scanf_s("%d", &compWatt);
printf("input average hrs used/day");
scanf_s("%d", &compUsed);
compTotal=((compWatt/1000)*compUsed)*365;
}
printf("Input average number of washing machine loads /day");
scanf_s("%d",&washLoad);
washLoad=washLoad*365;
printf("Input average number of clothes dryer loads/day");
scanf_s("%d",&dryerLoad);
dryerLoad=(dryerLoad*3)*365;
printf("Input average number of dishwasher loads/day");
scanf_s("%d",&dishLoad);
dishLoad=(dishLoad*1.5)*365;
printf("Input average cooking load/day");
scanf_s("%d",&cookLoad);
cookLoad=(cookLoad*7)*365;
printf("Input average hrs/day of shower usage");
scanf_s("%d",&showeruse);
showeruse=(showeruse*7)*365;
total_kWh=((kwH_lights)+(sumTV)+(fridge)+(compTotal)+(dryerLoad)+(dishLoad)+(cookLoad)+(showeruse));
printf("Total= %d", &total_kWh);
}
You should change this:
printf("Total= %d", &total_kWh);
to that:
printf("Total= %d", total_kWh);
Same is true for all your other integer variables.
There were quite a few mistakes in your code:
you printed the memory-address instead of result value (don't use & with printf if your variable is a plain int)
the computer for-loop had no curly brackets (so only the printf statement was looped)
results were not summed up (in all loops you've just overwritten your inputs from the last loop)
the rooms[] Array was never used - a few other variables also (possible error source, if you wanted to use them and just forgot it)
the result from a multiplication with 1.5 will hold a double value - you should cast that back to int (dishLoad)
The bold mistake is probably that one, why your values were wrong...
Also notice: The 'average number of washing machine loads/clothes dryer loads/ dishwasher loads' should better be asked by week or month... Or should hold Floating Point values: Because everyone I know don't use the washing machine and clothes dryer every day multiple times. So now you can't enter something like once a week (which would be an factor of 0.14, but is not enterable cause all values are stored as int).
Here Comes the code with everything fixed, I could found:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int main(int argc, char** argv){
int i = 0;
int rooms = 0;
int lights = 0;
int hrsUsed = 0;
int Telly = 0;
int TVWatt =0;
int sumTV = 0;
int TVuse = 0;
int Computer = 0;
int compWatt = 0;
int compUsed = 0;
int compTotal= 0;
int kwH_lights = 0;
int fridge = 0;
int washLoad = 0;
int dryerLoad = 0, dishLoad = 0, cookLoad = 0;
int showeruse = 0;
int total_kWh = 0;
printf("Enter number of rooms: ");
scanf_s("%d", &rooms);
for(i=0;i<rooms;i++){
printf("A few questions about room %d\n", i+1);
printf("input average wattage of lights: ");
scanf_s("%d", &lights);
lights+=lights/1000;
printf("input number of hours use/day (average): ");
scanf_s("%d", &hrsUsed);
kwH_lights+=((lights*hrsUsed)*365);
printf("input number of TVs: ");
scanf_s("%d", &Telly);
printf("input average wattage: ");
scanf_s("%d", &TVWatt);
printf("input average use a day: ");
scanf_s("%d", &TVuse);
sumTV+=((Telly*(TVWatt/1000))*TVuse)*365;
}
printf("Input number of fridge/freezer: ");
scanf_s("%d",&fridge);
fridge=(fridge*2)*365;
printf("input number of Computers and/or video game consoles in the house: ");
scanf_s("%d", &Computer);
for(i=0;i<Computer;i++){
printf("A few questions about computer %d\n", i+1);
printf("input wattage: ");
scanf_s("%d", &compWatt);
printf("input average hrs used/day: ");
scanf_s("%d", &compUsed);
compTotal += ((compWatt/1000)*compUsed)*365;
}
printf("Input average number of washing machine loads/day: ");
scanf_s("%d",&washLoad);
washLoad=washLoad*365;
printf("Input average number of clothes dryer loads/day: ");
scanf_s("%d",&dryerLoad);
dryerLoad=(dryerLoad*3)*365;
printf("Input average number of dishwasher loads/day: ");
scanf_s("%d",&dishLoad);
dishLoad=(int)((dishLoad*1.5)*365);
printf("Input average cooking load/day: ");
scanf_s("%d",&cookLoad);
cookLoad=(cookLoad*7)*365;
printf("Input average hrs/day of shower usage: ");
scanf_s("%d",&showeruse);
showeruse=(showeruse*7)*365;
total_kWh=((kwH_lights)+(sumTV)+(fridge)+(compTotal)+(dryerLoad)+(dishLoad)+(cookLoad)+(showeruse));
printf("Total= %d\n", total_kWh);
system("Pause");
return 0;
}
I hope it helps you out - if you got any questions left, feel free to ask.
My first step would be to correct the second for loop { } ... fix this and ask again.
[EDIT]
your calculations with usages of int values divided by other ints (compwatt / 1000) ... are you sure your idea of using int is correct?
or:
cookLoad=(cookLoad*7)*365;
why multiplying with 7 AND 365? should not the average / day be multiplied by 365 only?
For more readability of your code, you can employ compound assignment operators as below,
Operator Name Syntax Meaning
-------------------------------------------------
Addition assignment a += b a = a + b
Subtraction assignment a -= b a = a - b
Multiplication assignment a *= b a = a * b
Division assignment a /= b a = a / b
#include <stdio.h>
#include <conio.h>
main() {
float num1, num2, num3, num4, num5, sum;
printf("Enter a Number between");
fflush;
scanf("%f",&num1);
fflush;
printf("Enter a Number between");
scanf("%f",&num2);
fflush;
printf("Enter a Number between");
scanf("%f",&num3);
fflush;
printf("Enter a Number between");
scanf("%f",&num4);
fflush;
printf("Enter a Number between");
scanf("%f",&num5);
fflush;
sum = num1 + num2 + num3 + num4 + num5;
printf("The sum of the five numbers you have entered is %f",sum);
getch();
}
I am a newbie in c programming. We have an assignment and I have created the above code. But we need a shorter solution. The user must input five numbers and display the sum. Can you please help me to translate this code using do while function or post test loop. Thank you very much in advance!
You can use a cycle to read 5 values and accumulate their sum. I prefer to leave you with this hint only because this seems like a homework assignment. You may reuse the same variable reading 5 different inputs and have a separate variable in which you accumalate the sum. You can also use a for cycle instead of the do... while you seem to be using.
Use a for loop to input numbers (say 5 in this case) and add it with value stored in sum in each iteration.
int num , sum = 0;
for(int i = 0; i < 5; i++)
{
scanf("%d", &num);
sum += num;
}
When someone asks me to do their homework for them, I enjoy coming up with a slightly convoluted, but functionally correct answer. :)
#include <stdio.h>
#include <conio.h>
int main()
{
float numbers[5] = {0.0F};
float sum = 0.0F;
int count = 5;
while(count --> 0)
{
printf("Enter a number for entry %d: ", 5-count);
scanf("%f",numbers+count);
sum += numbers[count];
}
printf("The sum is %f\n", sum);
getch();
return 0;
}