Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I properly declare this variable?

I am trying to write a program in C that takes a positive integer that is input and then counts down to zero and back up to the number by 1. I am getting errors when trying to run the code saying that my variables usernum and usernum2 are undeclared. In the main function I declare them both as integers so what am I doing wrong?

#include <stdio.h>
`
void loop_down_to_zero(){
    while (usernum2 >= 0){
       printf("%d\n", &usernum2);
       usernum2--;
       if (usernum2 ==0) {
          printf("****\n");
       }
    }
}
void loop_up_to_zero(){
    while (usernum2 < usernum){
       usernum2++;
       printf("%d\n", usernum2);
    }
}

int main(int argc, char * argv[]) {
   int usernum;
   int usernum2;
   usernum2 = usernum;
   printf("Enter a positive integer: \n");
   scanf("%d", &usernum);
   while (usernum <= 0){
      printf("Error, enter a positive integer: \n");
      scanf("%d", &usernum);
   }
   if (usernum > 0) {
      loop_down_to_zero();
      loop_up_to_zero();
   }
}
`

I tried moving the void functions below main because I am still trying to figure out some of the syntax in C but it did not appear to have much of an impact.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the line usernum2 = usernum you’re trying to assign value in usernum to usernum2. But in usernum there’s no value at that moment, because you’ve only declared the variable usernum, you’ve never defined it. Example of declaration: int usernum;. Example of definition: int usernum = 0;

Also, in your line printf("%d\n", &usernum2); you shouldn’t pass the address, you should pass the value: printf("%d\n", usernum2);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading