Check if array is empty or not C++ - c++

Please tell me how to check whether array is empty on not?
see my code after the step of code modify comment.I want a message "Sorry no value added so far".
#include<iostream>
using namespace std;
int count=0;
//----------------------------------------------------------//
//---------menu items list start from this position---------//
//----------------------------------------------------------//
void menu(int n){cout<<"\nEnter an option: \n";
cout<<"1- Add new value\n2- Search Value\n3- Modify value\n4- Print Value\n5- Print sum of all values\n6- Quit/terminate\n";
}
//-----------------------------------------------------------//
//---------Funtion to add new values starts from here--------//
//-----------------------------------------------------------//
void AddNewValue(int a[]){
cout<<"Enter a value\n";
cin>>a[count]; //taking input to array
count++;
}
//------------------------------------------------------------------------//
//---------Function to search a value from array starts from here---------//
//------------------------------------------------------------------------//
void SearchValue(int a[]){
int num,jawad=0;
cout<<"Enter a number to search\n";
cin>>num;
for(int starter=0;starter<count;starter++){ //starting loop from 1st value of array
if (num==a[starter])
jawad=1; //switching jawad from 0 to 1 if value found
}
if(jawad==1)
cout<<"value exists at "<<count<<"th position\n";
else cout<<"Value does not exist";
}
//-------------------------------------------------------------------//
//---------Function to modify value in array start from here---------//
//-------------------------------------------------------------------//
void ModifyValue(int a[]){
int modification,position;
cout<<"Enter the position of a number to modify";
cin>>position;
cout<<"Enter a number to modify";
cin>>modification;
a[position-1]=modification; //calculating index from enterd value and placing that equal to new number
}
//-----------------------------------------------------------//
//---------Function to Print values starts from here---------//
//-----------------------------------------------------------//
void PrintValue(int a[]){
cout<<"The stored values are : ";
for(int c=0;c<count;c++) //start loop and tak out all the values then print them
{cout<<a[c]<<' ';
if (a[c]==0)
cout<<"jawad adil";
}
}
//------------------------------------------------------------------------------//
//----------Function to Take sum of the values of array starts from here--------//
//------------------------------------------------------------------------------//
void PrintSum(int a[]){
int r=0,sum=0;
cout<<"The sum of all the values is : ";
while(r<count){
sum=sum+a[r]; //taking sum of all the values using loop
r=r+1;
}
cout<<sum<<'\n';
}
//---------------------------------------------//
//----------main body starts from here---------//
//---------------------------------------------//
int main(){
int n;
int a[100];
while(n!=6){
menu(n);
cin>>n;
if (n==1){
AddNewValue(a); //calling functions using if else statments
}
else if(n==2){
SearchValue(a);
}
else if(n==3){
ModifyValue(a);
}
else if(n==4){
PrintValue(a);
}
else if(n==5){
PrintSum(a);
}}
}
how can I do that? I am doing but it is not working.

