C - Increase Integer In Loop - c

I'm trying to increase 0.001f in a loop, so in loop 1 the value is 0.001f, in loop 2 the value is 0.002f
This is what I have (doesn't work since it doesn't include the i in the value and it's not correct):
for (int i = 0; i < 34; i++) {
GRAPHICS::DRAW_RECT(0.825f, ((maxOptions * 0.000f++) + 0.1765f), 0.23f, 0.035f, scrollerColor.r, scrollerColor.g, scrollerColor.b, scrollerColor.a); // Scroller
}
I have tried making a buffer like so, but as expected that didn't work:
int buffer[10];
sprintf(buffer, "0.00%if", i);
How would I do this? ANswers are appreciated!

0.000f++ is invalid syntax, as the postincrement operator cannot be used on constants. It can only be used on an lvalue (i.e. the name of a variable or an expression that represents one).
Assuming you want this value to range from 0.001 to 0.034 you would multiply 0.001 by the loop index, changing the loop to go from 1 to 34 instead of 0 to 33.
for (int i = 1; i <= 34; i++) {
GRAPHICS::DRAW_RECT(0.825f, ((maxOptions * 0.001f * i) + 0.1765f),
0.23f, 0.035f, scrollerColor.r, scrollerColor.g,
scrollerColor.b, scrollerColor.a); // Scroller
}

The variable i is never used inside your loop. Maybe you could tell us where you want to use it, or add more context to the question?
But here's my first raw attempt at an answer anyway:
for (float i = 0; i < 0.034f; i += 0.001f) {
GRAPHICS::DRAW_RECT(0.825f, ((maxOptions * 0.000f++ /* This part has an issue and I can't understand what you mean by it*/) + 0.1765f), 0.23f, 0.035f, scrollerColor.r, scrollerColor.g, scrollerColor.b, scrollerColor.a); // Scroller
}
Due to the way your processor handles floating point arithmetic, this code can result in one more or less loop as pointed out by dbush (thanks!)
You can fix it as follows:
// Include math.h at the top of your code.
for (float i = 0; fabs(i - 0.034f) > 0.0001; i += 0.001f) {
GRAPHICS::DRAW_RECT(0.825f, ((maxOptions * 0.000f++ /* This part has an issue and I can't understand what you mean by it*/) + 0.1765f), 0.23f, 0.035f, scrollerColor.r, scrollerColor.g, scrollerColor.b, scrollerColor.a); // Scroller
}

Related

C program to find the sum of all odd integers up to n using while-loop

My book says for programming using while-loop, we must first initialize with a number, provide the condition mentioning 'while', and then it's to be followed by the statement to partake in the loop until the condition is met as well as to increment value in the loop.
Example :
i = 1;
while(i<=10)
{
s = s + i;
p = p * i;
i++;
}
But, in case of summing of odd numbers program no such incrementing value has been shown.
And, strangely enough(for me), I get correct result w/o the use of i++. I absolutely cannot wrap my head around why that is the case. Is mentioning i++ or i+1 not really a rule within loops?
int s, i, n;
s = 0;
i = 1;
while (i <= n)
{
s = s + i;
i = i + 2;
}
This line is the incrementing value:
i = i + 2;
The first loop increments by 1 with i++. But since you only want the odd numbers, you need to increment by 2.
You can simplify this to:
i += 2;
There is no such rule that we must use i++ in every loop(and for that matter using i as a loop variable).
As #Barmar indicated, you are incrementing i using the line :
i = i + 2;
There are cases where we need to increment by 3, 10, √n, logn, etc.
There are even cases where we need to run a loop backwards hence, we decrement i.
The point is, the value of i must change at some point otherwise we'll end up in an infinite loop.

C error: pointer expected

I made a simple program in C that finds if a number is prime. I am new to C and decided to try to use scanf instead of hardcoded numbers to check. When I run my code:
#include <stdio.h>
typedef int bool;
#define true 1
#define false 0
int main(){
//I am going to check if the "checking" variable is a prime
int checking;
scanf("%d",checking);
//"stopper" is where the for loop will stop
int stopper = checking**0.5 + 1;
//"found" will show if I have found something bad
bool found = false;
for (int i = 2; i < stopper; i++)
{
if (checking % i == 0){found = true; break;}
}
if (!found) {printf("it is prime");}
else {printf("it is not prime");}
}
when I try to compile this with TCC it gives the error (primes.c is the name of the document)
primes.c:12 error: pointer expected
I don't know how to fix this.
EDIT: I just made stopper = checking/2 and the program crashes
int stopper = checking**0.5 + 1;
line 12... what do you expect the ** operator to do?
A * typically performs a multiply, or dereferences a pointer.
The compiler could be interpreting it as follows:
int stopper = checking * (*0.5) + 1;
Of course, trying to dereference a float (*0.5) is bad / impossible, hence the error.
Did you mean:
instead of **, you meant * (multiply)
instead of ** (not a C operator), you meant pow() (raise to the power of)
You also need to be specific - even if you're an expert at precedance, the reader may not be, and you may well be wrong.
If you're not sure what's going on, use braces to be specific, which of the following do you mean?
int stopper = checking * (0.5 + 1);
int stopper = (checking * 0.5) + 1;
int stopper = pow(checking, 0.5) + 1;
int stopper = pow(checking, 0.5 + 1);
If you are indeed after the square root, then as #JeremyP says, invert your thinking - multiply is much less costly than pow():
for (int i = 2; i * i <= checking; i++)
You have two problems in your program:
(1) Replace
int stopper = checking**0.5 + 1;
with
int stopper = checking*0.5 + 1;
(2) Replace
scanf("%d",checking);
with
scanf("%d",&checking);
You should be good to after these corrections.
There's no built in operator to raise a number to the power of another number. There is a function to do that - also a square root function but you don't need them (see below).
x**y
is parsed as
x* (*y)
which is where your pointer error comes from
Instead of trying to find the square root, come at it from the other direction, change your for loop like this
for (int i = 2; i * i <= checking; i++)
Also, as others have said, the scanf is wrong.
scanf("%d",&checking);
// ^- scanf needs a pointer to an int.
Firstly, the scanf is wrong.
Use scanf("%d",&checking);
For finding the square root use math.h library for sqrt function.
int stopper = sqrt(checking) + 1;
There were a lot of typing mistakes in your code. Please, correct your syntax before asking a question.
Ideone link for code

How to Optimize Simple Circular/Rotating Buffer/FIFO Handling for Performance

Hi: I have been ramping up on C and I have a couple philosophical questions based on arrays and pointers and how make things simple, quick, and small or balance the three at least, I suppose.
I imagine an MCU sampling an input every so often and storing the sample in an array, called "val", of size "NUM_TAPS". The index of 'val' gets decremented for the next sample after the current, so for instance if val[0] just got stored, the next value needs to go into val[NUM_TAPS-1].
At the end of the day I want to be able to refer to the newest sample as x[0] and the oldest sample as x[NUM_TAPS-1] (or equivalent).
It is a slightly different problem than many have solved on this and other forums describing rotating, circular, queue etc. buffers. I don't need (I think) a head and tail pointer because I always have NUM_TAPS data values. I only need to remap the indexes based on a "head pointer".
Below is the code I came up with. It seems to be working fine but it raises a few more questions I'd like to pose to the wider, much more expert community:
Is there a better way to assign indexes than a conditional assignment
(to wrap indexes < 0) with the modulus operator (to wrap indexes >
NUM_TAPS -1)? I can't think of a way that pointers to pointers would
help, but does anyone else have thoughts on this?
Instead of shifting the data itself as in a FIFO to organize the
values of x, I decided here to rotate the indexes. I would guess that
for data structures close to or smaller in size than the pointers
themselves that data moves might be the way to go but for very large
numbers (floats, etc.) perhaps the pointer assignment method is the
most efficient. Thoughts?
Is the modulus operator generally considered close in speed to
conditional statements? For example, which is generally faster?:
offset = (++offset)%N;
*OR**
offset++;
if (NUM_TAPS == offset) { offset = 0; }
Thank you!
#include <stdio.h>
#define NUM_TAPS 10
#define STARTING_VAL 0
#define HALF_PERIOD 3
void main (void) {
register int sample_offset = 0;
int wrap_offset = 0;
int val[NUM_TAPS];
int * pval;
int * x[NUM_TAPS];
int live_sample = 1;
//START WITH 0 IN EVERY LOCATION
pval = val; /* 1st address of val[] */
for (int i = 0; i < NUM_TAPS; i++) { *(pval + i) = STARTING_VAL ; }
//EVENT LOOP (SAMPLE A SQUARE WAVE EVERY PASS)
for (int loop = 0; loop < 30; loop++) {
if (0 == loop%HALF_PERIOD && loop > 0) {live_sample *= -1;}
*(pval + sample_offset) = live_sample; //really stupid square wave generator
//assign pointers in 'x' based on the starting offset:
for (int i = 0; i < NUM_TAPS; i++) { x[i] = pval+(sample_offset + i)%NUM_TAPS; }
//METHOD #1: dump the samples using pval:
//for (int i = 0; i < NUM_TAPS; i++) { printf("%3d ",*(pval+(sample_offset + i)%NUM_TAPS)); }
//printf("\n");
//METHOD #2: dump the samples using x:
for (int i = 0; i < NUM_TAPS; i++) { printf("%3d ",*x[i]); }
printf("\n");
sample_offset = (sample_offset - 1)%NUM_TAPS; //represents the next location of the sample to be stored, relative to pval
sample_offset = (sample_offset < 0 ? NUM_TAPS -1 : sample_offset); //wrap around if the sample_offset goes negative
}
}
The cost of a % operator is the about 26 clock cycles since it is implemented using the DIV instruction. An if statement is likely faster since the instructions will be present in the pipeline and so the process will skip a few instructions but it can do this quickly.
Note that both solutions are slow compared to doing a BITWISE AND operation which takes only 1 clock cycle. For reference, if you want gory detail, check out this chart for the various instruction costs (measured in CPU Clock ticks)
http://www.agner.org/optimize/instruction_tables.pdf
The best way to do a fast modulo on a buffer index is to use a power of 2 value for the number of buffers so then you can use the quick BITWISE AND operator instead.
#define NUM_TAPS 16
With a power of 2 value for the number of buffers, you can use a bitwise AND to implement modulo very efficiently. Recall that bitwise AND with a 1 leaves the bit unchanged, while bitwise AND with a 0 leaves the bit zero.
So by doing a bitwise AND of NUM_TAPS-1 with your incremented index, assuming that NUM_TAPS is 16, then it will cycle through the values 0,1,2,...,14,15,0,1,...
This works because NUM_TAPS-1 equals 15, which is 00001111b in binary. The bitwise AND resulst in a value where only that last 4 bits to be preserved, while any higher bits are zeroed.
So everywhere you use "% NUM_TAPS", you can replace it with "& (NUM_TAPS-1)". For example:
#define NUM_TAPS 16
...
//assign pointers in 'x' based on the starting offset:
for (int i = 0; i < NUM_TAPS; i++)
{ x[i] = pval+(sample_offset + i) & (NUM_TAPS-1); }
Here is your code modified to work with BITWISE AND, which is the fastest solution.
#include <stdio.h>
#define NUM_TAPS 16 // Use a POWER of 2 for speed, 16=2^4
#define MOD_MASK (NUM_TAPS-1) // Saves typing and makes code clearer
#define STARTING_VAL 0
#define HALF_PERIOD 3
void main (void) {
register int sample_offset = 0;
int wrap_offset = 0;
int val[NUM_TAPS];
int * pval;
int * x[NUM_TAPS];
int live_sample = 1;
//START WITH 0 IN EVERY LOCATION
pval = val; /* 1st address of val[] */
for (int i = 0; i < NUM_TAPS; i++) { *(pval + i) = STARTING_VAL ; }
//EVENT LOOP (SAMPLE A SQUARE WAVE EVERY PASS)
for (int loop = 0; loop < 30; loop++) {
if (0 == loop%HALF_PERIOD && loop > 0) {live_sample *= -1;}
*(pval + sample_offset) = live_sample; //really stupid square wave generator
//assign pointers in 'x' based on the starting offset:
for (int i = 0; i < NUM_TAPS; i++) { x[i] = pval+(sample_offset + i) & MOD_MASK; }
//METHOD #1: dump the samples using pval:
//for (int i = 0; i < NUM_TAPS; i++) { printf("%3d ",*(pval+(sample_offset + i) & MOD_MASK)); }
//printf("\n");
//METHOD #2: dump the samples using x:
for (int i = 0; i < NUM_TAPS; i++) { printf("%3d ",*x[i]); }
printf("\n");
// sample_offset = (sample_offset - 1)%NUM_TAPS; //represents the next location of the sample to be stored, relative to pval
// sample_offset = (sample_offset < 0 ? NUM_TAPS -1 : sample_offset); //wrap around if the sample_offset goes negative
// MOD_MASK works faster than the above
sample_offset = (sample_offset - 1) & MOD_MASK;
}
}
At the end of the day I want to be able to refer to the newest sample as x[0] and the oldest sample as x[NUM_TAPS-1] (or equivalent).
Any way you implement this is very expensive, because each time you record a new sample, you have to move all the other samples (or pointers to them, or an equivalent). Pointers don't really help you here. In fact, using pointers as you do is probably a little more costly than just working directly with the buffer.
My suggestion would be to give up the idea of "remapping" indices persistently, and instead do it only virtually, as needed. I'd probably ease that and ensure it is done consistently by writing data access macros to use in place of direct access to the buffer. For example,
// expands to an expression designating the sample at the specified
// (virtual) index
#define SAMPLE(index) (val[((index) + sample_offset) % NUM_TAPS])
You would then use SAMPLE(n) instead of x[n] to read the samples.
I might consider also providing a macro for adding new samples, such as
// Updates sample_offset and records the given sample at the new offset
#define RECORD_SAMPLE(sample) do { \
sample_offset = (sample_offset + NUM_TAPS - 1) % NUM_TAPS; \
val[sample_offset] = sample; \
} while (0)
With regard to your specific questions:
Is there a better way to assign indexes than a conditional assignment (to wrap indexes < 0) with the modulus operator (to wrap
indexes > NUM_TAPS -1)? I can't think of a way that pointers to
pointers would help, but does anyone else have thoughts on this?
I would choose modulus over a conditional every time. Do, however, watch out for taking the modulus of a negative number (see above for an example of how to avoid doing so); such a computation may not mean what you think it means. For example -1 % 2 == -1, because C specifies that (a/b)*b + a%b == a for any a and b such that the quotient is representable.
Instead of shifting the data itself as in a FIFO to organize the values of x, I decided here to rotate the indexes. I would guess that
for data structures close to or smaller in size than the pointers
themselves that data moves might be the way to go but for very large
numbers (floats, etc.) perhaps the pointer assignment method is the
most efficient. Thoughts?
But your implementation does not rotate the indices. Instead, it shifts pointers. Not only is this about as expensive as shifting the data themselves, but it also adds the cost of indirection for access to the data.
Additionally, you seem to have the impression that pointer representations are small compared to representations of other built-in data types. This is rarely the case. Pointers are usually among the largest of a given C implementation's built-in data types. In any event, neither shifting around the data nor shifting around pointers is efficient.
Is the modulus operator generally considered close in speed to conditional statements? For example, which is generally faster?:
On modern machines, the modulus operator is much faster on average than a conditional whose result is difficult for the CPU to predict. CPUs these days have long instruction pipelines, and they perform branch prediction and corresponding speculative computation to enable them to keep these full when a conditional instruction is encountered, but when they discover that they have predicted incorrectly, they need to flush the whole pipeline and redo several computations. When that happens, it's a lot more expensive than a small number of unconditional arithmetical operations.

