is there a better way i could have written this program? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int c;
int d;
int e;
int f;
int aa = 0;
int bb = 0;
int cc = 0;
int dd = 0;
int ee = 0;
int ff = 0;
const string odd = "ODD";
const string even = "EVEN";
cout << "enter 6 numbers " << endl;
cin >> a;
cin >> b;
cin >> c;
cin >> d;
cin >> e;
cin >> f;
aa = a % 2;
bb = b % 2;
cc = c % 2;
dd = d % 2;
ee = e % 2;
ff = f % 2;
if(aa == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(bb == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(cc == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(dd == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(ee == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(ff == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
return 0;
}
for example is there a way to make it do the same thing but with less code, anything I should have included?
is there an easier way than having to write 6 if/else statements - is there a way to do all 6 in one statement or loop?
how could i improve its efficiency?

Write this function:
void outputEvenness(int n)
{
static const string odd = "ODD";
static const string even = "EVEN";
if(n % 2){
cout << odd<< endl;
} else {
cout << even << endl;
}
}
then call it using outputEvenness(a); outputEvenness(b); etc.

First of all you should include header <string>if you use class std::string.
Also there is no sense to define these strings when they are used as string literals. Also instead of different variables it would be better to define only one array. The auxiliary variables are also unnecessary.
If to assume that you may not use arrays then I would write the program the following way
#include <iostream>
#include <initializer_list>
int main()
{
const size_t N = 6;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
const char *odd = "ODD";
const char *even = "EVEN";
std::cout << "enter " << N << " numbers: ";
std::cin >> a >> b >> c >> d >> e >> f;
for ( int x : { a, b, c, d, e, f } )
{
if ( x % 2 == 0 )
{
std::cout << x << " is " << even << std::endl;
}
else
{
std::cout << x << " is " << odd << std::endl;
}
}
return 0;
}
If you are allowed to use arrays then the program could look as
#include <iostream>
int main()
{
const size_t N = 6;
int a[N] = {};
const char *odd = "ODD";
const char *even = "EVEN";
std::cout << "enter " << N << " numbers: ";
for ( int &x : a ) std::cin >> x;
for ( int x : a )
{
if ( x % 2 == 0 )
{
std::cout << x << " is " << even << std::endl;
}
else
{
std::cout << x << " is " << odd << std::endl;
}
}
return 0;
}
For this simple program there is no sense to define a separate function that will check whether a number is even or odd because it is this program that is such a function.:)

Use arrays and loops:
int a[6]; // Array of 6 ints
cout << "enter 6 numbers" << endl;
// Input the 6 numbers
for (int i = 0; i < 6; i++)
{
cin >> a[i];
}
// Output the results
for (int i = 0; i < 6; i++)
{
cout << a[i] << " is " << (a[i] & 1 ? "ODD" : "EVEN") << endl;
}

int value = 0;
string response = "";
cout << "enter 6 numbers " << endl;
for(int i=0; i<6; i++)
{
cin >> value;
value % 2 == 0 ? response+="even\n" : response+="odd\n";
}
cout << response;

Related

How could I check If a variable is a certain number multiple times while changing what to do if It matches?

I want to check what the variable "num" is from 0 - 15 How can I check if it is one of those numbers and what number it is so far I've got.
#include <iostream>
using namespace std;
int num = 0;
int main()
{
cout << "Number to check:";
cin >> num;
{
if num = 0;
cout << "0000";
{
if num = 2;
cout << "0010";
{
if num = 1;
cout << "0001";
{
if num = 3;
cout << "0011";
{
if num = 4;
cout << "0100";
{
if num = 7;
cout << "0111";
{
if num = 5;
cout << "0101";
{
if num = 6;
cout << "0110";
{
if num = 8;
cout << "1000";
{
if num = 9;
cout << "1001";
{
if num = 10;
cout << "1010";
{
if num = 11;
cout << "1011";
{
if num = 12;
cout << "1100";
{
if num = 13;
cout << "1101";
{
if num = 14;
cout << "1110";
{
if num = 15;
cout << "1111";
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return 0;
How may I be able to do this If I can't, how can I convert a number to a 4-bit Binary byte? And if possible how can I make sure the number inputted is in the range of 0 - 15 and that there isn't letters in the inputted string
The program below does what you want.
#include<iostream>
#include <bitset>
int main() {
int num = 0;
std::cout << "Number to check: ";
std::cin >> num;
while (std::cin.fail() || num > 15 || num < 0) {
std::cout << "Error! Invalid Input \n";
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << "Number to check: ";
std::cin >> num;
}
std::bitset<4> value;
value = { static_cast<unsigned long>(num) };
std::cout << value.to_string() << "\n";
return 0;
}
Use <bitset>
#include <bitset>
#include <iostream>
#include <string>
int main()
{
std::string input{ "12" };
// std::cin >> input;
unsigned long number = std::stoul(input); // does number checking
if (number < 16) // do value checking
{
std::bitset<4> value{ number };
std::cout << value.to_string() << std::endl;
}
}
Since you declared num as an integer, your program won't work if you input nondigit characters during cin. I believe the shortest variant of your code without dealing with std::bitset would be
const int MAX_BITS = 4;
cout << "Number to check:";
cin >> num;
if (num < 0 || num > (1 << MAX_BITS) - 1) {
cout << "Invalid number, next time enter between 0 and " << (1 << MAX_BITS) - 1;
return 0;
}
for(int bit = MAX_BITS - 1; bit >= 0; --bit){
cout << ((num & (1 << bit)) > 0);
}
cout << endl;

C++ - Reading from a file bug

My program is working as I want it to work (It is on Bosnian language so the cout of the program is not that important). The program is about reading some text from file and then couting what I want to
The only problem I have with this program is that for some reason it is showing the two 0 0 at the end of the text file even though I do not have it in my text file
Here is the code:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
struct proizvod
{
char naziv[100];
char proizvodac[100];
int cijena = 0;
int kolicina = 0;
};
bool poredjenje(proizvod a, proizvod b)
{
if (a.cijena != b.cijena )
return a.cijena > b.cijena;
}
void sortiranje(proizvod a[], int n)
{
sort(a, a+n, poredjenje);
}
int main()
{
ifstream datoteka;
datoteka.open("proizvodi.txt.txt");
int brojStvari = 0;
int sumaProizvoda = 0;
int ukupnaVrijednost = 0;
char* spisakProizvoda[100];
int brojFIAT = 0;
int spisakCijena = 0;
proizvod automobili[100];
if (datoteka.fail())
{
cout << "Ne postojeca datoteka";
exit(1);
}
while (datoteka.good() && !datoteka.eof())
{
datoteka >> automobili[brojStvari].naziv >> automobili[brojStvari].proizvodac >> automobili[brojStvari].cijena >> automobili[brojStvari].kolicina;
++brojStvari;
++sumaProizvoda;
}
for (int i = 0; i < brojStvari; i++)
{
cout << automobili[i].naziv << " " << automobili[i].proizvodac << " " << automobili[i].cijena << " " << automobili[i].kolicina << endl;
}
for (int i = 0; i < brojStvari; i++)
{
ukupnaVrijednost += automobili[i].cijena;
if (automobili[i].kolicina == 0)
{
spisakProizvoda[i] = automobili[i].proizvodac;
}
else if (automobili[i].proizvodac == "FIAT")
{
brojFIAT++;
}
}
char pomocna[100];
cout << endl;
cout << "Ukupan broj proizvoda u datoteci: " << sumaProizvoda << endl;
cout << "Ukupan vrijednost proizvoda u datoteci: " << ukupnaVrijednost << endl;
cout << "Spisak automobila sa cijenom 0 su: ";
for (int i = 0; i < brojStvari; i++)
{
if (!spisakProizvoda[i])
{
cout << "Ne postoje ti proizvodi " << endl;
break;
}
else
cout << spisakProizvoda[i] << endl;
}
cout << "Broj prozivoda koji proizvodi FIAT: " << brojFIAT << endl;
cout << "Sortirani proizvodi prema cijeni: " << endl;
sortiranje(automobili, brojStvari);
for (int i = 0; i < brojStvari; i++)
{
cout << automobili[i].proizvodac << endl;
}
return 0;
}
And here is the cout
Golf Volskwagen 5000 5
AudiRS5 Audi 50000 3
0 0
Ukupan broj proizvoda u datoteci: 3
Ukupan vrijednost proizvoda u datoteci: 55000
Spisak automobila sa cijenom 0 su: Ne postoje ti proizvodi
Broj prozivoda koji proizvodi FIAT: 0
Sortirani proizvodi prema cijeni:
Audi
Volskwagen
Can anybody tell me what is the problem ?
P.S : Sorry if you do not understand the program itself I apologize sincerely
You are seeing the extra 0 0 at end most likely due to an extra empty line at end of proizvodi.txt.txt file. This happens because the new line is also accepted as input but since there are no entries, the entries in struct proizvod retain default 0 values for cijena and kolicina which gets printed out as 0 0.
Update your main() code to reading file like follow and it will work as expected:
while (datoteka >> automobili[brojStvari].naziv >>
automobili[brojStvari].proizvodac >> automobili[brojStvari].cijena >>
automobili[brojStvari].kolicina) {
++brojStvari;
++sumaProizvoda;
}

how I can print an array as a vector form

I want to cout an array as a row vector but when I write:
int main() {
int B[3]={0};
for (int w = 0; w <2; w++) {
cout <<"B="<<" "<< B[w] << " ";
}
cout << endl;
return 0;
}
The output is B=0 B=0
But I want output to be like:
B=(0 0)
For a fixed size array of only I would probably even prefer a oneliner like this, because I can read it at first glance:
cout << "B=(" << B[0] << " " << B[1] << " " << B[2] << ")\n";
For a container B with a dynamic or very high number of elements n, you should probably do something like this:
cout << "B=(";
if(n > 0)
{
cout << B[0];
// note the iteration should start at 1, because we've already printed B[0]!
for(int i=1; i < n; i++)
cout << ", " << B[i]; //I've added a comma here, so you get output like B=(0, 1, 2)
}
cout << ")\n";
This has the advantage, that no matter what number of elements, you don't end up with trailing commas or unwanted whitespace.
I'd reccommend making a generic (template) function for the purpose of printing array/std::vector content anyways - it's really useful for debugging purposes!
int main() {
int B[3] = { 0 };
cout << "B=(";
for (int w = 0; w < 3; w++) {
cout << B[w];
if (w < 2) cout << " ";
}
cout << ")" << endl;
return 0;
}
Output should be now:
B=(0 0 0)
The simplest way to do this is:-
#include<iostream>
using namespace std;
int main()
{
int B[3]={0};
cout << "B=(";
for (int w = 0; w < 3; w++)
{
cout << B[w] << " ";
}
cout << ")" << endl;
return 0;
}
the output will be B= (0 0 0 )
You can try this one if you want:
#include <iostream>
using namespace std;
int main() {
int B[3]={0};
cout << "B=(";
for (int w = 0; w <2; w++) {
cout << B[w];
if(w != 1) cout << " ";
}
cout << ")" << endl;
cout << endl;
return 0;
}
The output is:
B=(0 0)
The line if(w != 1) checks whether you 've reached the last element of the array. In this case the last index is 1, but in general the if statement should be: if(w != n-1) where n is the size of the array.

C++ : Count even / odd numbers in a range

My program has to count how many numbers in a range are even and how many of them are odd but I can't seem to figure it out.It kinda works
but when I put numbers in it spouts out nonsense. I'm an extreme nooob when it comes to programing, I think that the problem has to be at line 21 for (i=n; i<=m; i++) { ?
But I'm not sure. I have a programing book but it does not help much,maybe someone can help?
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i;
}
else {
b=b+i;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
Assuming you mean even and odd numbers your problem lies in this code:
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i; // increase number of even numbers by i
}
else {
b=b+i; // increase number of odd numbers by i
}
}
What you might want do to do is add 1 (instead of whatever i is):
for (i = n; i <= m; ++i) {
if (i % 2 == 0)
++a; // increase number of even numbers by one
else
++b; // increase number of odd numbers by one
}
Also I'd suggest using better variable names, for example even and odd instead of a and b and so on. It makes code easier to understand for everybody, even for you.
Just a little more tips. Assigning variables as soon as you declare them is good practice:
int m = 0;
You can declare variable inside of for loop, and in your case there is no need to declare it out of it:
for (int i = n; i <= m; ++i) { ... }
Example how it can change look and clarity of your code:
#include <iostream>
using namespace std;
int main() {
int from = 0,
to = 0,
even = 0,
odd = 0;
cout << "Enter a number that begins interval: ";
cin >> from;
cout << "Enter a number that ends interval: ";
cin >> to;
for (int i = from; i <= to; ++i) {
if (i % 2 == 0)
++even;
else
++odd;
}
cout << " even numbers: " << even << endl;
cout << " odd numbers: " << odd << endl;
return 0; // don't forget this! main is function returning int so it should return something
}
Ok, so as per the new clarification the following should work
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a++;
}else {
b++;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
So the following changes were done:
The for loop was closed
a = a + i or b = b + i was wrong as you are adding the counter value to the count which should be a++ or b++. Changed that also
The last two lines where you are showing your result was out of the main method, brought them inside the main method
Hope you find this useful.
You don't need to use loop to count even and odd numbers in a range.
#include <iostream>
int main ()
{
int n,m,even,count;
std::cin >> n >> m;
count=m-n+1;
even=(count>>1)+(count&1 && !(n&1));
std::cout << "Even numbers: " << even << std::endl;
std::cout << "Odd numbers: " << count-even << std::endl;
}
#include <iostream>
using namespace std;
int main()
{
int n, i;
cin >> n;
cout << " even : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 == 0)
cout << i << " ";
}
cout << " odd : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 != 0)
cout << i << " ";
}
return 0;
}
//input n = 5
// output is even : 2 4 6 8 10
// odd : 1 3 5 7 9
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a = 0;
b = 0;
for (i = n; i < = m; i++) {
if (i%2 == 0){
a = a + 1;
} else {
b = b + 1;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
Not sure why you are looping through all the elements (half of them are going to be even and the other half odd). The only case where you have to consider when the interval length is not divisible by two.
using namespace std;
int main()
{
int n;
int m;
int x;
int odds;
int evens;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
cout << n << " " << m << endl;
x = m - n + 1;
odds = x / 2;
evens = odds;
if (x % 2 != 0) {
if (n % 2 == 0) {
evens++;
} else {
odds++;
}
}
cout << " even numbers: " << evens << endl;
cout << " odd numbers: " << odds << endl;
}
This is a more readable version of #Lassie's answer

Can't find a solution to a c++ program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So I have to write a code for the following program:
Write a program with a main function and menu for choosing a function to:
a) input data for students into an array (faculty number, age, sex) (up to 25)
b) rewrite the data for the male and female students into two new arrays and output the arrays and the average age
c) output the youngest student and make the arrays into ascending order of the age and output the arrays
d) search for a student by a faculty number and output his information
Ok, so far so good. The a) and d) are working as they should, but b) and c) are giving me some trouble. On c) it says the youngest student is -88758375 year-old and it isn't outputting the arrays. And on b) it gives me a logical error and it says Integer division by zero and crashes the program. I really tried to find any mistakes but I'm stuck, so I ask you for some help:)))
#include "stdafx.h"
#include <iostream>
using namespace std;
const int N = 25;
struct student
{
int fN;
int age;
char sex;
};
// a)
void input(student fN[N], int numberOfStudents)
{
for (int i = 0; i<numberOfStudents; i++)
{
cout << "Faculty number: ";
cin >> fN[i].fN;
cout << "Age: ";
cin >> fN[i].age;
cout << "Sex: ";
cin >> fN[i].sex;
cout << endl;
}
}
// b)
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int m, int f)
{
int avgAgeM = 0, avgAgeF = 0;
for (int i = 0; i < numberOfStudents; i++)
{
if (fN[i].sex == 'm')
{
fNm[m].fN = fN[i].fN;
fNm[m].age = fN[i].age;
fNm[m].sex = fN[i].sex;
m++;
avgAgeM = avgAgeM + fN[i].age;
}
else if (fN[i].sex == 'f')
{
fNf[f].fN = fN[i].fN;
fNf[f].age = fN[i].age;
fNf[f].sex = fN[i].sex;
f++;
avgAgeF = avgAgeF + fN[i].age;
}
cout << endl;
for (int i = 0; i < m; i++)
{
cout << "\tFaculty number: " << fNm[i].fN << "\tAge: " << fNm[i].age << "\tSex: " << fNm[i].sex << endl;
}
cout << "Average male age: " << avgAgeM / m << "\n\n";
for (int i = 0; i<f; i++)
{
cout << "\tFaculty number: " << fNf[i].fN << "\tAge: " << fNf[i].age << "\tSex: " << fNf[i].sex << endl;
}
cout << "Average female age: " << avgAgeF / f << "\n\n";
}
}
// c)
void ascendingAge(student fNm[N], student fNf[N], int m, int f)
{
int x, y;
char z;
for (int i = 0; i < m-1; i++)
for (int j = 0; j < m-i-1; j++)
{
if (fNm[j].age > fNm[j + 1].age)
{
x = fNm[j].age;
y = fNm[j].fN;
z = fNm[j].sex;
fNm[j + 1].age = fNm[j].age;
fNm[j].age = x;
fNm[j + 1].fN = fNm[j].fN;
fNm[j].fN = y;
fNm[j + 1].sex = fNm[j].sex;
fNm[j].sex = z;
}
}
for (int i = 0; i < f-1; i++)
for (int j = 0; j < f-i-1; j++)
{
if (fNf[j].age > fNf[j + 1].age)
{
x = fNf[j].age;
y = fNf[j].fN;
z = fNf[j].sex;
fNf[j + 1].age = fNf[j].age;
fNf[j].age = x;
fNf[j + 1].fN = fNf[j].fN;
fNf[j].fN = y;
fNf[j + 1].sex = fNf[j].sex;
fNf[j].sex = z;
}
}
cout << "The youngest female student is " << fNf[0].age << " year-old." << endl;
for (int i = 0; i < m; i++)
cout << "\tFaculty number: " << fNm[i].fN << "\tAge: " << fNm[i].age << "\tSex: " << fNm[i].sex << endl;
for (int i = 0; i<f; i++)
cout << "\tFaculty number: " << fNf[i].fN << "\tAge: " << fNf[i].age << "\tSex: " << fNf[i].sex << endl;
cout << endl;
}
//d
void searchStudent(student fN[N], int numberOfStudents)
{
int x, index;
bool yes = false;
cout << "Enter a faculty number: ";
cin >> x;
for (int i = 0; i < numberOfStudents; i++)
if (fN[i].fN == x)
{
yes = true;
index = i;
}
cout << endl;
if (yes == true)
cout << "\tFaculty number: " << fN[index].fN << "\tAge: " << fN[index].age << "\tSex: " << fN[index].sex << endl;
else
cout << "No such faculty number.\n\n";
}
int main()
{
student fN[N], fNm[N], fNf[N];
int numberOfStudents, m = 0, f = 0;
char check;
cout << "Enter number of students: ";
cin >> numberOfStudents;
BACK:
cout << "\n\n";
cout << "\t a) \n\t b) \n\t c) \n\t d)\n Press'q' to exit.\n\n";
cin >> check;
switch (check)
{
case 'a':
input(fN, numberOfStudents);
goto BACK;
break;
case 'b':
rearrange(fN, fNm, fNf, numberOfStudents, m, f);
goto BACK;
break;
case 'c':
ascendingAge(fNm, fNf, m, f);
goto BACK;
break;
case 'd':
searchStudent(fN, numberOfStudents);
goto BACK;
break;
case 'q':
return 0;
break;
default:
cout << "Wrong input.\n";
goto BACK;
}
system("pause");
return 0;
}
In the function rearrange you need pass m and k by reference:
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int& m, int& f):
Оr they will not be changed
You seem to want m and f to be outputs from this function
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int m, int f)
but that would work only if passed by reference:
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int& m, int& f)
You should guard against divide by zero by testing. Instead of:
cout << "Average male age: " << avgAgeM / m << "\n\n";
use
if (m)
cout << "Average male age: " << avgAgeM / m << "\n\n";
else
cout << "There are zero males\n\n";
and similarly for f