Array Arithmetic in C: Incrementing Integers in an Array

  • Thread starter Thread starter pivoxa15
  • Start date Start date
  • Tags Tags
    Arithmetic Array
AI Thread 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.
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
I tried a web search "the loss of programming ", and found an article saying that all aspects of writing, developing, and testing software programs will one day all be handled through artificial intelligence. One must wonder then, who is responsible. WHO is responsible for any problems, bugs, deficiencies, or whatever malfunctions which the programs make their users endure? Things may work wrong however the "wrong" happens. AI needs to fix the problems for the users. Any way to...
Back
Top