statement with no effect for-loop C [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I got this for-loop:
for(int k=4;k<0;k--){
if(k == 0){
test[k] = 5;
break;
}
else{
test[k] = test[k-1];
}
}
it should shift the elements of the array to the right, but nothing happens.
To my knowledge it should work just fine, but the compiler says, that the for-loop statement has no effect: statement with no effect [-Wunused-value]
can anyone help me solve this problem?

The loop initializes k to a positive value (k=4) and then loops while k is negative (k<0).
Since k is never negative, the loop has no effect.
Did you mean to write k >= 0?

The condition expression of the loop is wrong.
for(int k=4;k<0;k--){
You initialized k with 4 and then are checking whether it is less than 0. As 4 is obviously greater than 0 then the loop will iterate never.
I think you mean the following
for(int k = 4; k >= 0; k-- ) {
But in any case the code looks badly. For example it is not clear what the magic number 5 means and there is no need to use the break stztement.
You could write a function. Here is an example of the corresponding program
#include <stdio.h>
void shift_right( int a[], size_t n )
{
if ( n > 1 )
{
size_t i = n - 1;
int last = a[i];
for ( ; i != 0 ; --i ) a[i] = a[i - 1];
a[i] = last;
}
}
int main(void)
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t i;
for ( i = 0; i < N; i++ ) printf( "%d ", a[i] );
puts( "" );
shift_right( a, N );
for ( i = 0; i < N; i++ ) printf( "%d ", a[i] );
puts( "" );
return 0;
}
The output is
0 1 2 3 4 5 6 7 8 9
9 0 1 2 3 4 5 6 7 8

In your loop you use condition k<0 -> 4<0 -> false.
so your condition fails in first time itself.so your loop has not executed.so change your conditional statement to k>0 instead of k<0.
use the printf statement to find the loop is executes or not.
for(int k=4;k>=0;k--){
if(k == 0){
test[k] = 5;
break;
}
else{
test[k] = test[k-1];
}
}
The above code works as you expected.

Related

I can't seem to fix this issue about nested for loops + 2d arrays [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
this is the code I am having a problem with 1 2 the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int i, j;
int num[3][2] = { (1, 2),
(3, 4),
(5, 6)
};
for(j = 0; j < 3; j++){
for( i = 0; i < 2; i++ ){
printf("%d, ", num[j][i]);
} printf("\n");
}
return 0;
}
guys I am watching this course of freecodecamp about the C language and the guy tutoring got this code right as it says in the console: 1, 2,
3, 4,
5, 6,
and I typed the EXACT same code but still not working, I double- checked and everything, but nothing seems to work.
3
As #Oka said you need to use {} in the initializer. Also fixing formatting, separators, and localizing variables:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};
for(size_t j = 0; j < sizeof(num) / sizeof(*num); j++) {
for(size_t i = 0; i < sizeof(*num) / sizeof(**num); i++ ) {
printf("%d%s",
num[j][i],
i + 1 < sizeof(*num) / sizeof(**num) ? ", " : "\n"
);
}
}
return 0;
}
Both #Oka and #Allan Wind have written that you've used () where {} is the correct way to define data in an array.
Below uses a different layout for the small amount of data being specified.
It also shows (similar #Allan's answer) how to let the compiler measure the array's dimensions, uses those values as limits to the loops.
The compiler "knows" there are 3 rows (better than erring humans could do.) If a 4th row is added, re-compiling will use the right value without the programmer remembering to change the loop counter from 3 to 4.
This version uses fewer {} in the code, certain that there is only one executable statement properly indented.
This alternative style is more compact and less garish.
As nice as they are, i & j are overused and, therefore, meaningless. Notice the use of r & c that hints at being row & col. Easier to keep things straight when variable names suggest their meaning and use.
Notice how the indentation in the two versions highlights when printf( "\n" ); will be executed. Whitespace is important for readability. Respect it.
#include <stdio.h> // don't include what you don't need
int main() {
int r, c, num[][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
int nRows = sizeof num/sizeof num[0];
int nCols = sizeof num[0]/sizeof num[0][0];
printf( "Version 1:\n" );
for( r = 0; r < nRows; r++ ) {
for( c = 0; c < nCols; c++ )
printf( "%d, ", num[ r ][ c ] );
printf( "\n" );
}
printf( "\nVersion 2:\n" );
for( r = 0; r < nRows; r++ )
for( c = 0; c < nCols; c++ )
printf( "%d, ", num[ r ][ c ] );
printf( "\n" );
return 0;
}
Output
Version 1:
1, 2,
3, 4,
5, 6,
Version 2:
1, 2, 3, 4, 5, 6,
Others will soon comment that the correct definition would be size_t nRows.... One step at a time...

Can anyone tell me why this program runs? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
New to c programming. Here is a question from an assignment. Can anyone tell me why this code still outputs two columns 5 and 2 even though i is less than j.
#include <stdio.h>
int main(void) {
int i = 0, j = 5;
for (i > j; i + j == 5; j < 2) {
printf("Two columns\n");
i = 5;
j = 2;
}
printf(" %d %d\n", i, j);
return 0;
}
Here are the steps executed in order:
int i = 0, j = 5; local variables i and j are defined and initialized to 0 and 5 respectively
for (i > j; i + j == 5; j < 2) {:
first executes the initial expression i > j which evaluates to false (0) and has no side effect, the result is ignored, hence probably completely omitted by the compiler.
second executes the test expression i + j == 5 which evaluates to true (1) so the body of the for loop executes.
printf("Two columns\n"); outputs Two columns and a newline.
i = 5; sets i to 5.
j = 2; sets j to 2.
} the increment expression is then evaluated: j < 2, which evaluates to false but has no side effect, the result is ignored.
the loop then evaluates the test expression again: i + j == 5 which now evaluates to false (0) since 5 + 2 is different from 5.
the loop exits.
printf(" %d %d\n", i, j); outputs the numbers 5 and 2 and a newline as you observe.
return 0; main returns the value 0 which is a successful exit status.
This code is very silly and purposely misleading as it has test expressions in all 3 parts of the for statement header. Only the middle one is the test expression, the first and last expressions are only used for side effects, such as initializing and incrementing a loop counter.
for (i > j; i + j == 5; j < 2)
In for loop initialization part i > j no make sense
Then i + j == 5 condition become true and executed for loop body where assigned new values to i and j respectively 5 and 2.
Then control goes to for loop increment part where j < 2 become false. this is also no make sense.
Then again control goes to condition part where i+j == 5 becomes false because i is a 5 and and j is a 2. So, 7 == 5 becomes false.
So, output of your code is 5 and 2.

C: Why is counter not resetting to 0 in for loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So Im creating a simple for loop within a for loop. The var frequecyCount is not resetting to 0, don't understand why.
I have going through to arrays x and hist array and need a counter variable to count the frequency of the same value in x as the position of hist.
#include <stdio.h>
void create_hist(double *x, int count, int *hist) {
int frequencyCount = 0;
for (int iHist = 0; iHist <= 5; iHist++) {
//initalize to zero
hist[iHist] = 0;
for (int ix = 0; ix < count; ix++) {
// convert to int
x[ix] = (int)x[ix];
if (x[ix] == hist[iHist]) {
frequencyCount++;
}
}
// add to the hist[] array the frequency count at position i
hist[iHist] = frequencyCount;
frequencyCount = 0;
}
int main( void ) {
double x[5] = {0, 0, 0, 0, 3};
int hist[5];
int count = 5;
create_hist(x, count, hist);
printf( "\tInput data:\n" );
for ( int i = 0; i < count; i++ ) {
printf( "\t%d\t%f\n", i, x[i] );
}
printf( "\tHistogram:\n" );
for ( int i = 0; i <= 5; i++ ) {
printf( "\t%d\t%d\n", i, hist[i] );
}
return 0;
}
Try this change:
for (int iHist = 0; iHist < 5; iHist++) { // <= changed to <
int frequencyCount = 0; // Moved this line to be inside the loop
The frequencyCount variable is resetting. There is another reason your output is not what you expect.
This if statement is most likely wrong:
if (x[ix] == hist[iHist]) {
frequencyCount++;
}
At this stage, hist[iHist] is always 0 (that's the value you assigned just before the loop).
I think you mean:
if (x[ix] == iHist) {
frequencyCount++;
}
You also need to change the loop range condtion from i <= 5 to i < 5 in main and from iHist <= 5 to iHist < 5 in create_hist to avoid buffer overflow.
Making these changes results in the output:
Input data:
0 0.000000
1 0.000000
2 0.000000
3 0.000000
4 3.000000
Histogram:
0 4
1 0
2 0
3 1
4 0

Simple for-loop countdown timer in C [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
This is what the code should do:
“Lift off in T minus 5 4 3 2 1 Blast-off!”
When I run it, it just keeps printing ''Sum = 5'' forever.
Code:
int main(void) {
int sum = 5;
int i;
printf("Lift off in T minus\n");
for (i = 0; i < 5; i=i+i) {
sum = sum - i;
printf("sum = %d\n",sum);
}
printf("Blast-off",sum);
return 0;
for (i = 0; i < 5; i=i+i) { // use i = i+1
sum = sum - i; //sum-- or sum = sum -1
printf("sum = %d\n",sum);
}
As initially i=0, so
i=i+i; //will be zero always, no increment.
And
sum = sum -1;
otherwise
i = 0 =>sum = sum - i; // = 5 as i=0
i = 1 =>sum = sum - i; // = 4 as i=1
i = 2 =>sum = sum - i; // = 2 as i=2
i = 3 =>sum = sum - i; // = -1 as i=3
Why not run the loop backwards?
for (i = 5; i > 0; --i) {
printf("i = %d\n",i);
}
This is simpler so the potential for bugs to creep in is reduced. Also, your final printf if malformed: you're missing a format specifier for sum.
Your specific problem: replace i=i+i with i=i+1 or something similar. (I prefer ++i).

Bad exercise statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Given the problem:
The statement is a bit ambiguous. I don't really understand what they want.
I can display the desired result using just a regular for loop:
int step = 0
for(int i = 1; i < m + 1; i++)
{
if(i != p)
{
printf("(%d, %d)", step, i);
step++;
}
}
Is this what they really want? I see that they are talking about linear time, so I think it can't be that easy? Am I supposed to build the vector that they are talking about, and then delete it?
Something like this? (compile with gcc test.c -lm)
#include <stdio.h>
#include <math.h>
int main(void) {
int i, j;
int n = 4;
int m = (int)pow(2,n);
int p = 5;
for(i = 1; i <= n; i++)
{
for(j = (int)pow(2,i-1); j < ((int)pow(2,i)); j++)
{
if(j == p) {
continue;
}
printf("%d, %d\n", i, j);
// remove vector[j]
if((j == (m-1)) && (m != p)) {
printf("%d, %d\n", i, m);
// remove vector[m]
}
}
}
return 0;
}
Run result n=3, p=5:
1, 1
2, 2
2, 3
3, 4
3, 6
3, 7
3, 8
Run result n=4, p=5:
1, 1
2, 2
2, 3
3, 4
3, 6
3, 7
4, 8
4, 9
4, 10
4, 11
4, 12
4, 13
4, 14
4, 15
4, 16
You should write the full code. Let me make it simple:
It should delete every element of the array.
By the end of the loop your program should print out the step and one of the numbers that were deleted, into the format (k, q) where k is the step you are on, and q is one of the elements you had deleted .
Every time you delete an element you can change it by X.
You also need to remember the algorithm they are telling you to use and the "rules of the game", for example: n should be positive and an integer.
And if you do not understand the algorithm, just try to put the idea on a paper:
When I put n = 1, I should delete one element from the array. When n = 2, 2 elements, When n = 3 it should delete 4 elements , n = 4 it deletes 8 element, etc.
As we can see, it is pretty simple because it goes like a geometric progression.

Resources