Structure with formulas

My problem is that the correct value that is suppose to be stored in the data[i].Px isn't stored and the same with the data[i].Py.
My formula in the do-while is faulty or must be.
The formula should calculate the 'position' of a projectile.
Vx and Vy is the initial velocities/values and Px and Py is the positions (in the x and y directions)
typedef struct
{
float t, Vx, Vy, Px, Py;
}datapoint;
steps = 100
data[0].Vx = (20*(cos(30))); //in my program 30 is in radians
data[0].Vy = (20*(sin(30));
data[0].Px = 0;
data[0].Py = 0;
do
{
i=1;
printf("Time: %.2f\t",i*q5);
//X
data[i].Vx = data[i-1].Vx;
data[i].Px = ((data[i-1].Px) + ((data[i].Vx) * i));
printf("X = %.2f\t",data[i].Px);
//Y
data[i].Vy= data[i-1].Vy - (9.81)*i;
data[i].Py= data[i-1].Py + (data[i].Vy * i);
printf("Y = %.2f\t", data[i].Py);
printf("\n");
i++;
}while(**(data[i].Py >0)** && (i<=steps));
In the while condition of the do while loop, do you want to have
while((data[i].Py > 0) && (i <= steps));
Oh just saw a flaw. Why are you initializing i=1 inside the loop! Its value will never go beyond 2.
(I just skimmed through your question, so if this doesn't work I will check it thoroughly).
Judging from the notation used (since the declaration is not shown), data is an array of datapoint. Then data->Px is equivalent to data[0].Px.
You don't show how data[0] is initialized.
i never gets beyond 2. Unless steps is 2, the loop won't terminate because of the i <= steps condition. Since the value in data[0].Py (aka data->Py) is not modified in the loop, you have an infinite loop unless data[0].Py is negative or zero on entry to the loop.
You should look askance at a do { ... } while (...); loop. They aren't automatically wrong; but they are used far less often than while or for loops.
Generally, you will get better answers on StackOverflow if you produce a minimal compilable and runnable program (or a minimal non-compilable program that illustrates the syntax error if you are having problems making the program compilable). And 'minimal' means that nothing can be removed without altering the behaviour.

Are loops with and without parenthesis handled differently in C?

I was stepping through some C/CUDA code in the debugger, something like:
for(uint i = threadIdx.x; i < 8379; i+=256)
sum += d_PartialHistograms[blockIdx.x + i * HISTOGRAM64_BIN_COUNT];
And I was utterly confused because the debugger was passing by it in one step, although the output was correct. I realised that when I put curly brackets around my loop as in the following snippet, it behaved in the debugger as expected.
for(uint i = threadIdx.x; i < 8379; i+=256) {
sum += d_PartialHistograms[blockIdx.x + i * HISTOGRAM64_BIN_COUNT];
}
So is are parenthesis-free for loops treated differently in C or in the debugger, or perhaps it is particular to CUDA.
Thanks
The debugger executes one statement at a time.
Check this out:
int sum = 0; /* one assignment statement */
for (int k = 0; k < 10; k++) sum += k; /* one for statement */
and compare with this
int sum = 0; /* one assignment statement */
for (int k = 0; k < 10; k++)
{ /* for statement with the body
in a block of statements */
sum += k; /* assignment statement */
}
In the first example above, the sum += k is an integral part of the for statement; in the 2nd example, it is a full statement on its own.
There isn't any execution difference between a single statement following the "for" or a block with one statement in it. Looking at your code though, do you realise that i isn't actually incremented? Perhaps you meant to put i+=256.
As far as the debugger is concerned the brackets constitute something else to "move into" whereas the single line is just that, a single line (just like an if statement with no block).

Resources