Week 2: Arrays in C

week2
c
arrays
compiling
debugging
command-line arguments

Hello and welcome to CS50!

We’re onto the second week of C! This week we will be learning about arrays in C. Arrays are a powerful data structure that allow you to store multiple values in a single variable. They are used in many different applications, from storing the pixels of an image to storing the scores of a game. This week we will be learning how to declare, initialize, and access arrays, as well as how to use them in loops and conditionals.

We will also be learning about command-line arguments, which allow you to pass information to your program when you run it. This can be useful for passing in filenames, options, or other information that your program needs to run.

Finally, we will be learning about debugging and how to use the CS50 debugging tools to find and fix bugs in your code. Debugging is an important skill for any programmer, and learning how to use a debugger can save you a lot of time and frustration when you are trying to track down a bug in your code.

Resources:

Section-Specific:

Course-wide:

Office Hours:

  • My Office Hours: Friday, September 20 10:30-11:30 AM in HSA 4th Floor (67 Mt. Auburn Street)
  • All-Staff Office Hours: Sunday 3-5PM in Widener Library
  • Office Hours Schedule
  • If you have any questions at all, email me!

Helpful Functions from the CS50 Manual / Documentation

Check length of string

strlen("string") == 6 // true

Validate characters

isupper("UPPERCASESTRING") == 1 // true
islower("lowercasestring") == 1 // true
isalpha("alphastring") == 1 // true
isdigit("123456") == 1 // true

Common Patterns for the Problem Set

Check how many input arguments are there

You can verify how many arguments are passed to the program by checking the argc variable.

When you run the program like this in the terminal:

./file arg

The value of argc is 2. You can check this in your program like this:

if (argc != 2)
{
    printf("Usage: ./file arg\n");
    return 1
}

Get the first argument

You might want to get the first argument passed to the program. You can do this by using the argv array.

When you run the program like this in the terminal:

./file arg

The first argument passed to the program is arg. You can access this argument in your program like this:

string arg = argv[1];
printf("The first argument is: %s\n", arg);