First Semester CS Student needs help understanding statement in While loop - c++

I normally post on DreamInCode.net but the site seems to be down right now. I'm a first semester CS student at De Anza. I don't understand really what the lineCount = 1; does in the else statement. I know what it does when I remove the statement but I don't understand it. If I could have someone explain it to me maybe in a different way that the book just happens to skip over, I would greatly appreciate it.
#include <stdio.h>
int main (void) {
int num;
int lineCount;
printf ("\nEnter a starting number to decend between 1 and 100: ");
scanf ("%d", &num);
if (num > 100)
num = 100;
lineCount = 0;
while (num >= 0)
{
if (lineCount < 10)
lineCount++;
else
{
printf ("\n");
lineCount = 1; // this line here is what I don't understand
}
printf ("%4d", num--);
}
return 0;
}

lineCount isn't actually counting lines. It's counting the number of numbers you've printed on the current line.
When that reaches 10, it breaks the line and starts a new one, resetting the counter to 1. 1 instead of 0 because you're placing another number on the new line.

Related

Longest substring of 2 alternating characters

I am trying to solve such competitive programming problem:
Alex likes to laugh a lot. Laughter is a sequence of alternating letters "a" and "h". For example, "ahahaha", "hah" and "a" are laughter and "abacaba" and "hh" are not.
Alex speaks very quickly, so all his words merge into one big one. You need to find out how long he can laugh. You have a line - a recording of Alex's conversation. Determine the maximum length of laughter in this conversation.
Input file is called "laugh.in"
Output file is called "laugh.out"
Input data:
The first line of the input file contains a single integer N (1 < N ≤ 10^5) - the length of the string with Alex's conversation. The second line contains a string of small Latin letters of length N - recording Alex's conversation.
Output data:
Output one number - the longest laugh length in Alex's conversation
Here's some examples of how input/output data must look like.
Examples:
Input in laugh.in
5
ahaha
Output in laugh.out
5
Input in laugh.in
24
ahahrunawayahahsofasthah
Output in laugh.out
4
Input in laugh.in
10
ahahaahaha
Output in laugh.out
5
So, here is my code, that is supposed to solve given problem:
#include <algorithm>
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
freopen("laugh.in", "r", stdin);
freopen("laugh.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, i;
cin >> n;
char *s = new char[n + 1];
getchar();
for (i = 0; i < n; i += 1)
{
s[i] = getchar();
}
s[n] = '\0';
int max_length = 0;
int length = 0;
for (i = 0; i < n; i += 1)
{
length += !length && (s[i] == 'a' || s[i] == 'h');
if ((s[i] == 'a' && s[i + 1] == 'h') ||
(s[i] == 'h' && s[i + 1] == 'a'))
{
length += 1;
}
else
{
max_length = max(max_length, length);
length = 0;
}
}
cout << max(max_length, length) << endl;
delete[] s;
return 0;
}
It only passes 13 tests with other 33 resulting in "Wrong answer" verdict.
So why my code is not working? Please, give counter examples to it or explain error.
Any help would be highly appreciated.
First of all, do not write everything in main (learn to avoid it ASAP).
Secondly, the task doesn't say anything about opening files.
Avoid the use of new delete in modern C++; it is a bad practice to use it.
Here is pattern you can start over:
size_t laugh_length(const std::string& s)
{
...
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
size_t l;
cin >> l;
std::string s;
s.reserve(l);
cin >> s;
cout << laugh_length(s) << '\n';
}
After an extra comment form OP I see another bit problem with OP code:
ios::sync_with_stdio(false);
and then use of:
getchar();
which is cstdio API which synchronization has been disabled.
https://wandbox.org/permlink/PJzjc1joKQgmpbwa
vs https://wandbox.org/permlink/aH3OypI94CpgNuxd

The program crashes after executing while loop

The code shuts down after executing the while loop and does not execute the last 2 printf statements. I don't know whats wrong.. after the loop goes around for the chosen times the program just closes.
#include <stdio.h>
int main()
{
int numberofq;
int questionansc;
int questionansic;
int counter;
int answer;
numberofq = 0;
questionansc = 0;
questionansic = 0;
counter = 0;
answer = 0;
while(numberofq <1 || numberofq >5)
{
printf("Hello enter the amount of questions you want between 1 and 5 \n");
scanf("%d", &numberofq);
} // End While
//Program runs until the counter is less than users wanted question number.
while (counter < numberofq)
{
//Question 1
printf("Question 1. what is 2+2? \n");
scanf("%d" , &answer);
//if users answer is equal to 4.
if (answer == 4)
{
printf("You entered %d, you are correct\n", answer);
questionansc = questionansc +1;
} //End If
//If the answer is not equal to 4.
else
{
printf("You entered %d, you are wrong correct answer is 4 \n", answer);
questionansic = questionansic +1;
} // End Else
counter = counter +1;
//End Question 1.
} //End While
printf("You got %d questions correct \n" , questionansc);
printf("You got %d questions wrong" , questionansic);
flushall();
return 0;
} // End Main`
It actually prints them and then exits, but it exits so quickly you don't have a chance to see this.
You can pause execution using system("pause") on Windows, but that's considered bad practice. You could use getch() or something, but you could also simply invoke the program from an existing CMD/Terminal and in this way the output will stay there after the program is done.

How to repeat a for loop in C language

