for (int i = 0; i < 3; i++)
for (int j = 3; j > 0; j--)
printf("i = %d, j = %d \n", i, j);
If there’s just a single line of code in a loop’s body, curly braces are unnecessary.
So, both of these are valid:
for (int i = 0; i < 3; i++)
for (int j = 3; j > 0; j--)
printf("i = %d, j = %d \n", i, j);
for (int i = 0; i < 3; i++)
{
for (int j = 3; j > 0; j--)
{
printf("i = %d, j = %d \n", i, j);
}
}
The for loop’s initialization, condition, and update are separated by semicolons — not commas!
for (int i = 0; i < 10; i++)
printf("This is CS50!\n");
for (int i = 0, i < 10, i++)
printf("This is CS50!\n");
Keep computationally-intensive processes like strlen() out of the loop’s condition. Here, we place strlen() in the initialization instead, so it’s only executed once rather than on every iteration.
for (int i = 0, j = strlen(name); i < j; i++)
name[i] = toupper(name[i]);
for (int i = 0; i < strlen(name); i++)
name[i] = toupper(name[i]);
A common bug is to add a semicolon after the loop’s declaration. This may cause you to wonder why the code in your loop isn’t executing or only executes once. The reason is that the loop is working, but it’s performing a no-op (empty statement) each time through the loop, assuming that the semi-colon is the statement you want to perform on each iteration.
for (int i = 0; i < 10; i++)
printf("This is CS50!\n");
for (int i = 0; i < 10; i++);
printf("This is CS50!\n");
Take as input a non-negative integer, n, no larger than 23. Use nested for loops to print an n-by-n square using hashes (#) at the command line.
jharvard@run.cs50.net (~): ./a.out
Give me a number between 1 and 23: 3
###
###
###
#include <cs50.h>
#include <stdio.h>
int main(int argc, string argv[])
{
// TODO
}
Take as input a number between 1 and 100. Use a for loop to print every multiple of that number between 1 and 100 (inclusive).
jharvard@run.cs50.net (~): ./a.out
Give me a number between 1 and 100: 5
5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100
#include <cs50.h>
#include <stdio.h>
int main(int argc, string argv[])
{
// TODO
}
Write a program that prompts the user for a message, and then outputs the message with its first letter capitalized, with all letters in alternating case, as per the sample output below. For simplicity, you may assume that the user will only input lowercase letters and spaces.
jharvard@run.cs50.net (~): ./a.out
thanks for the add
ThAnKs FoR tHe AdD
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main (int argc, string argv[])
{
// TODO
}
Rewrite the following double for
loop as a single for
loop. Make sure it prints exactly the same output, even though you may not have variables i
and j
around.
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
printf("i = %d, j = %d\n", i, j);
#include <cs50.h>
#include <stdio.h>
int main(int argc, string argv[])
{
// TODO
}