4 minute read

Chapter 2 C PSet

Exercise 3.2: Substitution - User gives unique 26 character alphabetical nonrepeat key as argument then prompt for text and use key to cipher the text

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>


int main(int argc, string argv[])
{
    // Check command-line argument count and key length
    if (argc != 2 || strlen(argv[1]) != 26)
    {
        printf("Usage: ./caesar 26alphabetkey\n");
        return 1;
    }

    // Check that key contains only alphabetic characters and no repeats
    for (int i = 0; i < 26; i++)
    {
        if (!isalpha(argv[1][i]))
        {
            printf("Key must contain only letters.\n");
            return 1;
        }
        for (int j = i + 1; j < 26; j++)
        {
            if (tolower(argv[1][i]) == tolower(argv[1][j]))
            {
                printf("Key must not contain repeated letters.\n");
                return 1;
            }
        }
    }

    // Prompt user for plaintext
    string input = get_string("plaintext: ");

    // Allocate array for ciphertext
    char ciphertext[strlen(input) + 1];

    // Build ciphertext
    for (int i = 0; i < strlen(input); i++)
    {
        char c = input[i];

        if (isupper(c))
        {
            int index = c - 'A';  // A = 0, B = 1, ...
            ciphertext[i] = toupper(argv[1][index]);
        }
        else if (islower(c))
        {
            int index = c - 'a';  // a = 0, b = 1, ...
            ciphertext[i] = tolower(argv[1][index]);
        }
        else
        {
            ciphertext[i] = c;  // Non-letter characters unchanged
        }
    }

    // Null-terminate the ciphertext
    ciphertext[strlen(input)] = '\0';

    // Print result
    printf("ciphertext: %s\n", ciphertext);

    return 0;
}

Exercise 3.1: Caesar - Get a key input from user that determines the cipher key that will be applied to the text. Give usage error if not 0-9 otherwise output the ciphered text with casing unchanged

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

char rotate(char c, int key);

bool only_digits(string s);

int main(int argc, string argv[])
{
    if(argc != 2 || strlen(argv[1]) != 1 || !only_digits(argv[1])) //argument count check if not two then print correct usage else run
    {
        printf("Usage ./ceasar key\n");
        return 1;

    }
    string input = get_string("plaintext:\n");
    //printf("%s", input);

    //convert argv[1] to an int
    int key = atoi(argv[1]);

    for (int i = 0; i < strlen(input); i++)
    {
        printf("%c", rotate(input[i], key));
    }
    printf("\n");



}

bool only_digits(string s)
{
    for (int i = 0; i < strlen(s); i++)
    {
        if (!isdigit(s[i]))
        {
            return false;
        }
    }
    return true;
}

char rotate(char c, int key)
{
    if(isupper(c))
    {
        return((c - 'A' + key) % 26) + 'A';
    }
    else if(islower(c))
    {
        return((c - 'a' + key) % 26) + 'a';
    }
    else
    {
        return c;
    }
}

Exercise2 Readability - Make a program that takes string input and outputs the grade level for the text

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <math.h>
#include <string.h>

int calletters(string text);
int calwords(string text);
int calsent(string text);
int coleliau(int letters, int sentences, int words);



int main(void)

{
    //prompt user for text
    string para = get_string("enter text:\n");
    printf("text check:%s\n", para);


    //calculate words and sentences
    int letters = calletters(para);
    int sentences = calsent(para);
    int words = calwords(para);

    //calculate Coleman-Liau score
    int score = coleliau(letters, sentences, words);

    //print the grade level
    if(score < 16)
    {
        printf("grade level: %i\n", score);
    }
    else if(score >= 16)
    {
        printf("grade level: 16+");
    }
}

int calletters(string text)
{
    int letters = 0; //initialize letters

    for(int i = 0; text[i] != '\0'; i++)
    {
        if(isalpha(text[i]))
        {
            letters++;
        }
    }
    return letters;
}

int calwords(string text)
{
    int words = 0; //initialize words

    for(int i = 0; text[i] != '\0'; i++)
    {
        if(isblank(text[i]))
        {
            words++;
        }
    }
    return words + 1;
}

int calsent(string text)
{
    int sentences = 0; //initialize sentences

    for(int i = 0; text[i] != '\0'; i++)
    {
        if(ispunct(text[i]))
        {
            sentences++;
        }
    }
    return sentences;
}

int coleliau(int letters, int sentences, int words)
{
    float L = ((float) letters/words) * 100;
    float S = ((float) sentences/words) * 100;
    int index = 0.0588 * L - 0.296 * S - 15.8;
    return index;
}

Exercise Functions - Make a function that checks validity of triangle

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdbool.h>


bool checktriangle(int length1, int length2, int length3);

int main(void)
{
    int length1 = get_int("enter length 1:\n");
        //printf("%i\n", length1);
    int length2 = get_int("enter length 2:\n");
        //printf("%i\n", length2);
    int length3 = get_int("enter length 3:\n");
        //printf("%i\n", length3);
    bool validity = checktriangle(length1, length2, length3);
    printf("%s\n", validity ? "true" : "false");


}

bool checktriangle(int length1, int length2, int length3)
{
    if (length1 + length2 > length3 && length1 + length3 > length2 && length2 + length3 > length1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Exercise 1: Scrabble - Ask each player for a word and see who wins based on given point system array

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

// Points assigned to each letter of the alphabet
int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};

int compute_score(string word);

int main(void)

{
    string word1 = get_string("Player 1 word:\n");
    // to check it is working and it is printf("Hello, %s\n", name1);
    string word2 = get_string("Player 2 word:\n");
    // to check it is working and it is printf("Hello, %s\n", name2);
    int score1 = compute_score(word1);
    int score2 = compute_score(word2);

    //final message
    if(score1 > score2)
    {
        printf("player 1 wins\n");
    }
    else if(score2 > score1)
    {
        printf("player 2 wins\n");
    }
    else if(score1 == score2)
    {
        printf("tie\n");
    }
}


//calculate score

int compute_score(string word)
{
    int score = 0;

    for (int i = 0, len = strlen(word); i < len; i++)
    {
        if(isupper(word[i]))
        {
            score += POINTS[word[i] - 'A'];
        }
        else if(islower(word[i]))
        {
            score += POINTS[word[i] - 'a'];
        }
    }
    return score;

}

 // program to prompt for two strings one from each user then output winner or tie. 1. first will ask for each string
// 2. then will calculate the sum of points for each and 3. finally a conditional depending on situation to print result

Updated: