CS50 llamas lab I don't know how to solve it - cs50

#include <cs50.h>
#include <stdio.h>
int main(void)
{
int start ;
do
{
start = get_int("start size: ");
}
while (start < 9);
int end;
do
{
end = get_int("end size: ");
}
while (end < start);
int year = 0;
do
{
start = start + (start / 3) - (start / 4);//calculate number of years untile we reach thresholă…‡
**year++;**
}
while (start < end);
printf("Years: %i", year);
}
enter image description here
:( handles same starting and ending sizes
expected "Years: 0", not "Years: 1"
i think year++ is the problem i don't know how to solve it

Remember, the do loop will execute the body and then test the condition (in the while). When start and end are both 100, year will be incremented before it evaluates the while condition. Since program needs to compare start and end before it increments year, a simple while loop is appropriate.

Related

pset2 readability always printing before grade 1 no matter what input

I know this is a fairly newbie question so I'm sorry if the solution is painfully obvious to you guys.
I've fully coded up pset 2 readability and it worked for printing out the number of letters, words and sentences for the user inputted text- I have since removed those print statement as they aren't needed for the pset (I just wanted to actually make sure the functions were returning something- they worked just fine).
I'm up to printing out the grade level now but no matter what text I input I only get before grade 1. I've already checked to see if I had anything wrong with my print statements and I can seem to find an issue there so I'm thinking that there may be an error in the calculation of the grade level itself- I've looked until my eyes have gone square and for the life of me I can not see anything wrong.
If someone could shed some light on my problem I would love to be saved the headache :), or even point me in the right direction so I get the learning. (also first time poster, long time lurkers so forgive me if anything is formatted incorrectly).
Thank you all!
Here is my code:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
// my functions to calculate letters, words
int count_letters(string text);
int count_words(string text);
int count_sentences(string text);
int main(void)
{
string text = get_string("Text: ");
int letters = count_letters(text);
int words = count_words(text);
int sentences = count_sentences(text);
float calculation = (0.0588 * letters / words * 100) - (0.296 * sentences / words *
100) - 15.8;
int index = round(calculation);
if (index < 1)
{
printf("Before grade 1.\n");
}
else if (index >= 16)
{
printf("Grade: 16+.\n");
}
else
{
printf("Grade: %i.\n", index);
}
}
int count_letters(string text)
{
int letters = 0;
for (int i = 0; i < strlen(text); i++)
//((text[i] > 65 && text[i] < 90) || (text[i] > 97 && text[i] < 122))
if (isalpha(text[i]))
{
letters++;
}
return letters;
}
int count_words(string text)
{
int words = 0;
for (int i = 0; i < strlen(text); i++)
if isspace ((text[i]))
{
words++;
words = words + 1;
}
return words;
}
int count_sentences(string text)
{
int sentences = 0;
for (int i = 0; i < strlen(text); i++)
if (text[i] == '.' || text[i] == '!' || text[i] == '?')
{
sentences++;
}
return sentences;
}
I just wanted to actually make sure the functions were returning something- they worked just fine
Yes, the functions return "something" but is it the right thing? Suggest you add back the debug printf and look at the results carefully and critically. Start with the simplest text ("One fish. Two fish. Red fish. Blue fish."). 29 letters, 8 words, 4 sentences. What result is printed?
Inside of the function count_words
you have an if statement, if statements need to have brackets, the line wouldn't make sense even if you had the brackets, so double-check the logic as well.

cs50 pset 1 cash only prints out zeros

I tried figuring out what the problem was with my code, i checked if the brackets were ok, but i still cant figure it out.this is pset 1 cash
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
{
float dollars;
int cents = 0;
int coin_amount = 0;
do
{
//prompt user for amount of change
dollars = get_float("change: ");
}
while (cents < 0);
cents = round(cents * 100);
while (cents >= 25)
{
cents = cents - 25;
coin_amount++;
}
while (cents >= 10)
{
cents = cents - 10;
coin_amount++;
}
while (cents >= 5)
{
cents = cents - 5;
coin_amount++;
}
while (cents >= 1)
{
cents = cents - 1;
coin_amount++;
}
printf("%d\n",coin_amount);
}
Input: 1 dollar
Expected Output:4 coins
Your bug is that you say cents = round(cents * 100) when you really meant to say cents = dollars * 100
It is difficult to read the code because of the lack of consistent indenting, but your first do while loop also isn't working properly. It checks the value of cents but you don't actually try to convert from dollars to cents until after you're out of the loop. In other words, the do-while loop will only ever be run exactly once. You could put a negative number into it and break the program's intent. You need to convert to cents within that loop. If this works, appreciate the upvote.

