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 8 years ago.
Improve this question
All I want to know is whether this statement is feasible or not
for(j = 2; (j <= i) && flag; j++)
flag is initialized to i before this loop. I have not seen any such thing before.
The general for loop condition is like this:-
for(initialization ; condition; increment)
So what you are doing is correct.
Breaking down your for loop means:-
for(j=2;(j<=i)&& flag ;j++)
initialization is j=2;
condition is (j<=i)&& flag ;
increment is j++
One example:-
int main(int argc, const char * argv[])
{
int sum = 0;
int j = 100;
for(int i = 1; i<=100/2 && j>100/2; i++){
sum += i+j;
j--;
}
return sum;
}
Second Example with flag:
Remember bubble sort, In bubble sort we need two nested loops, outer loop runs for number of passes and inner loop do swapping task for each pair a[i], a[i + 1]. To save execution we can make use of some flag variable. If in some pass no swapping done this means no need to execute next pass and sorting completeed, read: Optimizing bubble sort:
Now code for this:
FLAG = 1;
for(i = 0; FLAG && (i < n - 1); i++){//If flag = ), break outer loop sorting done
FLAG = 0; // set flag = 0
for(j = 0; j < n - 1 - i; j++){
if(arr[j] > arr[j + 1]){
swap(arr[j], arr[j + 1]);
FLAG = 1; // if any swapping need, then check in next round
}
}
}
Notice outer loop condition FLAG && (i < n - 1), I think this is what you wants. Hope this help!
Related
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 last year.
Improve this question
{
for (int i = 0; i <= 5; i++)
{
for (int j = 5; j >= i; j--)
{
printf("+");
}
printf("\n");
}
}
At i = 4; j will be 2 how does it satisfy the condition of j>=i?
You seem to be thinking that "j will be 2" because you see two "+" in output in that line.
But that only means that the inner loop is executed twice. Which is because (quoting Barmars comment):
When i == 4, the inner loop will only loop twice, with j == 5 and j == 4.
You analysed the detailed behaviour of your code based on output, which is good. But if something puzzles you then you either need more output on exactly the detail which puzzles you; e.g. by actually outputting the value in question for verifying your assumptions. Or you could use a debugger.
For example. I changed your code in a way which probably makes things very obvious:
#include <stdio.h>
int main(void)
{
for (int i = 0; i <= 5; i++)
{
printf("%d: ", i);
for (int j = 5; j >= i; j--)
{
printf("%d", j);
}
printf("\n");
}
}
It gets you an output (e.g. here https://www.onlinegdb.com/online_c_compiler ) of:
0: 543210
1: 54321
2: 5432
3: 543
4: 54
5: 5
Where the line 4: 54 indicates two inner loop iterations, with values for j of 5 and 4, while i is 4.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
#define SIZE 10
void fun(int arr[]){
int i,k,j,n = SIZE;
k = 0;
for (i = 1 ; i < SIZE; i++) {
j = k;
while (j > 0 && arr[j] != arr[i])
j = j - 1;
if( j == 0){
k = k + 1;
arr[k] = arr[i];
}
else
n--;
}
}
This function was in my test today.
My question is: does someone know what it does?
What does the variable n represent at the end of the function?
At the end of the function, the variable n will have counted how many times each i-th array value in the range [0, SIZE) was unique among the first i array elements..
In addition, the first n elements of the array will contain exactly those elements that were found to be unique in the above sense. All other array entries will remain unchanged.
The other variables will have the following values:
i == SIZE
j == some value between [0, SIZE)
k == n-1
Some inline comments may help understand the code better.
#define SIZE 10
void fun(int arr[]){
int i,k,j,n = SIZE;
k = 0;
// walk through the array up until its 10th element, skipping
// the first entry and hoping that the array actually contains
// at least 10 entries
for (i = 1 ; i < SIZE; i++) {
// similar to i, the variable k also walks up towards 10.
// However it starts at 0, not at 1, and it does not
// necessarily get incremented in every loop iteration. More
// on that below.
// Here, we set the variable j to start out as the same value
// as the current k, but j will walk the opposite direction, i.e.,
// toward 0, not toward 10.
j = k;
// find the largest j in the open interval [0,k) for which
// the array entry arr[j] differs from the current arr[i]
while (j > 0 && arr[j] != arr[i])
j = j - 1;
// if no value in [0, k) was equal to arr[i], we'll end up \
// with j == 0
if( j == 0){
// then we increment k -- that is, k counts how many times
// we encountered a value arr[i] during the for-loop that was
// unique among the first i array entries. But since the
// for loop starts at 1 instead of 0, k will count one
// element too few.
k = k + 1;
// well, so much for 'unique': here, we actually copy the current
// value arr[i] into arr[k]
arr[k] = arr[i];
}
else
// this part in effect assures that the expression
// (n-k) gets decremented in every iteration of the loop,
// no matter if j == 0 is true or false.
// Since we start out with (n-k) = SIZE, and
// the loop body gets executed SIZE-1 times, (n-k) will
// be equal to 1 after the for-loop has terminated.
n--;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
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.
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.
Improve this question
Story: I tried to convert a c99 script to regular gcc.
Problem: The output is empty.
Expected output: 3,2,1
length is the number of elements in the array.
Update: the script is designed to sort the elements of the array in a descending order.
The code:
#include <stdio.h>
int main() {
int arr[] = { 1,2,3 };
int temp = 0;
int length = sizeof(arr) / sizeof(arr[0]);
int i = 0;
int j = i + 1;
for (i < length; i++;) {
for (j < length; j++;) {
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
int y = 0;
for (y < length; y++;) {
printf("%d ", arr[y]);
}
return 0;
}
Your syntax for for loops is the issue.
Here is the correct way to write your loops.
int i, j;
for (i = 0; i < length; ++i) // for (initialisation; test condition; operation)
{
for (j = i + 1; j < length; ++j) // note that j is initialized with i + 1 on each iteration of
// the outer loop. That's what makes the bubble sort work.
{
/* test and swap if needed */
}
}
for (i = 0; i < length; ++i) // note that i is reset to zero, so we can scan the array from
// a known position (the top) to bottom.
{
/* printout */
}
Your semicolon is in the wrong place, move it to the far left just inside the parentheses.
Loop syntax is:
for (intializer; break condition; iterator)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How would I traverse a 2D array by finding the local maxima by checking if all the numbers around it are smaller than it? I am really confused on how I would do this in code. I need to get the position and I only need local maximums, not absolute maximums.
void reportMaxima(int rows, int cols, int grid[ rows ][ cols ])
{
}
This should work:
#include <stdbool.h>
#include <string.h>
void report_maxima(int rows, int cols, int arr_in[rows][cols],
bool arr_out[rows][cols])
{
int i, j;
int k, l;
memset(arr_out, 0, rows * cols * sizeof(arr_out[0][0]));
// memset(arr_out, 0, sizeof(arr_out)); I think this doesn't work :(
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
for (k = i - 1; k <= (i + 1); k++) {
if (k < 0)
continue;
if (k >= rows)
break;
for (l = j - 1; l <= (j + 1); l++) {
if (l < 0)
continue;
if (l >= cols)
break;
if (arr_in[i][j] < arr_in[k][l])
goto not_maxima;
}
}
arr_out[i][j] = true;
continue;
not_maxima:
}
}
}
First you need a bool array where to store the output info: whether a point is a maxima (true) or not (false).
You need to initialize that array to 0 (false) before storing the points where it is true. The best way to do that is by using memset().
Then, you need obviously to iterate over the input array. (i and j do that)
For each point of the input array, you check all the neighbours. (k and l do that).
You need to be sure that the neighbour you are trying to access is inside the array bounds (the if - continue and if - break do that).
Then, you check if all those neighbours are smaller than the point you are on. The first neighbour you find that is greater than your point tells you that you are not in a local maxima, and you should skip to the next point. If after checking all the neighboours you haven't found any neighbour greater than your point, then you are in a local maxima. (or at least in an inflection point).
That last thing is important: If you want to be sure, you should add a lot of checking, which would slow down the algorithm a lot. It depends on your needs.
EDIT:
Fixed a bug when using incorrect input to sizeof().
Simply run throw all of the cells in the array using 2 for loops
int i,j;
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
if(check(i,j,rows,cols,grid)) {
//do something.
}
else {
//do something else.
}
}
}
Then in code you can check all of the numbers around it. The key for this task is to not be lazy, just check every cell around it. Make sure that you don't try to access memory that is not part of the array.
[i-1][j-1] , [i-1][j] , [i-1][j+1]
[i][j-1] , the cell , [i][j+1]
[i+1][j-1] , [i+1][j] , [i+1][j+1]
So you will need to verify that the +1's are smaller then rows and cols (respectively) and that the -1's are bigger-equal to 0. After that check if the cell in question is smaller then the specific cell next to it, If so return false. At the end of the functions, if no near cell is bigger return true.
bool check(int i, int j, int rows, int cols,int grid[rows][cols]) {
if((i - 1 >= 0) && (j - 1 >= 0) && (grid[i-1][j-1]) > (grid[i][j]))
return false;
if((i - 1 >= 0) && (grid[i-1][j] > grid[i][j]))
return false;
//etc...
return true;
}
There are more esthetic ways to do it, but when you begin to code readability should be the most important thing. If you use a helper function remember to declare it before using it, Good luck!
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 7 years ago.
Improve this question
I have two arrays and if a number is repeated in 1 array I set that corresponding location in both to a value of zero. I then want to store it in a separate array now ignoring those zeros and copying the rest. However right now if I try this it just copies the array with the zeros, any idea?
for (i = 0; i < linect; i++) //searches array sets repeated points to zero
{
if (array1[i] == array1[i+1])
{
array1[i] = array1[i + 1] = 0;
array2[i] = array2[i + 1] = 0;
}
}
for (i = 0; i < linect; i++)
{
if (array1[i] > 0.5){
fixarray1[i] = array1[i];
fixarray2[i] = array2[i];
}
}
j = 0;
while (j <300){
printf("\n%f", fixarray2[j]);
j++;
}
So when you say "if a number is repeated in 1 array" do you mean if the number in the next index is the same as the current index or if the number is repeated in the entire array? As your code is, you are only checking the next value for repetition.
for (i = 0; i < linect; i++)
{
if (array1[i] > 0.5){
fixarray1[i] = array1[i];
fixarray2[i] = array2[i];
}
}
Will only copy non-zero values into array 2 at the indices where there were non-zero values in array 1. So you're not actually removing any of the 0 values, you're just making another array fixarray2[i] that is the same as array2[i] . You need to keep a separate counter if you want to skip all the zero's from your old array.
In the loop below value is stored in fixarray only when element in array1 is not zero but its index gets incrementated even when element is zero.
for (i = 0; i < linect; i++)
{
if (array1[i] > 0.5)
{
fixarray1[i] = array1[i];
fixarray2[i] = array2[i];
}
}
In this loop index of fixarray should incrementated only when value in array1 is not zero .Something like this -
int j=0;
for(i = 0; i < linect; i++)
{
if(array1[i]>0.5)
{
fixarray1[j] = array1[i];
fixarray2[j] = array2[i];
j++;
}
}
This is will store value in fixarray only when element in array1 is not zero.