The value of i is huge in this for loop !?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • FlamurKasa
    New Member
    • Dec 2010
    • 5

    #1

    The value of i is huge in this for loop !?

    Why is 'i' so big? I need it to be 1,2,3...
    Code:
    #include <stdio.h>
    int
    main()
    {
         int i,n,p;
         printf("How many numbers:");
         scanf("%d",&n);
         int v[n];
         for(i=1;i<=n;i++)
    {
         printf("n%d="),i;     
         scanf("%d",&v[i]);
    }
         printf("N=%d\n\n",n);
         system("PAUSE");
    }
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    I am not aware of such syntax.
    Code:
    printf("n%d="),i;
    Try
    Code:
    printf("%d\n",i);
    Regards
    Dheeraj Joshi

    Comment

    • Rabbit
      Recognized Expert MVP
      • Jan 2007
      • 12517

      #3
      If I remember correctly, doesn't C instantiated all variables at the beginning regardless of where it was declared? That's probably what's causing it.

      Comment

      • FlamurKasa
        New Member
        • Dec 2010
        • 5

        #4
        to Dheeraj Joshi:
        It prints the current number(n) and its value, example:
        n1=1
        n2=2
        ...

        to Rabbit:
        how can I fix it???
        normally the value of i should be 1,2,3,...; if you test it you get big numbers, but the programs runs perfectly if you enter 3 it loops 3 times ?!?! I am confused ?! Please test it if I'm not clear...

        Comment

        • tdlr
          New Member
          • Jan 2011
          • 22

          #5
          This shouldn't even compile.
          Code:
          int v[n];
          n needs to be a const value here and already be initialized at compile time.

          Instead, this works and makes also use of the C++ style functions, which are a lot easier to use and safer:
          Code:
          #include <iostream>
          #include <vector>
          
           int main()
           {
                int i,n,p;
          	  std::vector<int> v;
                printf("How many numbers:");
                std::cin>>n;
                for(i=1;i<=n;i++)
          		 {
          			  std::cout<<i<<"=";     
          			  std::cin>>p;
          			  v.push_back(p);
          		 }
                std::cout<<"N="<<n<<std::endl;
          
          	  // You might now do this:
          	  std::cout<<v.at(0);
          	  // to print the first element
           }
          Edit: Here's a c style version that works:
          Code:
           
          #include <stdio.h>
           int
           main()
           {
                int i,n,p; // p is unused however
                int* v;
                printf("How many numbers:");
                scanf("%d",&n);
                v = (int*) malloc(n*sizeof(int));
                for(i=0;i<n;i++)
          		 {
          			  printf("n%d=",i);     
          			  scanf("%d",&v[i]);
          		 }
                printf("N=%d\n\n",n);
                free(v);  // Don't forget this
           }
          Last edited by tdlr; Jan 5 '11, 07:27 AM. Reason: Corrected c version. Thanks to Dheeraj Joshi.

          Comment

          • donbock
            Recognized Expert Top Contributor
            • Mar 2008
            • 2427

            #6
            In what way is i huge?

            Comment

            • FlamurKasa
              New Member
              • Dec 2010
              • 5

              #7
              to donbock:
              the value printed by printf("%d",i) which should be 1,2,3..
              is instead 528465523,25846 54,21576854,... .

              Comment

              • donbock
                Recognized Expert Top Contributor
                • Mar 2008
                • 2427

                #8
                Have you followed the advice given by Dheeraj? I think that would have fixed your problem.
                Line 11 of your program is:
                Code:
                     printf("n%d="),i;
                Notice that ,i is outside the parentheses. This means that i is not passed to printf. Instead, printf prints whatever garbage happens to be on the stack. When printf returns the compiler runs into the comma operator, which is effectively a semicolon. Then the compiler finds a statement consisting of a bare i; this is effectively a null statement (nop). Perhaps you are used to cout (in C++); printf works differently.

                Another issue is that this printf is inside the loop and it doesn't emit a newline. This means that if the code were otherwise working and n were 5, the output would be "n1=n2=n3=n4=n5 =" -- the concatenation of all the i values.

                If you really want the output to be
                n1=1
                n2=2
                ...
                then you want
                Code:
                     printf("n%d=%d\n",i,i);
                but I don't know why you want to print the value of i twice.

                By the way, when you declare an array as v[n] then the array index must be between 0 and n-1. Your index ranges between 1 and n. The last array access goes off the end of the array -- that's undefined behavior.

                Comment

                • Dheeraj Joshi
                  Recognized Expert Top Contributor
                  • Jul 2009
                  • 1129

                  #9
                  Hi, tdlr
                  Code:
                  v = new int[n];
                  In you C version of the code you have mentioned new operator. There is no new operator in C.

                  Regards
                  Dheeraj Joshi

                  Comment

                  • tdlr
                    New Member
                    • Jan 2011
                    • 22

                    #10
                    @Dheeraj Joshi:
                    Of course, you're right. And of course I meant:
                    Code:
                    v = (int*) malloc(n*sizeof(int));
                    /*...*/
                    free(v)

                    Comment

                    • FlamurKasa
                      New Member
                      • Dec 2010
                      • 5

                      #11
                      @donbock
                      Finally a solution!(sorry for my late response)
                      You found my mistake thank you very much, and thanks everyone else for trying.

                      As for your other advices, they are not so true:
                      you state that <the output would be "n1=n2=n3=n4=n5 =">
                      let me point to the next line - scanf
                      after each value given the program goes automatically to a new line.
                      The purpose of the loop was store numbers from the user into v[n], so I don't need to print the value of i 2 times.
                      I just want the user to know at which number he is (n2,n6, n99...). I think you got the point.

                      And yes i in v[i] must start at zero, I knew it but I was rushing.

                      The final version of the complete code:
                      Code:
                      // Shows the numbers appearing more than once in a 
                      //given array
                      #include <stdio.h>
                      int
                      main()
                      {
                          int i,j,n,t=0,p=0;
                          printf("How many numbers do you have:");
                          scanf("%d",&n);
                          int v[n];
                          for(i=0;i<n;i++)
                      {
                          printf("\n n %d = ",i+1);
                          scanf("%d",&v[i]);
                      }
                      
                          for(i=0;i<n-1;i++)
                             for(j=i+1;j<=n;j++)
                             if (v[i]>v[j])
                             {
                             t=v[i];
                             v[i]=v[j];
                             v[j]=t;
                             }       
                       printf("\n This numbers occurs more than once: ");
                       for(i=1;i<n;i++)
                       {
                      if(v[i]==v[i-1])
                      if(v[i]!=v[i+1])
                      {
                          printf(" %d",v[i]);
                          p++;
                      }
                      }
                      if(p==0)
                      printf(" every number is unique.");
                          printf("\n\n");
                          system("PAUSE");
                      }
                      Tell me what you think!

                      Comment

                      • donbock
                        Recognized Expert Top Contributor
                        • Mar 2008
                        • 2427

                        #12
                        Line 10. FYI, a C89 compiler would flag this line as an error. That version of the language doesn't allow declarations to appear below executable statements. That version of the compiler doesn't support run-time specification of array size. You might want to add a comment to announce this limitation. Better would be to use conditional compilation to execute a #error if compiled with the wrong compiler version.

                        Lines 13-14. I realize now that you expect the scanf characters to be echoed to stdout. I'm not familiar enough with scanf to know if that is a portable assumption. Perhaps one of the other experts can tell us.

                        Lines 18-23. j will count up to n. In that last iteration the references to v[j] go beyond the end of the array.

                        Line 29. When i==n-1, v[i+1] goes beyond the end of the array.

                        Comment

                        • FlamurKasa
                          New Member
                          • Dec 2010
                          • 5

                          #13
                          Code:
                          18.  for(j=i+1;j<=n;j++)
                          
                          26.  for(i=1;i<n;i++)
                                  if(i!=(n-1))
                          {
                                      if((v[i]==v[i-1])&&(v[i]!=v[i+1]))
                              {
                              printf(" %d",v[i]);
                              p++;
                              }
                          }
                                  else if(v[i]==v[i-1])
                                  printf(" %d",v[i]);
                          should be fine now (scanf is like cin>> in c++)
                          Last edited by FlamurKasa; Jan 26 '11, 11:51 AM. Reason: add a comment and corrected a last bug

                          Comment

                          Working...