I am a C language beginner. I got this assignment to program for diving score. the rule is that the score has to be between 0 to 10, if the score is invalid, the program should ask for a new score, and there should be at least 4 judges to give the score.
I am having problem with the part with the for loop, I want the program to keep checking if the score is invalid or not, but I couldn't repeat the for loop. please help me, here is my code.
for (index = 0; index < judges; index++)
{
printf ("Enter the score for judges #%d(1-10): ", index + 1);
scanf ("%f", &score[index]);
if ((score[index] >= 0) && (score[index] <= 10))
{
totalscore += score[index];
}
else
{
totalscore = 0;
for (index = 0; index < judges; index++)
{
printf ("11111Enter the score for Judges #%d(0-10): ", index + 1);
scanf ("%f", &score[index]);
if ((score[index] >= 0) && (score[index] <= 10))
{
totalscore += score[index];
return EXIT_SUCCESS;
}
Use this pattern:
do
{
prompt();
scanf(&variable);
}
while (is_invalid (variable));
This way, you only need to check if the variable is valid in one place and you only need to prompt in one place.
Your multiple whiles and ifs are error prone and hard to get right.
So instead of:
printf ("Enter the number of judges (must bewteen 4-8): ");
scanf ("%d", &judges);
if ((judges < 4) || (judges > 8)){
while (true) {
printf ("\ninvaild number of judges\n\nEnter the number of judges (must between 4-8): ");
scanf ("%d", &judges);
if ((judges >= 4) && (judges <= 8)) {
break;
}}}
Use:
do
{
printf ("\n\nEnter the number of judges (must between 4-8): ");
scanf ("%d", &judges);
}
while ((judges < 4) || (judges > 8));
why you use the same variable "index" in the inner for loop? it'll mess up everything. suppose you have 4 judges, you have inputed 3 and 5. you try to input 17, and now the index is 2, right? but the score is invald, so it will goto the "else { xxxxx }" , here you have a inner for loop "for (index = 0; index < judges; index++)" , so the variable "index" come back to 0! IMO in this case, "while" is better:
while ((score[index] < 0) || (score[index] > 10))
printf(xxxxxxx)
scanf(xxxxxxx)
if you really need more than one for loop, you should use different variables:
for (i=0; i<judges; i++)
/*DO STH*/
for (j=0; j<judges; j++)
/*DO STH*/
for (k=0; k<judges; k++)
/*DO STH*/
Looking at your code, I believe that your problem isn't understanding "for" loops in C but rather building the correct flow of your program (your "algorithm" if you will) before approaching the code.
Practice Pseudo-Code for this:
For Each Judge:
Continue to ask for score until it is valid
Or you can break it down even more:
Beginning of loop:
Current Judge = 0
current Score = invalid
Do this while score is invalid
ask score of current judge.
Increment Current Judge
Unless no more judges, go to beginning of loop

Loop doesn't stop!? (C++ programming)

I don't understand why my loop stops, i want the user to keep asking for a number and find its square root. If the user enters negative number THEN it should stop. please help, cant see my mixtake...
CODE:
int main (void)
{
double number, calc;
printf ("Enter a number to find its sqrt");
while (1)
{
scanf ("%lf",&number);
if (number > 0)
{
calc = sqrt(number);
printf ("The sqrt of %lf is %lf", &number, &calc);
}
else
printf ("Try again:\n");
}
return (0);
}
Not allowed to answer but, I see thanks you two!!
(Didnt know i must exist loop)
You must exit the loop somewhere.
if(number < 0)
break;
Alternatively you can do this (which would be better in this case):
number = 0;
while(number >= 0)
{
....
}

Nested loops with C++ coin toss

I have to write a program that runs a loop for a coin toss. I am supported to enter a number into the console and have it run a loop of the coin toss for that many times. I need to use nested loops. I have been working on this for hours and cannot make it work.
The console i/o is supposed to look like below:
Enter the number of tosses to perform [0=exit]: 3
Heads
Tails
Heads
Enter the number of tosses to perform [0=exit]: 2
Tails
Tails
Enter the number of tosses to perform [0=exit]: 0
This is the code i have so far:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main ()
{
srand(time(0));rand();
int result = rand() % 2;
while (true)
{
int n; // this many tosses
cout << "How many tosses";
cin >> n;
cin.ignore (1000, 10);
if (n == 0)
break;
for (int i = 0; i < n; i++)
//random number generator
{
if (result == 0)
cout<< "Heads"<<endl;
else if (result == 1)
cout << "Tails"<<endl;
else if (result != 0 || result !=1)
return 0;
} //for
}//while
}//main
Your for loop doesn't have the part that you are actually trying to execute inside of {}. Try adding the braces around the part you want to loop and see if that fixes it for you.
I edited the indentation in your code to show you the only line that will actually be looping (the srand(time(0)))
You need brackets around the loop block, i.e.
for( int i = 0; i < n; i++ )
{
// Code goes here
}
As shown above, you need to initialize i.
Put the seeding of rand() before the while(...) loop.
You need to move int result = rand() % 2; inside your for loop! Otherwise you will get the same result every single time until you restart the application.
for (int i = 0; i < n; i++)
//random number generator
{
int result = rand() % 2;
if (result == 0)
cout<< "Heads"<<endl; /* to make your output look like your example you should removed the <<endl from here */
else if (result == 1)
cout << "Tails"<<endl; /* and here */
else if (result != 0 || result !=1)
return 0;
} //for
/* and put it here */
cout << endl;