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

Write a program that asks the user to enter a total budget for purchases, then r

ID: 3741742 • Letter: W

Question

Write a program that asks the user to enter a total budget for purchases, then repeatedly asks the

user for a number of items and price per item that will be bought. The program should stop asking

for new items when the budget has reached 0. Your program should use a

while

loop.

The program should function as follows (the items underlined are to be entered by the user):

Please enter your budget: 100

Please enter the items and price: 10, 4

Please enter the items and price: 3, 5

Please enter the items and price: 2, 10

Please enter the items and price: 10, 3

You cannot buy the last items.

Your remaining budget is 25.

Algorithm design process

1. What variables are needed and what type?

a. Need variables for

items, price, budget

.

2. Get budget from user

a. Print out the text to prompt the user, then use

scanf

to read in the budget.

3. Set up the

while

loop

a. What should be the control condition indicating that there is still money

available?

b. Inside the loop:

?

Ask the user to enter items and price, and use

scanf

to read in the

values

?

Update the budget with the amount taken by the last entered items

(items * price)

4. Print out the remaining budget

a. What happens if the budget becomes negative? The user cannot buy the last

entered items. After the

while

loop we have to check if the budget is negative

and do the following:

?

Add the value of the last entered items (items*price) back to the budget

?

Print the message to the user to indicate that the last items cannot be

purchased

b. What happens if the budget goes exactly to zero? Everything is ok: all the items

can be bought and the

while

loop will not ask for new items to be entered.

Question #2

Problem 1:

Write a program with the file name

lab5_problem1.c

that asks the user to enter a sentence

ended by a period, a question mark, or an exclamation mark and prints out the number of space

characters (spaces, new lines, tabs) in that sentence.

The program should function as follows (the items underlined are to be entered by the user):

Enter a sentence (end by ‘.’ or ‘?’ or ‘!’):

This is a sample

sentence.

Number of space characters: 2

Number of new line characters: 2

Number of tabs: 1

Note:

Above there is a new line before the first word of the sentence and after the word “sample”,

there are two spaces (after “is” and after “a”) and a tab (after the word “This”).

Algorithm design process

1. What variables are needed and what type?

a. Need variables to store the count of

characters, new_lines

and

tabs

.

b. Any other variables that you need? A variable of type

char

to read in the input

from the user.

2. Get input from user

a. Print out the text to prompt the user

b. Set up a loop (

while

,

do-while

) to read in character by character until a

‘.’

or

‘?’

or

‘!’

are found. What should be the logical condition that will enable

the loop to run until

‘.’

or

‘?’

or

‘!’

are encountered?

3. Inside the loop

a. For every character read, see if it is a new line, space or tab, in order to increment

the appropriate counter. Ignore any other characters. What is the best way to

structure this? A cascaded

if-else

statement would be too long, so the best

option would be a

switch

statement. Think about structuring the

switch

statement in the most compact way possible (group cases that go together and

think of what should go in the

default

case).

4. At the end of the loop print out the number of spaces, new lines and tabs.

Problem 2:

Write a program with the file name

lab5_problem2.c

that asks the user to enter a sentence

ended by a period and prints out the number of times each character appears in the sentence, only

for the characters that occur at least once. Uppercase and lowercase version of a letter should be

counted toward the same letter. The program should function as follows (the items underlined are

to be entered by the user):

Enter a sentence (end by ‘.’): This is a short sentence.

Occurrences of ‘a’: 1

Occurrences of ‘c’: 1

Occurrences of ‘e’: 3

Occurrences of ‘h’: 2

Occurrences of ‘i’: 2

Occurrences of ‘n’: 2

Occurrences of ‘o’: 1

Occurrences of ‘r’: 1

Occurrences of ‘s’: 4

Occurrences of ‘t’: 3

Algorithm design process

1. What variables are needed and what type?

a. A variable to store the

character

entered by the user.

b. An array of integers to store the number of

occurrences

for each character.

What should be the size of the array? How many characters there are in the

alphabet? Don’t forget to properly initialize the array – with what should we

initialize it?

c. Any other variables that you need? Maybe an integer counter used in a loop to

print the number of occurrences at the end.

2. Get input from user

a. Print out the text to prompt the user

b. Set up a loop (

while

,

do-while

) to read in character by character until a

‘.’

is found.

3. Inside the loop

a. In order to handle upper/lower case situations, we should convert each character

read to lowercase (use the

tolower

function from the string library).

b. For every character read, increment the corresponding value in the occurrences

array. How do we find the index associated with each character? Hint: character

‘a’

should be associated with the first element of the array (index 0), character

‘b’

with index 1 and so on. We can get the index by subtracting

‘a’

from the

value of the current character. This index can now be used to properly increment

the values in the occurrences array.

4. Print the results.

a. Set up a

for

loop that iterates through the occurrences array and prints out the

statistics. How do we print the ‘

a’, ‘b’, ‘c’

... letters in the output string?

We can obtain the character by adding the value of the index to character

‘a’

(this is the offset value for all the subsequent letters). Thus 0 will become

‘a’

, 1

will be

‘b’

and so on.

Explanation / Answer

Program 1:

#include <stdio.h>

int main()

{

    int budget, items, price, sum=0;

    printf("Enter Your Budget:");

    scanf("%d",&budget);

    while(budget > 0)

    {

        printf(" Please enter the items and price:");

        scanf("%d %d",&items,&price); /*Give one space between items and price*/

        if((budget >= (items * price)))

        {

            sum = sum + (items * price);

            budget = budget - (items * price);

        }   

        else

        {

            printf(" You cannot buy the last items.");

            printf(" Your remaining budget is:%d",budget);

            break;

        }

        if(budget == 0)

        {

            printf(" Everything is ok: all the items can be bought");

            break;

        }

    }

    return 0;

}

lab5_problem1.c

#include <stdio.h>

int main()

{

  

   int i=0,space_count = 0,tab_count = 0,newline_count = 0;

char ch, str[250];

printf("Enter a sentence (end by ‘.’ or ‘?’ or ‘!’):");

do

{

   ch = getchar();

   str[i++] = ch;

   if(ch == ' ')

    space_count = space_count + 1;

   else if(ch == ' ')

    tab_count = tab_count + 1;

   else if(ch == ' ')

    newline_count = newline_count + 1;

}while(ch == '.' || ch == '?' || ch == '!');

printf(" Number of space characters:%d",space_count);

printf(" Number of new line characters: %d",space_count);

printf(" Number of tabs:%d",space_count);

    return 0;

}

lab5_problem2.c

#include <stdio.h>

int main()

{

  

   char ch,str[500];

   int i=0,len,count[26];

    /* Input string from user */

    printf("Enter a sentence (end by ‘.’):");

    while((ch = getchar())!= '.')

        str[i++] = ch;

    while((ch = getchar()) != '.')

    len++;

    /* Initialize count of each character to 0 */

    for(i=0; i<26; i++)

        count[i] = 0;

    /* Find total number of occurrences of each character */

    for(i=0; i<len; i++)

    {

        /* If the current character is lowercase alphabet */

        if(str[i]>='a' && str[i]<='z')

             count[str[i] - 97]++;

        else if(str[i]>='A' && str[i]<='Z')

             count[str[i] - 65]++;

      

    }

    /* Print the count of all characters in the string */

    for(i=0; i<26; i++)       /* If current character exists in given string */

       if(count[i] != 0)

           printf("Occurrences of '%c' = %d ", (i + 97), count[i]);

    return 0;

}

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