Array Arithmetic in C: Incrementing Integers in an Array

  • Thread starter Thread starter pivoxa15
  • Start date Start date
  • Tags Tags
    Arithmetic Array
Click For Summary
Incrementing elements in an array in C using the syntax f[i]+=1 is valid, provided that the index i is within the bounds of the array, specifically between 0 and 4 for an array defined as int f[5]. While a C compiler allows the use of out-of-bounds indices, doing so can lead to undefined behavior and difficult-to-trace bugs. Testing code snippets, such as a simple loop that increments array values, is encouraged to clarify understanding and ensure correct implementation. A sample code demonstrates how to initialize an array, iterate through it, and increment its elements safely.
pivoxa15
Messages
2,250
Reaction score
1
int f[5];

Is it possible to do

f+=1;

inside a valid for loop?

If not than how can I increment integers stored in an arrary for each i in C?

Thanks
 
Technology news on Phys.org
I don't see anything wrong with it, but I tried it and it works just fine.
 
pivoxa15 said:
int f[5];
Is it possible to do
f+=1;


Sure, so long as i has a valid value for an index to that array, namely in the range 0...4.

Actually, a C compiler will cheerfully let you use a value of i outside that range, but then you'll be incrementing the contents of some memory location outside the array. This sort of thing produces bugs that can be very difficult to track down unless you step through the code with a debugger.
 
One of the best ways to learn C is to test these sorts of questions.

Code:
#include <stdio.h>

main()
{
  int f[5]={0}, i;
  
  for(i=0;i<5;i++)
  {
	printf("               i = %d \n", i);
	printf("            f[i] = %d \n", f[i]);
	f[i]+=i;
        printf("incremented f[1] = %d \n", f[i]);
  }

}

Don't be afraid to test these things when you have a question. A simple program like the one above will usually clear things up in a jiffy.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 4 ·
Replies
4
Views
6K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 32 ·
2
Replies
32
Views
3K
  • · Replies 25 ·
Replies
25
Views
2K
  • · Replies 13 ·
Replies
13
Views
5K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
Replies
1
Views
2K