This question already has answers here:
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
(11 answers)
Variable length arrays (VLA) in C and C++
(5 answers)
Closed 6 months ago.
What does " control reaches end of non-void function" means??
How to remove the warnings from out code ?
#include <bits/stdc++.h>
using namespace std;
int LinearSearch()
{
int ans=-1;
cout << "Enter the Size of the array: \n";
int n;
cin >> n;
cout << "Enter the array elements: \n";
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int key;
cout << "Enter the key: \n";
cin >> key;
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
{
cout << "the " << key << " is found at index " << i << endl;
}
return ans;
}
}
int main()
{
while (1)
{
cout << "\t Main Menu\n";
cout << "1. For Linear Search\n";
cout << "2. For Binary Search\n";
cout << "3. For First and last Occurence\n";
int ch;
cout << "Enter the choice: \n";
cin >> ch;
switch (ch)
{
case 1:
cout<< LinearSearch();
break;
case 2:
break;
case 3:
break;
default:
cout << "Invalid Choice OOps!! ";
break;
}
}
return 0;
}
enter image description here
AS I am trying to run it it is giving me Warning Why??
Error is: warning: control reaches end of non-void function [-Wreturn-type]
How to resolve it?
When n is zero, you never reach a return. You need a return after the loop. Returning -1 might be the sensible choice in that situation. (Also, the return in the loop is misplaced...)
It means that int LinearSearch() is expected to return an int but there are code paths where that does not happen. For instance, if n == 0. You fix this by adding a return statement with an appropriate value on that code path. It's probably an error that you have the return within the for() loop as this means you get at most one iteration. Maybe this is what you want?
int LinearSearch()
{
int ans=-1;
cout << "Enter the Size of the array: \n";
int n;
cin >> n;
cout << "Enter the array elements: \n";
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int key;
cout << "Enter the key: \n";
cin >> key;
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
{
cout << "the " << key << " is found at index " << i << endl;
ans = i;
break;
}
}
return ans;
}
Like others have mentioned, the warning indicates one of your code path has no return value. In LinearSearch after the for loop a return is missing. You can use -1 to return when a key match is not found or better still is if your C++ compiler supports C++17 or higher standard then I would suggest using std::optional and to return a "no value" to use std::nullopt and return the "ans" when you actually find the key.
Please look at the code below for a sample implementation.
#include <optional>
using namespace std;
std::optional<int> LinearSearch()
{
int ans;
cout << "Enter the Size of the array: \n";
int n;
cin >> n;
cout << "Enter the array elements: \n";
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int key;
cout << "Enter the key: \n";
cin >> key;
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
{
cout << "the " << key << " is found at index " << i << endl;
return ans;
}
}
return std::nullopt;
}
int main()
{
while (1)
{
cout << "\t Main Menu\n";
cout << "1. For Linear Search\n";
cout << "2. For Binary Search\n";
cout << "3. For First and last Occurence\n";
int ch;
cout << "Enter the choice: \n";
cin >> ch;
switch (ch)
{
case 1:{
auto res = LinearSearch();
if (res) cout<< *res;
else cout << "key not found";
}
break;
case 2:
break;
case 3:
break;
default:
cout << "Invalid Choice OOps!! ";
break;
}
}
return 0;
}
Related
Hello I am trying to go back to switch after every case and I can't figure it out. I've tried with return but I can return just to main and it doesn't save the values from v[i]. Here is the code. The code itself should represent how RAM works on 8 bit. Also, v[0] should be between 0 and 19 and v[0]+v[1] should be less than 19 and I don't know how to implement that.
#include < iostream >
using namespace std;
int main() {
char v[20];
int pc,
functie,
n,
i,
loop;
do {
cout << "Este pornit calculatorul? (0/1) ";
cin >> pc;
}
while ( pc != 1 );
cout << "Ce functie selectati? 1-4 ";
cin >> functie;
switch (functie) {
case 1:
cout << "Citire din memorie" << endl;
cout << "Cate numere cititi din memorie: ";
cin >> n;
for (i = 0; i < n; i++) {
cout << v[i];
}
break;
case 2:
cout << "Scriere in memorie" << endl;
cout << "Cate numere scrieti ";
cin >> n;
for (i = 0; i < n; i++) {
cout << "v[" << i << "]= ";
cin >> v[i];
}
break;
case 3:
cout << "Golirea memoriei";
for (i = 0; i < n; i++)
v[i] = '\0';
break;
case 4:
cout << "Oprirea calculatorului";
exit(0);
break;
default:
cout << "Nu ati selectat nici o functie";
}
return 0;
}
The switch should be included in a loop if you want to iterate over it multiple times.
Also you should not generally include vulgar language in your code, even if it is not in English (6th variable you declared).
Update: I managed to do the code but i still need to have v[0] between 0 and 19 and v[0]+v[1] <=19 and i don't know how to do it.
#include <iostream>
using namespace std;
int main() {
char v[20];
int pc, functie, n, i,loop;
do {
cout << "Este pornit calculatorul? (0/1) ";
cin >> pc;
}
while (pc != 1);
while(loop=1)
{
cout << "Ce functie selectati? 1-4 ";
cin >> functie;
switch (functie) {
case 1:
cout << "Citire din memorie" << endl;
cout << "Cate numere cititi din memorie: ";
cin >> n;
for (i = 0; i < n; i++)
{
cout << "v[" << i << "]="<<v[i]<<" ";
cout<<endl;
}
break;
case 2:
cout << "Scriere in memorie"<<endl;
cout << "Cate numere scrieti ";
cin >> n;
for (i = 0; i < n; i++) {
cout << "v[" << i << "]= ";
cin >> v[i];
}
break;
case 3:
cout << "Golirea memoriei";
for(i=0;i<n;i++)
v[i]='\0';
cout<<endl;
break;
case 4:
cout << "Oprirea calculatorului";
exit(0);
break;
default:
cout << "Nu ati selectat nici o functie";
}
}
}
You can use goto to jump at starting point of switch or any function for sake of simplicity. Consider the following code:
loop:
switch(...) {
case ...
break;
}
goto loop;
Note that it's not always good to use the goto, it may throw serious problems in programs in some situations. Alternatively, you can do the same with for in a very convenient way. The example:
for(; ;)
{
// body of the for loop.
}
Hope you understand.
I have created an array that holds 5 numbers, and the user inputs the numbers. If the mark is less than 0 and greater than 100, I want to print out "invalid mark number". How could I do that?
using namespace std;
int mark[5];
int main ()
{
cout << "enter mark 0: ";
cin >> mark[0];
cout << "enter mark 1: ";
cin >> mark[1];
cout << "enter mark 2: ";
cin >> mark[2];
cout << "enter mark 3: ";
cin >> mark[3];
cout << "enter mark 4: ";
cin >> mark[4];
}
You should use a for-loop to make the code more readable and compact. Because once you introduce if statements, the code size would grow alot. It should look like this:
#include <iostream>
using namespace std;
int mark[5];
int main () {
for (int i = 0; i < 5; i++){
cout << "enter mark " << i << ": ";
cin >> mark[i];
if (mark[i] < 0 || mark[i] > 100){
cout << "invalid mark number\n";
}
}
}
Don't use using namespace std; (read here why) and keep the int mark[5]; inside the main-function (read here why). Also to add to the logic force the user to input again:
#include <iostream>
int main () {
int mark[5];
for (int i = 0; i < 5; i++){
bool valid_input = false;
while (!valid_input){
std::cout << "enter mark " << i << ": ";
std::cin >> mark[i];
if (mark[i] < 0 || mark[i] > 100){
std::cout << "invalid mark number\n";
}
else{
valid_input = true;
}
}
}
}
This is what I have so far. I am trying to edit a dynamically allocated array in C++, however, when the for loop runs, it is skipping over the first item. I need it to get all of the items. Any help is appreciated. Thanks in advance.
#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// Declare Variables
int userChoice = 0;
int numItems = 0;
cout << "How many items will be on your list? ";
cin >> numItems;
string *list = new string[numItems];
// Give the user some options
cout << "1. Add Item" << endl;
cout << "2. Remove Item" << endl;
cout << "3. Sort Items" << endl;
cout << "4. Exit" << endl;
cout << "Enter the number of the operation you wish to perform: ";
cin >> userChoice;
cout << endl;
// Perform the operation
switch(userChoice)
{
case 1:
{
cin.clear(); // Remove new line from cin
for(int i = 0; i < numItems; i++)
{
cout << "Item #" << i + 1 << " --> ";
getline(cin, list[i]);
}
}
break;
case 2:
{
}
break;
case 3:
{
}
break;
case 4:
{
return 0;
}
default:
{
cout << "Error! Invalid Selection" << endl;
}
}
// Output the list
cout << "-------Items-------" << endl
<< *list << endl << endl;
// free memory
delete [] list;
cout << "Enter the number of the operation you wish to perform: ";
cin >> userChoice;
return 0;
}
It seems odd to me to be using the STL for some things (like string) and then use a standard array to hold the strings. Also, list is a standard type of object in STL, so that is not a great name for a variable. This revised code fixes your issues with ignoring the first line, and also uses a vector instead of doing new and delete.
#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
// Declare Variables
int userChoice = 0;
int numItems = 0;
cout << "How many items will be on your myList? ";
cin >> numItems;
cin.ignore ();
vector<string> myList;
while (true)
{
// Give the user some options
cout << "1. Add Item" << endl;
cout << "2. Remove Item" << endl;
cout << "3. Sort Items" << endl;
cout << "4. Exit" << endl;
cout << "Enter the number of the operation you wish to perform: ";
cin >> userChoice;
cin.ignore ();
cout << endl;
// Perform the operation
switch(userChoice)
{
case 1:
{
for(int i = 0; i < numItems; i++)
{
cout << "Item #" << i + 1 << " --> ";
string s;
getline(cin, s);
myList.push_back (s);
}
}
break;
case 2:
{
}
break;
case 3:
{
sort (myList.begin (), myList.end ());
}
break;
case 4:
{
return 0;
}
default:
{
cout << "Error! Invalid Selection" << endl;
}
}
// Output the myList
cout << "-------Items-------" << endl;
copy(myList.begin(), myList.end(), ostream_iterator<string>(cout, "\n"));
} // end of while
}
The project description explicitly says I can't use standard containers, sort functions, or smart pointers
Redone below to not use those things. :)
#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
using namespace std;
int myCompare (const void * a, const void * b)
{
if ((*(string *) a) < *(string *) b) return -1;
if ((*(string *) a) > *(string *) b) return 1;
return 0;
}
int main()
{
// Declare Variables
int userChoice = 0;
int numItems = 0;
cout << "How many items will be on your myList? ";
cin >> numItems;
cin.ignore ();
string *myList = new string[numItems];
while (true)
{
// Give the user some options
cout << "1. Add Item" << endl;
cout << "2. Remove Item" << endl;
cout << "3. Sort Items" << endl;
cout << "4. Exit" << endl;
cout << "Enter the number of the operation you wish to perform: ";
cin >> userChoice;
cin.ignore ();
cout << endl;
// Perform the operation
switch(userChoice)
{
case 1:
{
for(int i = 0; i < numItems; i++)
{
cout << "Item #" << i + 1 << " --> ";
getline(cin, myList [i]);
}
}
break;
case 2:
{
}
break;
case 3:
{
qsort (myList, numItems, sizeof (string *), myCompare);
}
break;
case 4:
{
delete [] myList;
return 0;
}
default:
{
cout << "Error! Invalid Selection" << endl;
}
}
// Output the myList
cout << "-------Items-------" << endl;
for(int i = 0; i < numItems; i++)
cout << myList [i] << endl;
} // end of while
}
The for loop isn't skipping the first element. The first element is just a an empty line.
Because the following clears the error flags.
cin.clear(); // Remove new line from cin --> No!!!!
If you want to skip until the new line you have to use ignore() instead.
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // this removes until newline from cin !
When I'm searching an integer in my dynamic array, the search function isn't working well as its always showing its positioned at 1. whether the data is actually there or not.
What i'm actually trying to do is using dynamic data structure, I'm adding the data. Deleting, searching and saving to txt file. and Loading it back. But the problem is search. I used switch cases and search is at Case 4.
#include<iostream>
#include<string>
#include<fstream> //to save file in text
using namespace std;
int main()
{
int *p1;
int size = 0;
int counter = 0;
p1 = new int[size];
int userchoice;
int i;
int position;
while (1)
{
cout << "Please enter your choice " << endl;
cout << endl;
cout << "To insert Press '1'" << endl;
cout << "To Delete press '2'" << endl;
cout << "To View press '3'" << endl;
cout << "To Search press '4'" << endl;
cout << "To Save Press '5'" << endl;
cout << "To Load Previously saved Data press '6'" << endl;
cout << "To Exit press '7'" << endl;
cout << endl;
cout << "Enter your choice: ";
cin >> userchoice;
switch (userchoice) // User's selection from the menu
{
case 1: //Insert Number
cout << "Enter a Number: ";
cin >> p1[size];
counter++;
size++; //Add's memory space
break;
case 2: //Delete Number
int udelete;
cout << "Enter a number to delete: ";
cin >> udelete; //User enters Number to be deleted
//Checking if the number is in an array.
for (position = 0; position<size; position++)
{
if (p1[position] == udelete)
break;
}
if (position>size)
{
cout << "The number is not in the memory: ";
cout << endl;
break;
}
for (i = position; i<size; i++) {
p1[i] = p1[i + 1];
}
size--;
cout << "Successfully Deleted!!! ";
cout << endl;
break;
case 3: // View
for (i = 0; i<size; i++)
{
cout << "Your data" << " " << i << " " << "-->" << p1[i] << endl;
}
break;
case 4:
{
int usearch;
cout << "Please enter the figure you would like to search ";
cout << "->";
cin >> usearch;
for (i = 0; i>size; i++)
{
if (p1[size] == usearch)
break;
}
if (usearch == size)
{
cout << "not found. ";
}
cout << "Position at: " << i + 1 << endl;
break;
}
case 5: // Save
{
ofstream save;
save.open("Dynamicdata.txt", ofstream::out | ofstream::app);
for (i = 0; i<size; i++)
{
save << p1[i] << endl;
}
save.close();
cout << "File Saved " << endl;
break;
}
case 6: //Read from File
{
string read;
ifstream file_("Dynamicdata.txt");
if (file_.is_open())
{
while (getline(file_, read))
{
cout << read << "\n";
}
file_.close();
}
else
cout << "File Not open" << endl;
cin.get();
break;
}
case 7:
{
return 0;
}
}
}
}
Your problem is that the size of your array is 0. Here you set size to 0 and then size for the size of p1
int size=0;
int counter=0;
p1 = new int[size];
You are going to need to make size bigger so that you can actually store elements in p1 or instead of using arrays and dynamic memory allocation use a std::vector and let it handle that for you.
The code has undefined behaviour because initailly the dynamically allocated array pointed to by pointer p1 has no elements
int size=0;
^^^^^^^^^^
//...
p1 = new int[size]; // size is equal to 0
So in the following code snippet an atttempt to write data to p1[size] results in undefined behaviour
case 1: //Insert Number
cout<<"Enter a Number: ";
cin>>p1[size]; // undefined behaviour
^^^^^^^^^^^^^
counter++;
size++; //Add's memory space
break;
You need to reallocate the array to reserve memory for the added new element.
Take into account that for example this loop
for (i = 0; i>size; i++)
^^^^^^^
{
if (p1[size] == usearch)
break;
}
will never iterate because variable i set to zero can not be greater than size that at least equal to zero.
And it would be logically more correct to write
if (p1[i] == usearch)
^^^^^
instead of
if (p1[size] == usearch)
^^^^^^^^
Consequently this if statement
if (usearch == size)
^^^^^^^
{
cout << "not found. ";
}
should be replaced with this for statement
if (i == size)
^^
{
cout << "not found. ";
}
I have created an Array that is sized by user input.
int spotInArray = 0;
Bankcard* a = NULL;
int n;
cout << "Enter number of cards" << std::endl;
cin >> n;
a = new Bankcard[n];
This is my code I have in my switch for the user to select which card they want to delete.
int choice;
cout << "Enter Number of card you would like to delete: " << endl;
cin >> choice;
for (int i = n; i < spotInArray; i++)
{
a[n] = a[n + 1];
a[choice - 1] = 0;
}
I am getting this error on a[choice - 1] = 0;
IntelliSense: no operator "=" matches these operands
Here is the full code.
int main()
{
//Bankcard bankcard1("Blue Card", 1, .05, 3000.00, 430.32, 200.35, 124.00);
int spotInArray = 0;
Bankcard* a = NULL; // Pointer to int, initialize to nothing.
int n; // Size needed for array
cout << "Enter number of cards" << std::endl;
cin >> n; // Read in the size
a = new Bankcard[n]; // Allocate n ints and save ptr in a.
//for (int i=0; i<n; i++) {
//a[i] = bankcard1;
//bankcard1.show();
//}
int choice;
showMenu();
cin >> choice;
while (choice != 6)
{
switch(choice)
{
case 1 : {
string productName;
int cardNum;
double interestRate;
double maxLimit;
double outstandingBalance;
double purchaseAmount;
double paymentAmount;
cout << "Enter Card Name(No spaces, no special characters)" << std::endl;
cin >> productName;
cout << "Enter Number of Card" << std::endl;
cin >> cardNum;
cout << "Enter interest Rate" << std::endl;
cin >> interestRate;
cout << "Enter Max Limit" << std::endl;
cin >> maxLimit;
cout << "Enter Outstanding Balance" << std::endl;
cin >> outstandingBalance;
cout << "Enter Purchase Amount" << std::endl;
cin >> purchaseAmount;
cout << "Enter Payment Amount" << std::endl;
cin >> paymentAmount;
Bankcard bankcard1(productName, cardNum, interestRate, maxLimit, outstandingBalance, purchaseAmount, paymentAmount);
a[spotInArray] = bankcard1;
spotInArray++;
break;
}
case 2 : update();
break;
case 3 : {
int choice;
cout << "Enter Number of card you would like to delete: " << endl;
cin >> choice;
for (int i = 0; i < n; i++)
{
a[n] = a[n + 1];
a[choice - 1] = 0;
}
}
deleteCard();
break;
case 4 : overLoad();
break;
case 5 : {
for ( int i = 0; i < spotInArray; i++)
{
cout << a[i];
}
}
break;
case 6 : exit();
break;
}
showMenu();
cout << endl;
cin >> choice;
};
std::cin.get();
std::cin.get();
return 0;
}
Unless there are other code that you haven't shown, currently this for loop shouldn't even run:
for (int i = n; i < spotInArray; i++)
{
a[n] = a[n + 1];
a[choice - 1] = 0;
}
because spotInArray is 0 and i starts at n (and you are incrementing i, too).
Are you sure it's failing on that line?
There are few incorrect things with the code. First of all, a[n] is invalid. Valid index of array of size n are 0 to n-1. Avoid handling memory your self. Use std::list instead in this case ( if there is frequent removals ).
std::list<Bankcard> bCards(n);
// Take input to for the cardToRemove.
bCards.erase( bCards.begin() + cardToRemove );