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

Write a program that takes a dollar amount (...XXX.XX) as a string input and ins

ID: 3809665 • Letter: W

Question

Write a program that takes a dollar amount (...XXX.XX) as a string input and inserts commas every three digits if the number is large. You should search for the "." and then count back three characters from that location, inserting a comma every 3 digits until the character at index 0 is reached. See the attached source file for how it is done in C++. Perform the same operation using C.

#include <iostream>
#include <iomanip>

using namespace std;

void dollarFormat(string &);

int main()
{
string s;
cout << "Enter dollar amount in the form nnnn.nn :";
cin >> s;
dollarFormat(s);
cout << "Here is the amount formatted: ";
cout << s << endl;

return 0;
}

void dollarFormat(string &currency)
{
int dp;
dp = currency.find('.');
if(dp > 3)
{
for(int x = dp-3; x > 0; x-= 3)
{
currency.insert(x, ",");
}
currency.insert(0, "$");
}
}

Convert this C++ code to C only

Explanation / Answer

PROGRAM CODE:

#include <stdio.h>
#include <string.h>

void dollarFormat(char* s);

int main(void) {
   char s[20];
printf("Enter dollar amount in the form nnnn.nn :");
scanf("%s",s);
dollarFormat(s);
printf("Here is the amount formatted: ");
printf("%s ",s);
return 0;
}
int find(char *s)
{
   for(int i=0; i<strlen(s); i++)
   {
       if(s[i] == '.')
           return i;
   }
}

void insert(char string[], int index, char toadd)
{
   char next;
   char current = toadd;
   for(int i=index; i<strlen(string); i++)
   {
       next = string[i];
       string[i] = current;
       current = next;
   }
}
void dollarFormat(char currency[])
{
int dp;
dp = find(currency);
if(dp > 3)
{
for(int x = dp-3; x > 0; x-= 3)
{
insert(currency, x, ',');
}
insert(currency, 0, '$');
}
}

OUTPUT:

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