Week 2
Week 2
Week 2
Shreyvardhan Sharma
Tuesdays, 4 30pm, Boylston 104
[email protected]
Arrays
Arrays are data structures that can store fixed-size sequential collection of
elements of the same type. Indexing starts with 0, as is the norm in CS. Not
only are arrays more efficient (than declaring a bunch of variables separately),
but their utility lies in being able to store and access data seamlessly at any
stage of the program.
Declaring arrays: type name[size] , for example,
int scores[5]
Declaring (and initialising arrays) so as to input data from the user is similar:
int scores[3];
for (int i = 0; i < 3; i++)
{
scores[i] = get_int("Score: ");
}
Strings
A string can be thought of as an array of characters. Although C does not have
an inbuilt data type for strings, the header file allows us to use
cs50.h string
Week 2 1
Strings are terminated with a special character: , to demarcate the end of
\0
the string. Knowing this is particularly useful when we want to iterate through
a string: the last character of the string will always be . The is not
\0 \0
We typically define main() with two arguments: the first argument, is an argc
integer storing the number of command line arguments. The second argument,
argv is an array of strings storing a list of the command line arguments
themselves. For example, executing a program in CS50 IDE with
caesar.c
Week 2 2
$ ./addition 2 8
2 + 8 = 10
$ ./addition 2
Usage: ./addition x y
Solution:
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
there are less (or more) than 3 arguments, we want to exit the program. A
simple way to do this is to return 1from within the function.
main int
main returns by default, indicating that the program ran successfully, and
0
we can return 1 to exit the program midway in case any condition is not
met.
2. To add the two numbers inputted from the user, the numbers need to be of
type . The numbers obtained from the command line are of type
int
int.
3. is a placeholder for variables of type .
%i int
Example 2: Palindrome
Week 2 3
Write a program that takes a string as input, and determines
palindrome.c
$ ./palindrome
Text: jellyfish
NOT PALINDROME
Solution:
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
string s = get_string("Text: ");
// Print output
if (palindrome)
{
printf("PALINDROME\n");
}
else
{
printf("NOT PALINDROME\n");
}
Example 3: Initials
Week 2 4
Write a program that takes a user’s full name as input, and outputs
initials.c
their initials. The program should accept a user’s name using . Initials
get_string
should all be printed as uppercase letters, even if the name contains lowercase
letters. You may assume that the user’s names will be separated by one space.
Sample usage:
$ ./initials
Name: David J. Malan
DJM
Solution:
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
string name = get_string("Name: ");
printf("\n");
}
Week 2 5