for (int i = 0; i < n+1; ++i)
{
sum = sum + i;
}
for (int i = 0; i < n+1; i++)
{
sum = sum + i;
}
Two paragraphs are different because of ++i and i++ in function call argument.
but it works like i only starts with 0. Why does even ++i starts with 0?
There are absolutely no difference between these two snippets. i++ vs ++i only matters when mixed with other operators in the same expression. Which is a bad idea most of the time, since i++/++i comes with a side effect.
A generic for loop like
for (a; b; c)
{
d
}
is equivalent to
{
a;
while (b)
{
d;
c;
}
}
Note how the "increment" expression c is after the main statement of the loop body.
For your loops that means they will be equivalent to:
{
int i = 0;
while (i < n+1)
{
sum = sum + i;
i++; // or ++i
}
}
Since the increment of i doesn't happen until after you calculate sum there's no practical difference between the loops. Both will lead to the exact same result.
On a side-note: Remember to explicitly initialize sum to zero before the loop, or it might have an indeterminate value (that could be seen as garbage).
The two for loops you posted will behave exactly the same. The reason they are equivalent, which also answers your question of why both loops start from 0, is that the increment (i++ or ++i) only happens after the {expression} in {} has executed, and after every time it has executed.
Your code would produce identical results.
The following code would produce different results.
int i = 0;
while (i < 5) {
printf("%d\n", ++i);
}
// 1
// 2
// 3
// 4
// 5
i = 0;
while (i < 5) {
printf("%d\n", i++);
}
// 0
// 1
// 2
// 3
// 4
In my example the reason the bottom for-loop prints out 0 and the top for-loop doesn't is because printf and i++/++i form a combined expression where in the top i is incremented and then accessed from memory whereas in the bottom loop i is access from memory and then incremented.
The i++ and ++i expressions in the last clause of these for loops both increment i as a side effect and since the value of the expression is not used, they have exactly the same effect, namely the side effect.
Here are other alternative, all of which behave the same and should produce the same code:
for (int i = 0; i < n+1; i += 1) {
sum = sum + i;
}
and
for (int i = 0; i < n+1; i = i + 1) {
sum = sum + i;
}
Note however that if n is an int with the value INT_MAX, n+1 has undefined behavior. A safer way to write this loop is:
for (int i = 1; i <= n; i++) {
sum = sum + i;
}
But the <= operator has the same problem when n is INT_MAX: the undefined behavior would occur on the i++ part when i reaches INT_MAX...
Here is an alternative that avoids this corner case:
if (n > 0) {
for (int i = 1; i < n; i++) {
sum = sum + i;
}
sum = sum + n;
}
Related
disclaimer this is not my code and this code is from Remove Duplicate Elements from an Array in C - Javatpoint
What I want to know is in the Example 2 coding part. (I edit code a bit for me or you can see the code clearly.)
/* program to delete the duplicate elements from sorted array in C. */
#include <stdio.h>
int duplicate_element ( int arr[], int num)
{
// check num is equal to 0 and num == 1
if (num == 0 || num == 1)
{
return num;
}
// create temp array to store same number
int temp [num];
// declare variable
int i, j = 0;
// use for loop to check duplicate element
for (i = 0; i < num - 1; i++)
{
// check the element of i is not equal to (i + 1) next element
if (arr [i] != arr[i + 1])
{
temp[j++] = arr[i];
}
}
temp[j++] = arr[ num - 1];
// check the original array's elements with temporary array's elements
for (i = 0; i < j; i++)
{
arr[i] = temp[i];
}
return j;
}
int main ()
{
int num;
printf (" Define the no. of elements of the array: ");
scanf (" %d", &num);
int arr[num], i;
printf (" Enter the elements: ");
// use loop to read elements one by one
for ( i = 0; i < num; i++)
{
scanf (" %d", &arr[i]);
}
printf (" \n Elements before removing duplicates: ");
for ( i = 0; i < num; i++)
{
printf (" %d", arr[i]);
}
num = duplicate_element (arr, num);
// print array after removing duplicates elements
printf (" \n Display array's elements after removing duplicates: ");
for ( i = 0; i < num; i++)
{
printf (" %d", arr[i]);
}
return 0;
}
Here's the question, what does all j++ in function duplicate_element do? (If possible I would like to know what the code is doing since line // use for loop to check duplicate element until before return too. This part I'm just curious if I know it correctly or not.)
This is my understanding (j is the final size of arr[]). In the first question, when executed
j right now is 0
temp[j++]
is it plus the value of j by 1 first then assign value arr[i] to temp[1]. (Does this right?)
The second question, in the first for loop checks when the value in arr[i] is not equal to the value in arr[i + 1] then assign value in temp[j++] with value in arr[i] until for loop is over then assign temp[j++] with arr[num - 1]
(j++ right now is dependent on the if condition for example when all value is not equal to the value of j++ == value of num - 1 and num - 1 is equal to the last value of arr)
and in the last for loop, it assigns every value in Array arr with Array temp. (Does this right?)
In short, the statement
temp[j++] = arr[i];
is equivalent to
int old_value_of_j = j;
j = j + 1;
temp[old_value_of_j] = arr[i];
For starters the code is very bad.
Firstly, the function should be declared like
size_t duplicate_element ( int arr[], size_t num );
That is the size of the passed array should be specified using the unsigned integer type size_t instead of the signed int type int. Otherwise this declaration of the variable length array
// create temp array to store same number
int temp [num];
along with this statement
temp[j++] = arr[ num - 1];
will invoke undefined behavior if the user will pass as the second argument a negative number and according to the function specification it allows to pass a negative number.
Secondly, using the variable length array temp
// create temp array to store same number
int temp [num];
makes the function unsafe. It can occur such a way that the program will be unable to define this variable length array.
The approach is too complicated, confusing and inefficient.
As for your question relative to the postfix operator ++ then according to the C Standard (6.5.2.4 Postfix increment and decrement operators)
2 The result of the postfix ++ operator is the value of the operand.
As a side effect, the value of the operand object is incremented (that
is, the value 1 of the appropriate type is added to it).
So in fact this statement
temp[j++] = arr[i];
may be equivalently rewritten like
temp[j] = arr[i];
j += 1;
As the function adds to the array temp the last element in a series of duplicated elements in the array arr then after this main loop
// use for loop to check duplicate element
for (i = 0; i < num - 1; i++)
{
// check the element of i is not equal to (i + 1) next element
if (arr [i] != arr[i + 1])
{
temp[j++] = arr[i];
}
}
you need to add the last element pf the array arr to the array temp
temp[j++] = arr[ num - 1];
Here is a demonstration program that shows how the function can be rewritten and can look more simpler.
#include <stdio.h>
size_t duplicate_element( int a[], size_t n )
{
size_t m = 0;
for (size_t i = 0; i < n; i++)
{
if (i == 0 || a[i] != a[m-1])
{
if (i != m) a[m] = a[i];
++m;
}
}
return m;
}
int main( void )
{
int a[] = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
size_t m = duplicate_element( a, N );
for (size_t i = 0; i < m; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
The program output is
1 2 2 3 3 3 4 4 4 4 5 5 5 5
1 2 3 4 5
I wrote a program in C for this series. but when I enter n = -8 and m = 2 the result is zero.
Why and how can I fix it?
Series here
#include <stdio.h>
#include <math.h>
int main()
{
int n,m;
double sum = 0;
printf("Enter n:\n");
scanf_s("%d",&n);
printf("Enter m:\n");
scanf_s("%d", &m);
for (int i = -10; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
sum += (pow((i + j), 3) / pow(j,2) );
}
}
printf_s("%f",sum);
}
for (int j = 1; j <= n; j++)
{
sum += (pow((i + j), 3) / pow(j,2) );
}
when you are trying to input n=-8 this loop won't work coz j=1 and condition is set to work until j<=n
In your code, the only expression that modifies the variable named sum is inside the inner loop. The loop will execute only if its controlling expression j <= n is true.
You initialize j with the value of 1. If you give n any value less than 1, the loop will not execute because j <= n would be false.
Since the initial value of the variable sum is 0 and the expression that modifies sum is not executed, the output is 0.
#include <stdio.h>
int main() {
int i, j;
for (i = 2; i < 20; i++) {
for (j = 2; j <= (i/j); j++) {
if (!(i%j)) break;
}
if (j > (i/j)) printf("%d\n", i);
}
return 0;
}
I am a Beginner at C and trying to understand how the for loop works. My question is at the 4th iteration, the condition in the nested loop will return TRUE
(j < (i/j)) // 2 <= 4/2
and the first if statement will also return TRUE because of NOT operator
(!(i%j)); // 4/2 = !(0)
so now the value of j = 3 because of incrementation, but why the second if statement did not print the output if it is TRUE?
(j > (i/j)); // 3 > 4/3
You're breaking out of the loop before j is incremented, so j is still 2, not 3
A break statement ends its nearest enclosing loop prematurely. Everything after it (and that includes the third statement of the for loop), will not occur.
So j is still 2 when the condition for printing is checked, like Mark answered.
For some reason that I can't comprehend ,this program keeps looping when I execute it in the CMD.
#include <stdio.h>
int main() {
char array [] = {'b','f','r','o','a','u','v','t','o','\0'};
int grootteArray = sizeof(array);
int grootteChar = sizeof(char);
int lengteArray = grootteArray / grootteChar;
int i;
for (i = 0; i < lengteArray + 1; i + 2) {
printf("%c", array[i]);
}
return 0;
}
Your counter variable remains the same after each loop. You need to increase it by assigning the new value:
for (i=0; i<lengteArray+1; i=i+2) //change to this
Because i never changes. You should assign i + 2 to i:
for (i=0; i<lengteArray+1; i = i + 2) {
↑
The way you wrote it has no effect on the value of i, it just calculates i + 2 and does nothing with this value.
You're getting infinite loop because i is set to 0 and it's always 0.. So once i < legteArray + 1, it'll remain like that.
The value of i is never changed.
try this:-
for (i=0; i<lengteArray+1; i = i+2) {
i is not modifying in you loop. Also i < lengteArray + 1 will lead you to print garbage value and undefined behavior.
for (i = 0; i < lengteArray; i++){
printf("%c", array[i]);
}
If you are interested in incrementing i by 2 in each iteration then you can use i += 2
for (i = 0; i < lengteArray; i += 2){
printf("%c", array[i]);
}
In the program that I'm writing, I currently have a for-loop that goes through an array, num[5], and checks to see if there are any 1's in that array, which looks like:
int counter = 0;
for (int i = 1; i <= 5; i++)
if (num[i] == 1)
counter++;
This works successfully, but I'm now trying to go through the array and see what the indices of the 1's in the program are. So, if I have 01001, I want to make an array that holds the positions of the 1's. The following is what I've tried so far:
int b[counter];
for (int k = 0; k <= counter; k++) {
for (i = 0; i <= 5; i++) {
if (num[i] == 1) {
b[k] = i;
}
}
}
but this doesn't produce the desired result. When I type the string in, say 1001, I get 444. Can someone tell me what I'm doing incorrectly?
For each value of k, for each occurrence of a 1, you're setting b[k] to the index of the 1. Thus each b[k] will have the index of the last 1.
Try:
int b[counter];
int k = 0;
for (i = 0; i <= 5; i++) {
if (num[i] == 1) {
b[k++] = i;
}
}
So, whenever it gets a 1, it assigns b[k] to the index and then increases k.
Then you should also use k, not counter, when trying to print out b.
The problem lies in this part of your code.
int b[counter];
for (int k = 0; k <= counter; k++) {
**for (i = 0; i <= 5; i++) {
if (num[i] == 1) {
b[k] = i;
}**
}
}
Suppose you get a 1 at the index 1 of the array as in 01001. You assign b[k] = 1;
This is perfectly valid. But as the loop continues you get another 1 at the index 4. Thus the command b[k] = 4; is again executed.
Note that your value of k is constant in both the statements and hence you get the array b as 44.
So what you need to do is break the inner for loop as soon as you get a 1.
Here is the modified code. You also need to keep a track of the iterator i and I have done that here using the variable- new_pos // new position.
int b[counter];
int new_pos=0; //to keep track of the iterator
for (int k = 0; k <= counter; k++) {
for (i = new_pos; i <= 5; i++) {
if (num[i] == 1) {
b[k] = i;
new_pos = i+1;
break;
}
}
}
The code provided by Dukeling is also perfect, but I am just giving another way to make your own code work.