473,320 Members | 2,006 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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

Why is 'i' so big? I need it to be 1,2,3...
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. int
  3. main()
  4. {
  5.      int i,n,p;
  6.      printf("How many numbers:");
  7.      scanf("%d",&n);
  8.      int v[n];
  9.      for(i=1;i<=n;i++)
  10. {
  11.      printf("n%d="),i;     
  12.      scanf("%d",&v[i]);
  13. }
  14.      printf("N=%d\n\n",n);
  15.      system("PAUSE");
  16. }
  17.  
Dec 30 '10 #1

✓ answered by donbock

Have you followed the advice given by Dheeraj? I think that would have fixed your problem.
Line 11 of your program is:
Expand|Select|Wrap|Line Numbers
  1.      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
Expand|Select|Wrap|Line Numbers
  1.      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.

12 2242
Dheeraj Joshi
1,123 Expert 1GB
I am not aware of such syntax.
Expand|Select|Wrap|Line Numbers
  1. printf("n%d="),i;
  2.  
Try
Expand|Select|Wrap|Line Numbers
  1. printf("%d\n",i);
  2.  
Regards
Dheeraj Joshi
Dec 30 '10 #2
Rabbit
12,516 Expert Mod 8TB
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.
Dec 31 '10 #3
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...
Jan 1 '11 #4
tdlr
22
This shouldn't even compile.
Expand|Select|Wrap|Line Numbers
  1. 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:
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <vector>
  3.  
  4.  int main()
  5.  {
  6.       int i,n,p;
  7.       std::vector<int> v;
  8.       printf("How many numbers:");
  9.       std::cin>>n;
  10.       for(i=1;i<=n;i++)
  11.          {
  12.               std::cout<<i<<"=";     
  13.               std::cin>>p;
  14.               v.push_back(p);
  15.          }
  16.       std::cout<<"N="<<n<<std::endl;
  17.  
  18.       // You might now do this:
  19.       std::cout<<v.at(0);
  20.       // to print the first element
  21.  }
Edit: Here's a c style version that works:
Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <stdio.h>
  3.  int
  4.  main()
  5.  {
  6.       int i,n,p; // p is unused however
  7.       int* v;
  8.       printf("How many numbers:");
  9.       scanf("%d",&n);
  10.       v = (int*) malloc(n*sizeof(int));
  11.       for(i=0;i<n;i++)
  12.          {
  13.               printf("n%d=",i);     
  14.               scanf("%d",&v[i]);
  15.          }
  16.       printf("N=%d\n\n",n);
  17.       free(v);  // Don't forget this
  18.  }
Jan 2 '11 #5
donbock
2,426 Expert 2GB
In what way is i huge?
Jan 4 '11 #6
to donbock:
the value printed by printf("%d",i) which should be 1,2,3..
is instead 528465523,2584654,21576854,....
Jan 4 '11 #7
donbock
2,426 Expert 2GB
Have you followed the advice given by Dheeraj? I think that would have fixed your problem.
Line 11 of your program is:
Expand|Select|Wrap|Line Numbers
  1.      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
Expand|Select|Wrap|Line Numbers
  1.      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.
Jan 4 '11 #8
Dheeraj Joshi
1,123 Expert 1GB
Hi, tdlr
Expand|Select|Wrap|Line Numbers
  1. v = new int[n];
  2.  
In you C version of the code you have mentioned new operator. There is no new operator in C.

Regards
Dheeraj Joshi
Jan 5 '11 #9
tdlr
22
@Dheeraj Joshi:
Of course, you're right. And of course I meant:
Expand|Select|Wrap|Line Numbers
  1. v = (int*) malloc(n*sizeof(int));
  2. /*...*/
  3. free(v)
Jan 5 '11 #10
@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:
Expand|Select|Wrap|Line Numbers
  1. // Shows the numbers appearing more than once in a 
  2. //given array
  3. #include <stdio.h>
  4. int
  5. main()
  6. {
  7.     int i,j,n,t=0,p=0;
  8.     printf("How many numbers do you have:");
  9.     scanf("%d",&n);
  10.     int v[n];
  11.     for(i=0;i<n;i++)
  12. {
  13.     printf("\n n %d = ",i+1);
  14.     scanf("%d",&v[i]);
  15. }
  16.  
  17.     for(i=0;i<n-1;i++)
  18.        for(j=i+1;j<=n;j++)
  19.        if (v[i]>v[j])
  20.        {
  21.        t=v[i];
  22.        v[i]=v[j];
  23.        v[j]=t;
  24.        }       
  25.  printf("\n This numbers occurs more than once: ");
  26.  for(i=1;i<n;i++)
  27.  {
  28. if(v[i]==v[i-1])
  29. if(v[i]!=v[i+1])
  30. {
  31.     printf(" %d",v[i]);
  32.     p++;
  33. }
  34. }
  35. if(p==0)
  36. printf(" every number is unique.");
  37.     printf("\n\n");
  38.     system("PAUSE");
  39. }
  40.  
Tell me what you think!
Jan 25 '11 #11
donbock
2,426 Expert 2GB
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.
Jan 26 '11 #12
Expand|Select|Wrap|Line Numbers
  1. 18.  for(j=i+1;j<=n;j++)
  2.  
  3. 26.  for(i=1;i<n;i++)
  4.         if(i!=(n-1))
  5. {
  6.             if((v[i]==v[i-1])&&(v[i]!=v[i+1]))
  7.     {
  8.     printf(" %d",v[i]);
  9.     p++;
  10.     }
  11. }
  12.         else if(v[i]==v[i-1])
  13.         printf(" %d",v[i]);
should be fine now (scanf is like cin>> in c++)
Jan 26 '11 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

12
by: Steve | last post by:
Hi, I'm getting some output by running a command using os.popen. I need to parse the output and transform it in some sense so that it's 'DB compatible', (i.e I need to store the output in a...
1
by: Jonathan | last post by:
I am getting an error message that other people have gotten. I have done some search and reading enough to see that this error isn't only happening to me. However, I am not able to discern a...
6
by: Michael | last post by:
How can I get X (or another value) from this string "asdfsadfX", basically i want to get what ever is in between the tags and place them in a variable called $www , can anyone help?
1
by: annbb | last post by:
I have a piece of code which resets all the control on a form ..but if I also put an option group on the form and the relevant code in the routine to reset it I get an error message saying that...
7
by: Andy Baxter | last post by:
Is there a way to pass parameters to functions by reference instead of by value in javascript? i.e. if I have code like this: function setPointer(pointer) { pointer=new String("hello world");...
2
by: mika_ella258 | last post by:
the output should be like this Loop Program -------------------- enter 1st integer: enter 2nd integer: enter 3rd integer: enter 4th integer: enter 5th integer:
2
by: gert | last post by:
Can you replace this->value with *this.value in c ?
2
by: dp_pearce | last post by:
I have some code that takes data from an Access database and processes it into text files for another application. At the moment, I am using a number of loops that are pretty slow. I am not a...
5
by: dave816 | last post by:
Sorry for the Excel question in an Access forum...................I don't see an Excel forum and there's probably a reason for that but figured I'd give this a shot anyway. Again sorry, delete if...
1
by: Kristoffer | last post by:
I can't comprehend that this loop isnt working in practise as in my head it makes perfect theoretical sense while(fscanf(input, "%c", &c)==1) { i = 0; while(c!=';') { printf("%c",...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.