This question already has answers here:
for loop missing initialization
(6 answers)
Closed 2 years ago.
Not long ago, I stumbled across a very interesting innovation in a for loop (or maybe it is nothing new but I've been living in a cave?). Please take a look and explain to me why the initialize gap is empty? Of course, that's the part of the program which works. I would grateful for any revelation:)
void rzad_zn(char ch, int i, int j)
{
int pom;
pom = i;
for(; i<=j; i++)
{
printf("%d ", i);
}
printf("\n");
for(; pom<=j; pom++)
{
printf("%c ", ch);
}
printf("\n");
}
The for loop has three components, all of which are optional, as in this is a valid loop as well:
for (;;) { }
Though it is an infinite loop unless something calls break.
Any combination of arguments may be used, even compound ones like:
for (int i = 0, j = 0; i < j; ++i) { ... }
Where you can declare multiple variables, or use the comma operator in the other parts to join together several operations if necessary.
Related
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 4 years ago.
Improve this question
I want to sort 12 integers using a "reverse bubble sort" (We call it "the drowning axe sort", whatever). My function looks good to me but something goes wrong.
Error: having typed my 12 random numbers I don't get the result printed, instead my compiler stops and does not proceed any further.
Can anyone help?
Code:
#include<math.h>
#include<math.h>
void array_clean(int a[11]) //just an array cleaner
{
for(int i=0; i<12; i++)
{
a[i] = a[i]&&0; // smth && 0 = 0 anyway
}
}
void axe_sort(int a[11]) //drowning-axe sort function
{
int place = 0;
for(int i=0; i<12; i++)
{
for(int j=0; j<12; j++)
{
if(a[j]<a[j+1])
place=a[j];
a[j] = a[j+1];
a[j+1] = place;
}
}
}
int main(void)
{
int array[11]; //declaring an integer array;
array_clean(& array[11]); // giving user-filed array to a cleaner function
printf("Enter 12 random integers you'd like to sort: ");
for(int m=0; m<12; m++)
{
scanf("%d", &array[m]); //letting user to fill an array
}
axe_sort(&array[11]); //sorting an array via our axe_sort function
for(int m=0; m<12; m++)
{
printf("%d", array[m]); //printing the sorted array
}
return 0;
}
Your array int array[11]; isn't doing what you think it is. That declares an array of 11 ints, indexed from 0 to 10 inclusive. There is no array[11] therefore trying to access this will lead to undefined behavior.
You've got the correct form of your for loop, it'll correctly iterate over 12 members of the array, numbered 0 to 11 inclusive. However you need to declare the array as int array[12]; to get it big enough to work.
Also, you're passing the array to the two functions using &array[11]. You just need to say array and it'll pass in the array correctly. What you're doing will cause the two functions to write over random memory, which definitely won't help.
Try fixing these and see what changes.
First of all, You should include stdio.h header file in order to use printf() and scanf()
You are dealing with 12 integers. Then Why did you declare an array of 11 integers???
int array[11]; //declaring an integer array; <-------- change the size to 12 from 11
The purpose of the array_clean(); is to initialize each number with 0. You can simply put 0 instead of a[i]&&0;
Here you are passing the address of 12th element.
array_clean(&array[11]); //<---------------------
You should pass the address of the base element(1st).
You can do this by two ways.
array_clean(&array[0]);
Or,
array_clean(array);
When an array is used as a value, its name represents the address of the first element.
And finally, please check your bubble sort logic.
for(int j=0; j<12; j++)
{
if(a[j]<a[j+1])
{place=a[j]; //<-----curly braces missing in the body of if
a[j] = a[j+1]; //<----error
a[j+1] = place;
}
}
For j=11, your code will try to access 12th index and that will give you a segmentation fault. Enclose the body of if with curly braces.
Here is the modified code
#include<math.h>
#include<stdio.h> // <---------- include this header file
void array_clean(int a[12]) //just an array cleaner
{
for(int i=0; i<12; i++)
{
a[i] = 0; // smth && 0 = 0 anyway
}
}
void axe_sort(int a[12]) //drowning-axe sort function
{
int i,j;
for(i=0; i<11; i++)
{
for(j=0; j<11-i; j++) //<-------- see the logic carefully
{
if(a[j] < a[j+1]) //<-----put curly braces
{int place=a[j];
a[j] = a[j+1];
a[j+1] = place;}
}
}
}
int main(void)
{
int array[12]; //declaring an integer array;
array_clean(&array[0]); // <---------------- pass the base address
printf("Enter 12 random integers you'd like to sort: ");
for(int m=0; m<12; m++)
{
scanf("%d", &array[m]); //letting user to fill an array
}
axe_sort(&array[0]); // <---------------- pass the base address
for(int m=0; m<12; m++)
{
printf("%d ", array[m]); //printing the sorted array
}
return 0;
}
I think you forgot to include the stdio.h library in your code
What I mean by my question is that if I have a nested for loop like
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; i++)
{
printf("%d\n"___);
}
}
What would I put in the blank? Would [i][j] be illegal if I declared an array already?
I am not sure what exactly you are stuck on based on your question so I made a minimal C program with comments
I declared an int array who's first and second dimension are at least 10 because you iterate both i and j from 0 to 9 (inclusive). This is to avoid out of bounds problems while iterating
The array's elements are not initialized in the program. It is possible that this program will print all zeros when you run it. It is also possible that it prints other values that happened to be in memory (because the array values are not initialized)
Last I declared i and j outside the for loop just in case this was the problem you were facing
#include <stdio.h>
int main(int argc, char** argv) {
// Declare an array
// Note that both dimensions are at least 10
// Also note that none of the values are initialized here
int myArray[10][10];
// Both i and j are declared here rather than in the for loop
// This is to avoid the following potential error:
// error: 'for' loop initial declarations are only allowed in C99 or C11 mode
int i, j;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
// Note that the values this prints are uninitialized
printf("%d\n", myArray[i][j]);
}
}
return 0;
}
Your question was really unclear. But from what I understand is you have some 2-d array, and you want to print contents of array.
You must have arrary already defined as int arr[10][10], then you can use,
printf("%d\n", arr[i][j]);
I have a contrived example to demonstrate the request for a specific functionality - I wonder if anyone has a clever trick to do this.
The following is a problem one encounters quite frequently:
"Print a series of numbers; print a space between them, and a carriage return (but no space) at the end.
The obvious solution is to make the last (or first) statement a special case. I was pondering ways to make this more efficient/compact.
brute force:
for(ii=0; ii<4; ii++) {
printf("%d", ii);
if(ii<3) printf(" "); else printf("\n");
}
Note that this involves two evaluations of a condition.
unrolling:
for(ii=0; ii<3; ii++) {
printf("%d ", ii):
}
printf("%d\n", ii);
Leverages the fact that ii will be incremented one last time as we leave the loop.
functionality I would like
ii = 0;
while(1) {
printf("%d", ii);
ii++;
if(ii<3) printf(" ");
else {printf("\n"); break;}
}
And I was wondering if it's possible to make this work inside the for statement. I tinkered a bit, and found that the following works (somewhat to my surprise... it did need the parentheses, and it quite unreadable between the ?: and the , operators - see http://codepad.org/wFa2YwCg):
for(ii=0; (ii<3)?(printf("%d ",ii),1):(printf("%d\n",ii),0);ii++);
I am essentially turning the evaluate this condition part of the for loop into a execute this statement for most of the loop, and this other one for the last pass statement.
I was wondering if there is a better way to do this - both efficient, and readable?
[In many ways this question should be closed as it's opinion based.]
This problem crops up often. I always opt for a solution that minimises the instructions in the iterative part.
{ /*don't pollute the outer scope with ii*/
int ii;
for (ii = 0; ii < 3; ++ii/*I've always preferred this to ii++*/) {
printf("%d ", ii);
}
printf("%d\n", ii);
}
Ternaries, if statements etc. just obfuscate things. In my opinion.
I have used the following type of construct for this situation. It is not more efficient (still has a condition at each iteration), but I like it because it results in a single printf:
char *sep = " ";
for(ii=0; ii<4; ii++) {
if ( ii == 3 )
sep = "\n";
printf( "%d%s", ii, sep );
}
"Brute force" and ternary condition solution have the same complexity, but the second one is less "readable".
You can do a simple method print:
void print() {
int i = 0;
for(i=0; i != size - 1; ++i) {
printf("%i ",i);
}
printf("%i\n", i);
}
I think it is efficient and readable too.
In this way you reduce cyclomatic complexity of your alghotitm.
For both readability and performance, I think the following code can be used:
for (ii = 0;; ii++)
{
printf("%d", ii);
(ii < 3) ? (putchar(' ')) : ({ putchar('\n'); break; });
}
Actually, the above code is similar to your last code. It is readable, and it still has one conditional evaluation in each increment.
int numberoftimes = 4
if numberoftimes > 1
{
for(ii=0; ii<numberoftimes - 1; ii++)
{
printf("%d ", ii);
}
}
printf("%d\n", numberoftimes - 1);
Either you test every time in the loop, or you test once first...
Here's a way that requires a separate initialization pass, but that has a slightly cleaner for loop. Array sepsarray holds the separators you want (in this example, commas so you can see them). The last element of sepsarray is followed by a '\0' that terminates the loop.
#include <stdio.h>
#define MAXNUM 5
//print up to this
void main() {
char sepsarray[256] = {0}; //256=arbitrary max size
int i;
char *seps=sepsarray;
for(i=0;i<MAXNUM;++i) sepsarray[i]=','; //fill in the separators
sepsarray[i]='\n'; //the last separator
for(i=0; printf("%d%c",i,*seps++),*seps; i++) /* pretend to do nothing */ ;
}
Output:
0,1,2,3,4,5
Hardly IOCCC material, but hey... :)
Don't know if it's a really dumb thing to ask as I feel it goes against C syntax.But I am not sure.I stumbled across that in a question posted few minutes back.The OP uses something like (int i = 0; i < n; i++), ie without even a ; after i++.
Fibonacci Series in C - The series of numbers up to a given number
But though the OP's line is obviously wrong, I am tempted to ask something I just don't know- What does the following mean in C :
(int i = 0; i < n; i++;) // Three `;` terminated statements enclosed in ()
as the following simply means a block of statements in C:
{int i = 0; i < n; i++;}
I mean, what does (int i = 0,n=3; i = n; i++;) mean in the following dummy program:
#include<stdio.h>
int main(void)
{
(int i = 0,n=3; i = n; i++;)
}
Edit Even that single line sourced from that original question is ridden with errors.So let me ask this independently : What does it do if we enclose multiple ; terminated statements within a pair of ()? If we enclose within {} it becomes a block,but what about ()?
Nothing. The parentheses are used in certain situations such as boolean expressions and for loop comprehensions. You'll get a bunch of syntax errors.
Common for loop construction:
for (int i = 0; i < 10; i++){
//code here
}
The code
{int i = 0; i < 10; i++;}
doesn't really do much except set i to 0 and increment it to 1.
I'm not even sure if saying i < 10 is valid outside a condition
This question already has answers here:
How does the Java 'for each' loop work?
(29 answers)
Closed 9 years ago.
Can someone please explain to me how for(int current : values) works. Assuming we have a method like this. Thanks
public int count(int[] values, int value)
{
int count = 0;
for (int current : values)
{
if (current == value)
count++;
}
return count;
}
It is equivalent to:
for (int i = 0; i < values.length; i ++) {
int current = values[i]
...
}
It is called an enhanced for loop. (Other programming languages may use for ... in or foreach, but they mean the same thing.)
Here is an article on the Oracle website about it.
It loops over all the elements in the values array. It's the same idea as this, only without an index variable:
for (int i = 0; i < values.length; ++i) {
int count = 0;
if (current == values[i])
count++;
return count;
}
You can think of it as a "for each" loop. In other words, for each element in values array, do this loop.
for(int current : values)
is a for-each loop ,which is similar to :
for(int i =0 ; i< values.length; i++)
It is not simply a for, it is a foreach, and it works like this:
public int count(int[] values, int value)
{
int count = 0;
for (int i=0;i<values.length;i++)
{
current = values[i];
if (current == value)
count++;
}
return count;
}
The for-each and equivalent for statements have these forms. The two basic equivalent forms are given, depending one whether it is an array or an Iterable that is being traversed. In both cases an extra variable is required, an index for the array.
For-each loop
for (type var : arr) {
body-of-loop
}
Equivalent for loop
for (int i = 0; i < arr.length; i++) {
type var = arr[i];
body-of-loop
}
Update:
Turbo C does not support for each loop. But same you can achieve using for loop constructs of C.
Read here : For Each Loop supports in languages