Reading m words from a paragraph from n thread ? C++ multithreading ? Not working?

I want read a paragraph by extracting one word at a time using Multithreading . Each thread should read exactly one word and when paragraph ends they should exit peacefully . I know threads shouldn't be used in this way as there is no advantage in that . But I want to do that so that I can check how threads can work sequentially if required . I tried but it looks like the program is reaching deadlock state and not giving any output at all . There are 11 words in the string and I am using 4 threads .
#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
#include <chrono>
#include <condition_variable>
using namespace std;
stringstream s("Japan US Canada UK France Germany China Russia Korea India Nepal");
int count = 0;
string word;
condition_variable cv;
mutex m;
int i = 0;
bool check_func(int i,int k)
{
return i == k;
}
void print(int k)
{
while(count < 11) // As there are 11 words
{
unique_lock<mutex> lk(m);
int z = k;
cv.wait(lk,[&]{return check_func(i,z);}); // Line 33
s >> word;
cout<<word<<" ";
i++;
cv.notify_all();
count++;
}
return;
}
int main()
{
thread threads[4];
for(int i = 0; i < 4; i++)
threads[i] = thread(print,i);
for(auto &t : threads)
t.join();
return 0;
}
You need to change this code:
while(count < 11) // As there are 11 words
{
unique_lock<mutex> lk(m);
int z = k;
cv.wait(lk,[&]{return check_func(i,z);}); // Line 33
s >> word;
cout<<word<<" ";
i++;
cv.notify_all();
count++;
}
To this:
int z = k;
while(z < 11) // As there are 11 words
{
unique_lock<mutex> lk(m);
int z = k;
cv.wait(lk,[&]{return check_func(i,z);}); // Line 33
s >> word;
cout<<word<<" ";
i++;
z+=4;
cv.notify_all();
count++;
}
Three things changed in the above: the declaration of z is moved outside of the loop, the condition in the while changed to check z instead of count, and the line z+=4 added. You need to increment z by 4 each time if you want each of your threads to move onto the next word. Also, you need to check z not count because otherwise some of the threads will overshoot and the last word will be printed multiple times (consider the thread that reads the ninth word: if checking on count instead of z it continues on to the next iteration of the loop even though there will be nothing further for it to read).

Vigenere.c CS50 Floating Point Exception (Core Dumped)

I am working on the Vigenere exercise from Harvard's CS50 (in case you noticed I'm using string and not str).
My program gives me a Floating Point Exception error when I use "a" in the keyword.
It actually gives me that error
when I use "a" by itself, and
when I use "a" within a bigger word it just gives me wrong output.
For any other kind of keyword, the program works perfectly fine.
I've run a million tests. Why is it doing this? I can't see where I'm dividing or % by 0. The length of the keyword is always at least 1. It is probably going to be some super simple mistake, but I've been at this for about 10 hours and I can barely remember my name.
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main (int argc, string argv[])
{
//Error message if argc is not 2 and argv[1] is not alphabetical
if (argc != 2)
{
printf("Insert './vigenere' followed by an all alphabetical key\n");
return 1;
}
else if (argv[1])
{
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (isalpha((argv[1])[i]) == false)
{
printf("Insert './vigenere' followed by an all alphabetical key\n");
return 1;
}
}
//Store keyword in variable
string keyword = argv[1];
//Convert all capital chars in keyword to lowercase values, then converts them to alphabetical corresponding number
for (int i = 0, n = strlen(keyword); i < n; i++)
{
if (isupper(keyword[i])) {
keyword[i] += 32;
}
keyword[i] -= 97;
}
//Ask for users message
string message = GetString();
int counter = 0;
int keywordLength = strlen(keyword);
//Iterate through each of the message's chars
for (int i = 0, n = strlen(message); i < n; i++)
{
//Check if ith char is a letter
if (isalpha(message[i])) {
int index = counter % keywordLength;
if (isupper(message[i])) {
char letter = (((message[i] - 65) + (keyword[index])) % 26) + 65;
printf("%c", letter);
counter++;
} else if (islower(message[i])) {
char letter = (((message[i] - 97) + (keyword[index])) % 26) + 97;
printf("%c", letter);
counter++;
}
} else {
//Prints non alphabetic characters
printf("%c", message[i]);
}
}
printf("\n");
return 0;
}
}
This behavior is caused by the line keyword[i] -= 97;, there you make every 'a' in the key stream a zero. Later you use strlen() on the transformed key. So when the key starts with an 'a', keywordLength therefor is set to zero, and the modulo keywordLength operation get into a division by zero. You can fix this by calculating the keyword length before the key transformation.