You should add a "check" in your "modify" function.
Original:
void ModifyValue(int a[]){
int modification,position;
cout<<"Enter the position of a number to modify";
cin>>position;
cout<<"Enter a number to modify";
cin>>modification;
a[position-1]=modification;
With "check":
void ModifyValue(int a[]){
//Check
if(count == 0)
{
cout << "Sorry no value added so far";
return; //Exit from function
}
int modification,position;
cout<<"Enter the position of a number to modify";
cin>>position;
cout<<"Enter a number to modify";
cin>>modification;
a[position-1]=modification;
}
Also I recommend you to use switch instead of "if else if"
if (n==1){
AddNewValue(a); //calling functions using if else statments
}
else if(n==2){
SearchValue(a);
}
else if(n==3){
ModifyValue(a);
}
else if(n==4){
PrintValue(a);
}
else if(n==5){
PrintSum(a);
}
like:
switch (n)
{
case 1:
AddNewValue(a);
break;
case 2:
SearchValue(a);
break;
case 3:
ModifyValue(a);;
break;
//And so on...
default:
cout << "Unknown option";
}
Also in this code you don't need any arguments in
void menu(int n)
So you can make
void menu()
instead.
Also I recommend you to place whitespaces between operands and operators (words)
cout << "Enter a value\n";
cin >> a[count]; //taking input to array
count++;
instead
cout<<"Enter a value\n";
cin>>a[count]; //taking input to array
count++;

Related

How to add a value to an already full array without using std::copy to make a new one

I'm trying to develop a program that, in case 2, after an array has been "filled" it adds another space so you are able to add another value to your original array. I tried my best but failed miserably. I cannot use std::copy to just copy the array and add it to a new one with more space in it. Any help is appreciated, thanks!
#include <iostream>
#include <string>
using namespace std;
void stampa (string x[], int q){ //Cout all inserted names
int i;
cout<<"Your names are: "<<endl;
for (i=0; i<q; i++){
cout<<x[i]<<endl;
}
}
void carica(string x[], int q){ //Function to insert the names
int i;
for(i=0; i<q; i++){
cout<<"Insert the "<<i+1<<" name:"<<endl;
cin>>x[i];
}
}
void controllo (int &x){ //Error if a negative number is inserted
while (x<=0) {cout<<"Error! Insert a positive number:"<<endl;
cin>>x;
}
}
int main(){
int scelta, n;
string nome;
bool exit=false;
cout<<"How many names do you want to enter?"<<endl;
cin>>n;
controllo(n);
string a[n];
carica(a,n);
do{
system("cls");
cout<<"1) Print your names"<<endl;
cout<<"2) Insert a new name"<<endl;
cout<<"3) Exit"<<endl<<endl;
cin>>scelta;
switch (scelta){
case 1:
stampa(a,n);
system("pause");
break;
case 2:
cout << "Enter new name to insert: " << endl;
cout<<"Done!"<<endl;
system("pause");
break;
case 3:
exit=true;
cout<<"Goodbye!"<<endl;
break;
}
}while (!exit);
system("pause");
}
Try using std::vector instead of a simple array, or create an array through pointers.
vector: https://www.youtube.com/watch?v=Jh2urtP00Zg
Pointers: https://www.programiz.com/cpp-programming/memory-management

how to make my program run again C++

I have given the following question.
Write a menu driven program with following options:
Add new value
Search value
Modify value
Print value
Print sum of all values
Quit / Terminate
You have to create 5 options as five function. Add another function to show menu options.
and here is my code:
#include<iostream>
using namespace std;
float f[100]={0};
//1st option
void AddNewValue(){int input;
cout<<"Enter a value\n";
cin>>f[input];
}
//2nd option
void SearchValue(){int i, search;
cout<<"Enter a value to search\n";
cin>>search;
int match=0;
for (int i=1;i<=100;i++)
{if (f[i]==search)
{match=1;
break;}
}
if (match==1){cout<<"Matched value found\n";
}
else {cout<<"No match found\n";}
}
//3rd option
void ModifyValue(){int input1;
cout<<"Enter the position at which you want to modify value\n";
cin>>input1;
cout<<"Enter a value\n";
cin>>f[input1-1];
}
//4th option
void PrintValue(){int i;
for (i=1;i<=100;i++)
{cout<<f[i]<<' ';}
}
//5th option
void PrintSum(){int i,sum;
for(i=1;i<=100;i++)
{sum=f[i]+f[i+1];}
cout<<"Sum is : "<<sum;
}
//starting Function
void menu(){int x;
cout<<"Enter an option: \n";
cout<<"1- Add new value\n2- Search Value\n3- Modify value\n4- Print Value\n5- Print sum of all values\n6- Quit/terminate\n";
cin>>x;
if(x==1){
AddNewValue();
}
else if (x==2){
SearchValue();
}
else if(x==3){
ModifyValue();
}
else if(x==4){
PrintValue();
}
else if(x==5){
PrintSum();
}
else{
}
}
int main(){
menu();
}
And I want to make my full program run again and again until the user enter a wrong option.
One option available to you is to create a while loop encapsulating the body of your menu() function, and using break; if the user enters 6.
void menu(){
int x = 0;
while(1){
cin >> x;
//your code here
if(x==6)
break;
}
}
This example will cause your menu to repeat until the user enters 6.
The purpose of break; is to 'break' from the while loop. In this case, breaking will end your menu()and return to main().
Further, it is good practice to add return 0; to the end of your main function.
You can use a loop and make it run untill user give a specific input. In below code once the program will run and then it will ask user to input 5 to exit or any other key to run again, and if user gives 5 as input, then it will stop or if user gives any other input then program will run again.
Hope it is clear and help you.
#include<iostream>
using namespace std;
float f[100]={0};
//1st option
void AddNewValue(){int input;
cout<<"Enter a value\n";
cin>>f[input];
}
//2nd option
void SearchValue(){int i, search;
cout<<"Enter a value to search\n";
cin>>search;
int match=0;
for (int i=1;i<=100;i++)
{if (f[i]==search)
{match=1;
break;}
}
if (match==1){cout<<"Matched value found\n";
}
else {cout<<"No match found\n";}
}
//3rd option
void ModifyValue(){int input1;
cout<<"Enter the position at which you want to modify value\n";
cin>>input1;
cout<<"Enter a value\n";
cin>>f[input1-1];
}
//4th option
void PrintValue(){int i;
for (i=1;i<=100;i++)
{cout<<f[i]<<' ';}
}
//5th option
void PrintSum(){int i,sum;
for(i=1;i<=100;i++)
{sum=f[i]+f[i+1];}
cout<<"Sum is : "<<sum;
}
//starting Function
void menu(){int x;
cout<<"Enter an option: \n";
cout<<"1- Add new value\n2- Search Value\n3- Modify value\n4- Print Value\n5- Print sum of all values\n6- Quit/terminate\n";
cin>>x;
if(x==1){
AddNewValue();
}
else if (x==2){
SearchValue();
}
else if(x==3){
ModifyValue();
}
else if(x==4){
PrintValue();
}
else if(x==5){
PrintSum();
}
else{
}
}
int main(){
int repeater;
do{
menu();
cout<<"Enter 5 to exit or any other key to run the program again :";
cin>>repeater;
}while(repeater != 5);
}
Keep it simple. The function in charge of displaying the menu should only display the menu and return the user's choice.
enum choice
{
ADD_NEW_VALUE,
SEARCH_VALUE,
// ...
QUIT
};
choice menu()
{
choice result = QUIT;
// display menu
// input choice
// (the more I think about it, the more I'd split it in two separate functions)
return result;
}
int main()
{
while (true) {
switch (menu())
{
case ADD_NEW_VALUE: AddNewValue(); break;
// ...
case QUIT: return 0;
}
}
}
This helps menu()'s testing and make it easier to add new options and new features.
If the user selects a correct option, call the menu function again. Otherwise, return control to main. I think this may work.
int menu(){int x;
cout<<"Enter an option: \n";
cout<<"1- Add new value\n2- Search Value\n3- Modify value\n4- Print Value\n5- Print sum of all values\n6- Quit/terminate\n";
cin>>x;
if(x!=1||x!=2||x!=3||x!=4||x!=5) return 0;
if(x==1){
AddNewValue();
}
else if (x==2){
SearchValue();
}
else if(x==3){
ModifyValue();
}
else if(x==4){
PrintValue();
}
else if(x==5){
PrintSum();
}
menu();
}
You could also wrap your code in a do-while loop.
void menu(){
do{
int x;
cout<<"Enter an option: \n";
cout<<"1- Add new value\n2- Search Value\n3- Modify value\n4- Print Value\n5- Print sum of all values\n6- Quit/terminate\n";
cin>>x;
if(x==1){
AddNewValue();
}
else if (x==2){
SearchValue();
}
else if(x==3){
ModifyValue();
}
else if(x==4){
PrintValue();
}
else if(x==5){
PrintSum();
}
}while(x==1||x==2||x==3||x==4||x==5);
}

Program compiles but I think switch is ignored.

I am currently studying c++ but I fell behind a little bit, so I apologize if my question is obvious.
I have to create a program that asks for a student's name, GPA, Year of admission, and get a random 5 digit number generated for that person. The number of students will not exceed 42.
My program compiled (somehow) and I am able to get the error for invalid menu selection, however, whenever I give a valid selection (currently 1) nothing happens.
Maybe I am missing something, this is why I need help.
Here is my code.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//print all the menu options
void print_menu()
{
cout<<"\nRCNJ Registrar Menu:"<<"\n"
<<"\n"
<<"[1] Add a student"<<"\n"
<<"[2] Display all students"<<"\n"
<<"[3] Display by year"<<"\n"
<<"[4] Display statistics"<<"\n"
<<"[5] Quit"<<"\n";
}
//get and return the student's name
void get_name(string& student_name) //call student_name after that.
{
cout<<"Please enter the sudent's name: ";
cin >> student_name;
cout<<"\n";
}
//validate and return gpa
double get_gpa()
{
double student_gpa = 0;
cout<<"Please enter the GPA: ";
cin >>student_gpa;
cout<<"\n";
while (student_gpa > 4 || student_gpa < 0)
{
cout<<"Please enter a valid GPA for the student (0.00 - 4.00): ";
cin >> student_gpa;
cout<<"\n";
}
return student_gpa;
}
//validateand return year
int get_year()
{
int student_year = 0;
cout<<"Please enter the year: ";
cin >> student_year;
cout<<"\n";
while (student_year >2016 || student_year <1972)
{
cout<<"Please enter a valid year (min 1972, max 2016): ";
cin >> student_year;
cout<<"\n";
}
return student_year;
}
//generate the student's R#
int generate_number()
{
int r_number;
srand (time(NULL));
r_number = rand() % 89999 + 10000;
return r_number;
}
//save info. Include get_name, get_gpa, get_year
void input_new_student()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int s_name, s_gpa, s_year, r_num;
get_name(student_name);
get_gpa();
get_year();
generate_number();
}
//display all students in the proper format
void print_all()
{
}
//get a year as selection and print all students that are the same year
void print_by_year()
{
}
//display statistics based on entered students
void print_statistics()
{
}
//validate and return the menu option selected by the user.
//it should call print_menu defined earlier
int get_selection(int menu_choice)
{
menu_choice = 0;
cout<<"\n"
<<"Selection: ";
cin >> menu_choice;
cout<<"\n";
while (menu_choice > 5 || menu_choice< 1)
{
cout<<" Menu choice is invalid. Please re-enter (1 - 5): ";
cin>> menu_choice;
cout<<"\n";
}
return menu_choice;
}
int main()
{
string student_name;
double student_gpa;
int student_year;
int r_number;
int menu_choice;
int s_name=0;
int s_gpa=0;
int s_year=0;
int r_num=0;
string nameArray[42];
s_name++;
double gpaArray[42];
s_gpa++;
int yearArray[42];
s_year++;
int ramapoArray[42];
r_num++;
print_menu();
get_selection(menu_choice);
switch (menu_choice)
{
case 1:
input_new_student();
nameArray[s_name] = student_name;
gpaArray[s_gpa] = student_gpa;
yearArray[s_year] = student_year;
ramapoArray[r_num] = r_number;
break;
}
return 0;
}
I dont have permission to comment, hence adding it here.
In you main(),
get_selection(menu_choice);
switch (menu_choice)
You return menu_choice, but there is none to take the value, you end you using garbage value as it is uninitialized.
So two ways you can do it, either by passing the address/reference of menu_choice or by return value. try either of these it should work, though I have not gone through the rest of your program.
As suggested by others, try a debugger e.g. gdb?

