-2

following code is throwing compiling error. I am new to programming and so dont know what else to do. I did as taught in the class but cant get it right. cam anyone please help me solve it?

#include<stdio.h>
#include<cs50.h>

int main(void)
{
   int y; 
do
{
   printf("Minutes: ");
   int Minutes = get_int();
}
while(Minutes< 0);

y= Minutes * 12;
printf("Bottles: %i\n", y);
}

it is throwing following error:

water.c:10:8: error: unused variable 'Minutes' [-Werror,-Wunused-variable]
   int Minutes = get_int();
   ^
water.c:12:7: error: use of undeclared identifier 'Minutes'
while(Minutes< 0);
  ^
water.c:14:4: error: use of undeclared identifier 'Minutes'
y= Minutes * 12;
   ^
    3 errors generated.
make: *** [water] Error 1

3 Answers3

1

You defined Minutes in the scope of the do block. That means it can only be used within that same scope - ie. between the {} enclosing the block.

You are however using the variable outside of that scope (twice in fact).

Instead, define Minutes before the do loop :

int Minutes = 0;
do {
    printf("Minutes: ");
    Minutes = get_int();
}
while(Minutes< 0);

This puts it in the scope of the main function body, so it can be used anywhere in the main function (after its definition).

Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40
  • It is showing following error: water.c:10:8: error: declaration shadows a local variable [-Werror,- Wshadow] int Minutes = get_int(); ^ water.c:6:11: note: previous declaration is here int y, Minutes=0; ^ water.c:10:8: error: unused variable 'Minutes' [-Werror,-Wunused- variable] int Minutes = get_int(); ^ 2 errors generated. make: *** [water] Error 1 ~/workspace/pset1/ $ – Alwira Sheikh Mar 22 '17 at 10:23
  • 1
    The new error is because you still have `int Minutes = get_int();` in the loop meaning `Minutes` is redeclared -- it should be `Minutes = get_int();`. – G.M. Mar 22 '17 at 10:28
0

int Minutes is declared local to the loop body, meaning that the loop condition while(Minutes< 0) has no idea what "Minutes" is.

Simply move the declaration out of the loop, above it.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

This is the answer

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    printf("minutes: ");
    int minutes = get_int();

    printf("bottles: ");
    int bottles = get_int();

    printf("%i\n divided %i\n is %i\n", minutes, bottles, minutes / bottles);
}
pergy
  • 5,285
  • 1
  • 22
  • 36