C++ primers Ex 1.11

Exercise 1.11: Write a program that prompts the user for two integers.
Print each number in the range specified by those two integers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

int main() {
	// c++ primer pg 39
	// take two values and print all numbers in the range specified by the input
	int v1=0,v2=0;
	int lower=0,upper=0;
	std::cout << "Enter two values: " << std::endl;
	std::cin >> v1 >> v2;
	if (v1>v2) {
		upper=v1;
		lower=v2;
	}
	else if (v1<v2) {
		upper=v2;
		lower=v1;
	}
	else {
		upper=v1;
		lower=v1;
	}
	while (lower<=upper) {
		std::cout << lower << " " << std::endl;
		++lower;
	}
}
closed account (48T7M4Gy)
Well done!
If we give this program the following input:

42 42 42 42 42 55 55 62 100 100 100

then the output should be

42 occurs 5 times
55 occurs 2 times
62 occurs 1 times
100 occurs 3 times

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main() {
	int currVal=0,val=0,count=0;
	if (std::cin >> currVal) {
		count=1;
		while (std::cin >> val) {
			if (currVal==val) {
				count++;
			}
			else {
				std::cout << currVal << " occurs " << count <<" times." << std::endl;
				currVal=val;
				count=1;
			}
		}
		std::cout << currVal << " occurs " << count <<" times." << std::endl;
	}
	return 0;
}


Algorithm
1
2
3
4
5
6
7
8
9
10
11
12
get currVal
currVal.count=1
get val (*)
   if currVal=val
      currVal.count++
      go to (*)
   else
      print currVal.count
      set currVal=val
      currVal.count=1
      go to (*)
print currVal.count
Last edited on
Exercise 1.22: Write a program that reads several transactions for the same
ISBN . Write the sum of all the transactions that were read.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include "Sales_item.h"

int main() {
	/*
	Sales_item book;
	std::cin >> book;
	std::cout << book << std::endl;
	*/

	Sales_item pre,post;
	if (std::cin >> pre) {
		while (std::cin >> post) {
			pre+=post;
		}
	}
	std::cout << pre << std::endl;

	return 0;
}
closed account (48T7M4Gy)
Is there a question here or should I understand this to be a show and tell?
Exercise 1.23: Write a program that reads several transactions and counts
how many transactions occur for each ISBN .
Exercise 1.24: Test the previous program by giving multiple transactions
representing multiple ISBN s. The records for each ISBN should be grouped
together.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include "Sales_item.h"

int main() {
	Sales_item first,second;
	int count;
	if (std::cin >> first) {
		count=1;
		while (std::cin >> second) {
			if (first.isbn()==second.isbn()) {
				++count;
			}
			else {
				std::cout << first.isbn() << " " << count << std::endl;
				first=second;
				count=1;
			}
		}
		std::cout << first.isbn() << " " << count << std::endl;
	}
}
closed account (48T7M4Gy)
Don't miss the next gripping episode!
Topic archived. No new replies allowed.