Doesn't show output during input of values using vector and sort

vector<int> var;
int numb;
cout<<"Enter number: ";
while (cin>>numb) {
if (cin.get()==char(32)) {
var.push_back(numb);
shellsort(var);
for (int i=0; i<var.size(); i++) {
cout<<var[i]<<" ";
}
} else if (cin.get()=='\n') {
break;
}
}
I used ascii code 32 to read space and a sort function. Loop the value to show current list. The problem is the current sorted list wont show during input of value. What to do?
You are calling, cin.get(), twice unnecessarily, fix that, and you are good to go.
Here is the fixed code:
vector<int> var;
int numb;
cout<<"Enter number: ";
while(cin>>numb)
{
char c = cin.get();
if(c==char(32))
{
var.push_back(numb);
shellsort(var);
for(int i=0;i<var.size();i++)
{
cout<<var[i]<<" ";
}
cout<<endl;
}
else if(c=='\n')
{
break;
}
}

Program on cricket scoreboard

Why is the following code not giving results and how to get results?
Whenever I run the code, it first asks for the names of the players of two teams playing the match, then it shows the menu from which if we select any one of the option it again asks for the batsman name which is not according to the program designed. My research on the code and the problem is that I think buffer memory is full but I don't know how to free it, any help would be beneficial. Thank you
#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
class scorecard{
char batname[11][20];
int runscored[11];
char situation[11][10];
char mode[11][15];
char bowlername[11][20];
float oversplayed[11];
int maiden[11];
int runsgiven[11];
int wicketstaken[11];
public:
void updatebatsman(void);
void updatebowler(void);
void displaybat(void);
void displaybowl(void);
void menu(void);
scorecard()
{for(int n=0;n<12;n++)
{
runscored[n]={0};
oversplayed[n]={0};
maiden[n]={0};
runsgiven[n]={0};
wicketstaken[n]={0};
}
}
};
int main()
{
int jb=0;
scorecard s1;
int kb;
s1.menu();
do
{
cout<< "Enter the option"<<endl;
cout<<"(1) Display batting score"<<endl<<"(2) Display Bowling score"<<endl<<"(3) Update batting score"<<endl;
cout<<"(4) Update Bowling score"<<endl;
cin >>kb;
switch(kb)
{
case 1 : s1.displaybat();
break;
case 2 :s1.displaybowl();break;
case 3:s1.updatebatsman();break;
case 4:s1.updatebowler();break;
default:cout<<"Wrong choice";
}
}while (jb<1);
}
void scorecard::updatebowler(void)
{char bowlname[20];
int str,k,option,overnumbers,maidenumb,uprun,upwicket;
cout<<"Enter Bowler name:";
cin.getline(bowlname,20);
for( k=0;k<11;k++)
{str= strcmp(bowlername[k],bowlname);
if (str== 0)
{
cout<<"Menu for Bowler information update "<<endl;
cout<<"(1) Update Number of overs"<<endl<<"(2) Update maiden overs"<<endl<<"(3) Update runs given"<<endl;
cout<<"(4) Update wickets taken"<<endl;
cin >> option;
switch(option)
{
case 1:{cout<<"Enter Numbers of overs to be updated:";
cin >>overnumbers;
cout<<endl;
oversplayed[k]+=overnumbers;
break;
}
case 2:{cout <<"Enter the number of maiden overs to be updated:";
cin>>maidenumb;
cout<<endl;
maiden[k]+=maidenumb;
break;
}
case 3:{cout <<"Enter the number of runs to be added:";
cin>>uprun;
cout<<endl;
runsgiven[k]+=uprun;
break;
}
case 4: {cout<<"Enter number of wickets to be updated:";
cin >>upwicket;
cout<<endl;
wicketstaken[k]+=upwicket;
}
default:cout<<"wroung choice";
}
break;
}
}
if (str!=0)
cout <<"You entered wrong player."<<endl;
}
void scorecard::updatebatsman(void)
{char batsmaname[20];
int str,k;
cout<<"Enter Batsman name:";
cin.getline(batsmaname,20);
for( k=0;k<11;k++)
{str= strcmp(batname[k],batsmaname);
if (str== 0)
{
cout<<"enter runs scored:";
cin>>runscored[k];
cout<<endl<<"enter weather out or not out:";
cin>>situation[k];
cout<<endl<<"enter mode(if batsman out) by which batsman was out:";
cin>>mode[k];
break;
}
}
if (str!=0)
cout <<"You entered wrong player."<<endl;
}
void scorecard::displaybat(void)
{
cout << "Batsman name"<<'t'<<"Runs scored"<<'t'<<"situation"<<'t'<<"mode"<<endl;
for(int j=0;j++;j<12)
{
cout<<batname[j]<<'t'<<runscored[j]<<'t'<<situation[j]<<'t'<<mode[j]<<endl;
}
}
void scorecard::displaybowl(void)
{
cout << "Bowler name"<<'t'<<"overs played"<<'t'<<"maiden overs"<<'t'<<"wicket taken"<<'t'<<"Runs given"<<endl;
cout<<endl;
for(int j=0;j++;j<12)
{
cout<<bowlername[j]<<'t'<<oversplayed[j]<<'t'<<maiden[j]<<'t'<<wicketstaken[j]<<'t'<<runsgiven[j]<<endl;
}
}
void scorecard::menu(void)
{
cout<<"Enter the name of players of batting team"<<endl;
for (int k=0;k<11;k++)
{
cout <<"Enter name of player "<<k+1<<":";
cin>>batname[k];
}
cout <<"Enter the name of players of bowling team"<<endl;
for (int n=0;n<11;n++)
{
cout <<"Enter name of player "<<n+1<<":";
cin>>bowlername[n];
}
}
This is very wrong:
for(int j=0;j++;j<12)
It should be:
for(int j=0; j < 11; j++)
You are also missing a break in your case 4 statement for the options:
case 4: {cout<<"Enter number of wickets to be updated:";
cin >>upwicket;
cout<<endl;
wicketstaken[k]+=upwicket;
break;
}
default:cout<<"wroung choice";
Without the break you will see also the output wrong choice when the user selects option 4.