Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The following code segment reads a string (consists of letters and digits) from

ID: 3765680 • Letter: T

Question

The following code segment reads a string (consists of letters and digits) from the keyboard and count how many ‘0’ s in the string

string str;
int zeroCount=0;
getline(cin,str);
  
for(int i = 0 ; i <= str.length() – 1 ; i++){
if(str[i]== ‘0’)
zeroCount++;
}
Hint: If you are not familair with length() function, str.length() returns the number of actual characters in a string, and does not count the null character at the end of the string. Ex. string str = "Arizona"; str.length() is 7 (Arizona is 7 characters).

You need to write three different codes;

a) Rewrite the above code using a while loop. [5 Points]


b) Modify the above code (code given or your answer to part i above) so that it count total number of digits in the string str. ASCII values for digits are values are between 48-57. ('0' is 48 and '9' is 57 in ASCII values) [5 Points] (The string may contain both digits and other characters, so you need to check each character one by one)


c) Write a C++ code segment that reads integers from the keyboard until user enter 0 and determine the largest integer entered. [10 Points] (The number of inputs is unlimited)

Explanation / Answer

#include <iostream>
#include <string>

using namespace std;


int main()
{

   string str;
   int zeroCount=0;
   int totalDigits = 0;
   getline(cin,str);

   int i = 0;
   int ch;
   while(i < str.length()){
      if(str[i]== '0')
        zeroCount++;
      // ASCII values for digits are values are between 48-57. ('0' is 48 and '9' is 57 in ASCII values)
      ch = (int)str[i];
      if(ch >=48 && ch <=57)
          totalDigits++;
      i++;
   }

   cout << str <<" : 0's count : " <<zeroCount << "   Total digits:" <<totalDigits <<endl;

   int largest = 0;
   int number = 0;
   int count = 0;
   cout << "Enter a digit (0 for exit): " <<endl;
   do {

       cin >> number;
       if(number != 0) {
           if(count == 0)
               largest = number;
           if(number > largest)
               largest = number;
           count++;
       }
   }while(number != 0);

   cout << "Largest of " << count << " numbers : " <<largest <<endl;


}

---------output----------------

test120t4sd0-1
test120t4sd0-1 : 0's count : 2   Total digits:6
Enter a digit (0 for exit):
1
-1
25
-45
100
-10
5
0
Largest of 7 numbers : 100

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote