IT, Programming, & Web Development › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 3: [Algorithms] – Linear Search, Binary Search, Bubble Sort, Selection Sort, Recursion, Merge Sort › Bool variable won and print_winner function
Tagged: bool type in C
- This topic is empty.
-
AuthorPosts
-
January 12, 2023 at 10:51 am #1028
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
// Check if election has been won bool won = print_winner(); if (won) { break; }
[/dm_code_snippet]
An explanation of the above code will be helpful.
Here is the print_winner function that I have coded:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
// Print the winner of the election, if there is one bool print_winner(void) { int necand = 0; for (int cc = 0; cc < candidate_count; cc++) { if (candidates[cc].eliminated == false) { necand = necand + 1; } } for (int canc = 0; canc < candidate_count; canc++) { if (candidates[canc].votes > necand/2) { printf("winner is %s", candidates[canc].name); return true; break; } } return false; }
[/dm_code_snippet]
As far I understand, a variable won is created that is of bool type. The value of won will be equal to what is returned by the print_winner function.
The print_winner function will break (not sure if terminate will be the right term here) if indeed there is a winner (line 17 and 18 of print_winner function). I understand after break on line 18, the function print_winner will terminate but not the whole program. In case break applicable, the result which is true passed on to the value of won?
Not clear what it means by
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
// Check if election has been won bool won = print_winner(); if (won) { break; }
[/dm_code_snippet]
Reply
https://edstem.org/us/courses/176/discussion/2378898?answer=5427665[learn_press_profile]
-
AuthorPosts
- You must be logged in to reply to this topic.