The programmed cant find my file

I was doing a programmed that require me to prepare two separate input file which was name group1.txt and group2.txt and then create a programmed that finds the average score for each group
I wrote this but it cant find my file for reasons I do not know
some help maybe thanks !
Here is the code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
string line;
const int num_lines = 10; //change numline to any number you like, its to set the size of the array
string sub_code[num_lines];
float avrgs[num_lines];
string sub_code2[num_lines];
float avrgs2[num_lines];
ifstream myfile ("group1.txt");
int sum=0,score=0,j=1,i=0,i2=0;
double ave=0.0;
if (myfile.is_open())
{
while ( myfile>>line )
{
//cout<<line<<endl;
sub_code[i] = line;
while ( myfile>>score && score <100 && score >= 0)
{
sum += score;
j++;
}
ave = sum/j;
j=1;
sum = 0;
avrgs[i]=ave;
i++;
}
}
else
{cout << "Unable to open file"<<endl;}
myfile.close();
//this is for the secode line
ifstream myfile2 ("group2.txt");
if (myfile2.is_open())
{
while ( myfile2>>line )
{
//cout<<line<<endl;
sub_code2[i2] = line; //add all the subject code into the array to store sub codes
while ( myfile2>>score && score <100 && score >= 0) //well basically the score should be between 0 - 100,
{ //so -999 wont be read. Can change to while ( myfile2>>score && score!=-999)
sum += score; //read each grade and add it to sum
j++; //just to know how many grades are there so that division can be done
}
ave = sum/j; //find the average.
j=1; //set j back to 1, cause j is used to count the number of marks.
sum = 0; //since its sum+=score, we need to set sum back to 0, or else it will be adding on to the old marks
avrgs2[i2]=ave; //add that calculated ave into the array for average
i2++; //i2 is to basically know how many entries are in the file for grp2
}
}
else
{cout << "Unable to open file"<<endl;}
myfile2.close();
int gr1,gr2;
//outputing the averages and so on...
for (gr1=0;gr1<i;gr1++)
{
for(gr2=0;gr2<i2;gr2++)
{
if(sub_code[gr1]==sub_code2[gr2]) // compare subject id before displaying
{
cout<<sub_code[gr1]<<"\t"<<" 1 "<<avrgs[gr1]<<endl;
cout<<sub_code2[gr2]<<"\t"<<" 2 "<<avrgs2[gr2]<<endl;
break;
}
}
}
//
cout<<endl;
double grpave1=0,grpave2=0;
//to find the average of each group
for (gr1=0;gr1<i;gr1++)
{
grpave1+=avrgs[gr1];
}
for(gr2=0;gr2<i2;gr2++)
{
grpave2+=avrgs2[gr2];
}
grpave1=grpave1/i;
grpave2=grpave2/i2;
cout<<"Average for group 1:"<<grpave1<<endl;
cout<<"Average for group 2:"<<grpave2<<endl;
system("pause");
return 0;
}
Just need to know how to get my file ! I have put in Desktop, MY document, Projects, With the C++ file and I have no idea how !! Somemore I need to have a soft copy which I dun know whether it will be able to find my file in there !
The way you specify the file name, as "group1.txt" the file will only be found by the program if it's in the current working directory of the compiled program.
There are two ways to solve this problem:
actually copy the file to the working directory of the program. In many cases that will be the directory the executable resides in.
use an absolute filename, like ("c:\Users\youruser\Desktop\group1.txt" for a file stored on the desktop on a Win7 system.

Resources