1 minute read

Chapter 2 C PSet

Exercise 3.2: Credit - Program to ask users for a credit card number and check whether it is VISA, MC, or AMEX implementing Luhn’s algorithm

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: