I was cleaning out a flash drive and found the log I made two years ago when learning Python. I thought I'd post the first day here. Bear in mind that the only languages I knew beforehand were ActionScript and JavaScript.
2010/05/08 10:20: Started the Python tutorial. It's nice that you don't need to install anything extra. Hello world is simple but there are no parentheses. Interesting.
Wednesday, March 28, 2012
Friday, March 23, 2012
C/C++ loop surprises
A basic element of almost any program is a loop. Loops are a simple concept to grasp, but they can have pitfalls in some languages; here I will present one I learned about yesterday in C.
The basic for loop in C is of this form:
int n;
unsigned int i;
for (i=0; i<n; i++) {
//do something
}
Which is pretty foolproof as long as you leave i alone inside the loop. But another type of loop is the decrementing loop. Here is a simple program that prints the numbers from 5 down to 1:
#include <stdio.h>
int main (int argc, char **argv) {
int n = 5;
unsigned int i;
for (i=n; i>=1; i--) {
printf("%u\n", i);
}
}
And the output:
5
4
3
2
1
The basic for loop in C is of this form:
int n;
unsigned int i;
for (i=0; i<n; i++) {
//do something
}
Which is pretty foolproof as long as you leave i alone inside the loop. But another type of loop is the decrementing loop. Here is a simple program that prints the numbers from 5 down to 1:
#include <stdio.h>
int main (int argc, char **argv) {
int n = 5;
unsigned int i;
for (i=n; i>=1; i--) {
printf("%u\n", i);
}
}
And the output:
5
4
3
2
1
Subscribe to:
Posts (Atom)