binary search in c++ using 2d array [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Write a loop to ask the user for a gpa and check that it's not negative before doing the search end the loop when the user enters a negative value. When there is a match, print the corresponding student number; when there is no match, print "No match".
I am working on the binary search function. I want to code to check and stop if a negative number is entered and print the student nummber (or "Not found") when a gpa is entered.
void search (double AVGgpa[][NUM_STUDENTS])
{
double gpa;
int first = 0,
last = NUM_STUDENTS - 1,
mid,
position = -1;
int row = 2;
bool found = false; // not found yet
cout << "Enter gpa(-1 to end): ";
cin >> gpa;
if (gpa==-1)
{
cout<<"You enter a nagative value"<<endl;
}
while (!found && first <= last)
{
mid = (first + last) / 2;
if (AVGgpa[row][mid]== gpa)
{
cout << "found at index " << mid << endl;
found = true;
}
else if (AVGgpa[row][mid]> gpa)
last = mid - 1;
else
first = mid + 1;
}

Assuming your data is correct and the array sorted by row, you are probably running into trouble because of float-inacurracy.
Look at the following questions for details: What is the most effective way for float and double comparison?
From that you can use a comparision function like:
bool doubleCompare(double d1, double d2)
{
static const double epsilon = 0.001; // Define this as needed
return std::fabs(d1 - d2) < epsilon;
}
If that does not help you, you should check your input data and/or post more code, since your binary search looks ok to me.

Related

Error in program to find the Armstrong numbers between intervals given by the user [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Error:
//Count(variable) not declared! error.
But I have declared it. This is a program to calculate the number of Armstrong digits in the interval given by the user. It will continue to run until there is at least one Armstrong number in the interval. I have used a Do-While loop for this purpose.
C++:
#include<iostream>
#include<cmath>
using namespace std;
//Function to check if the number is an Armstrong number
bool Armstrong(int n) {
int number, original, remainder, result = 0, k = 0;
original = n;
//Calculating the number of digits
while (original != 0) {
original /= 10;
++k;
}
original = n;
while (original != 0) {
remainder = original % 10;
result += pow(remainder, k);
original /= 10;
}
if (result == n)
return true;
else
return false;
}
//Checking Armstrong in the interval
int main() {
do {
int start, stop, n, i = 1;
std::cout << "Enter Starting Point: ";
std::cin >> start;
std::cout << "Enter Stop Point: ";
std::cin >> stop;
n = start;
int count = 0; //printing the numbers in the interval
for (; start <= stop; start++) {
if (Armstrong(start)) {
std::cout << "Armstrong Number " << i << " : " << start;
count++;
i++;
}
n--;
}
//It is showing the error here. "Count not Declared"
}
while (count == 0);
}
The problem is that you declare int count; inside the do-while loop, so you can't check for it in the loop condition. Move it to outside of the loop:
int count = 0;
do {
int start, stop, n, i = 1;
...
} while (count == 0);

Display powers in C++ loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have to solve following exercise
Write a program to display 1,5,25,125 upto n terms.
I am in 11th grade and I have tried of many ways of writing this program.
Value of control variable is one, and it's less than n.
But by how much should it differ so that it obeys the above question?
Please answer if you could in simple language.
Also should I use a special variable for power?
Thanks in advance, Abhijith
Print out the old value times five, starting with 1
Basic mockup:
auto PrintExercise(std::size_t terms) -> void {
std::size_t lastResult = 1;
for (std::size_t i = 0; i < terms; ++i) {
std::cout << std::to_string(lastResult) << std::endl;
lastResult *= 5;
}
}
Edit: Turns out I overthought this. It would be easier to just print the power of the control variable.
auto PrintExercise(std::size_t terms) -> void {
for (std::size_t i = 0; i < terms; ++i) {
std::cout << std::to_string(pow(5,n)) << std::endl;
}
}
Since the correct answers have already been provided, here's the same approach using recursion instead of iteration (loops) with (hopefully) enough comments to explain the process. Just for completeness. Give it a try, it's fun!
#include <iostream>
//value = the value that will be printed
//end = after how many iterations you want to stop
void PowerOfFive( const int value, const int end )
{
//Print the current value to the console. This is more or
//less everything the function does...
std::cout << value << ", ";
//... but a function can also call itself, with slightly different
//values in this case. We decrement "end" by 1 and let the whole
//process stop after "end" reaches 0. As long as we're doing that,
//we're multiplying "value" by five each time.
if ( end != 0 )
{
PowerOfFive( value * 5, end - 1 );
}
}
int main()
{
//Example for the above
//Start:
// 1st PowerOfFive(1, 3)
// --> prints 1
// --> calls 2nd PowerOfFive(1 * 5, 3 - 1)
// --> prints 5
// --> calls 3rd PowerOfFive(5 * 5, 2 - 1)
// --> prints 25
// --> calls 4th PowerOfFive(25 * 5, 1 - 1)
// --> prints 125
// --> function 4 ends because "end" has reached 0
// --> function 3 ends
// --> function 2 ends
// --> function 1 ends
PowerOfFive( 1, 3 );
getchar( );
return 0;
}
It seems you want to print powers of 5 upto n, not sure what you mean by control variable. So this should work
for (int i=0;i<=n;++i) cout << pow(5,i) << ", " ;
Iteration value is by 5, it can be done with pow() function & also by using simple for loop like this.
power=0;
cout<<power;
for(i=0;i<n;i++)
{
power=power*5; // OR power*=5
}
cout<<power;
Im adding code see if it helps
#include<iostream>
#include <cmath>
using namespace std;
int main()
{
int exp;
float base;
cout << "Enter base and exponent respectively: ";
cin >> base >> exp;
for(int i=0;i<exp;i++)
{
cout << "Result = " << pow(base, i);
}
return 0;
}
You have to pass the base and exponent value and for your question it should be base=5 and exp=3 and your output will be till 1 , 5 ,25

Finding words in sentences [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a programming assignment I cannot finish. This one part is killing me.
Accept some text from the user. Accept the string that needs to be searched. Your program is supposed to print the number of occurrences of the string found within the text, and the position at which the pattern was found. Look at the following sample output:
Sample Output:
Enter text: “Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen, and regulating the circulation”
String to search – “Some years ago”
Number of occurrences – 1
Position Found – 18
This is my function:
void getText()
{
string itext, word;
int position;
bool done = false;
cout << "Enter some text" << endl;
cin >> itext;
cout << "Enter the word or phrase to wish to find" << endl;
cin >> word;
char text[itext.length()];
char search[word.length()];
for(int i = 0; i < itext.length(); i++)
{
for(int j = 0; j < word.length(); j++)
{
if(text[i] == search[j])
{
position = i;
cout << position;
}
}
}
}
This might get you started: (pseudo code from the Knuth-Morris-Pratt algorithm)
algorithm kmp_search:
input:
an array of characters, S (the text to be searched)
an array of characters, W (the word sought)
output:
an integer (the zero-based position in S at which W is found)
define variables:
an integer, m ← 0 (the beginning of the current match in S)
an integer, i ← 0 (the position of the current character in W)
an array of integers, T (the table, computed elsewhere)
while m + i < length(S) do
if W[i] = S[m + i] then
if i = length(W) - 1 then
return m
let i ← i + 1
else
if T[i] > -1 then
let m ← m + i - T[i], i ← T[i]
else
let i ← 0, m ← m + 1
(if we reach here, we have searched all of S unsuccessfully)
return the length of S
http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
EDIT:Simpler and using c++ std library :
#include <string>
#include <vector>
int main ()
{
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
// different member versions of find in the same order as above:
std::size_t found = 0;
int matches = 0;
std::vector<size_t> positions;
while( found = str.find(str2) != std::string::npos) {
matches++;
positions.push_back(found);
}
}
You can make your live much easier if you will use std::string in this task instead of char[]. All you have to do is to load your text into a std::string and then use its find method as described here:
http://www.cplusplus.com/reference/string/string/find/
By the way, I am not sure that these lines can work as you can create not dynamic array only with a constant expression length
char text[itext.length()];
char search[word.length()];

Minimum Edits for Two Strings [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to use dynamic programming to determine the minimum edits required on one string
to transform it into another string
The code below does this, but I'm trying to find a way to keep track of the edits (d=delete, r=replace, i=insert).
For example:
string 1: sunflower
d rrrr <---Changes applying to string 1 (tracking minimum edits necessary to transform it into string 2)
string 2: sunlight
I'm not certain how to accomplish this, but I suspect it might have something to do with backtracking through the minimum distance table which is created. The code below finds the minimum distance perfectly fine, but I'm not certain how to approach keeping track of the necessary edits. Any ideas?
#include<iostream>
#include<cstring>
#define INSERT_COST 1
#define DELETE_COST 1
#define REPLACE_COST 1
using namespace std;
int min(int a,int b) {
return ((a < b) ? a : b);
}
/* convert str1 to str2 with minimum edits(insert,delete,replace)
suppose length(str1) = m and length(str2) = n
cost(i,j) -> cost of converting str1[0...i-1] to str2[0...j-1]
cost(m,n) -> cost of converting str1 to str2
Standard recursive formula for computing cost(m,n) :-
cost(i,j) = min[cost(i-1,j)+D, cost(i,j-1)+I, cost(i-1,j-1)+R]
D -> delete cost, I -> insert cost, R -> replace cost */
int editDistance(char str1[],int size1,char str2[],int size2) {
// cost matrix
// row -> str1 & col -> str2
int cost[size1][size2];
int i,j;
// initialize the cost matrix
for (i=0;i<size1;i++) {
for(j=0;j<size2;j++) {
if (i == 0) {
// source string is NULL
// so we need 'j' insert operations
cost[i][j] = j*INSERT_COST;
} else if (j == 0) {
// target string is NULL
// so we need 'i' delete operations
cost[i][j] = i*DELETE_COST;
} else {
cost[i][j] = -1;
}
}
} //initialization done
//compute cost(i,j) and eventually return cost(m,n)
for(i=1;i<size1;i++) {
for(j=1;j<size2;j++) {
int x = cost[i-1][j] + DELETE_COST;
int y = cost[i][j-1] + INSERT_COST;
// if str1(i-1) != str2(j-1), add the replace cost
// we are comparing str1[i-1] and str2[j-1] since
// the array index starts from 0
int z = cost[i-1][j-1] + (str1[i-1] != str2[j-1])*REPLACE_COST;
// as per our recursive formula
cost[i][j] = min(x, min(y,z));
}
}
// last cell of the matrix holds the answer
return cost[size1-1][size2-1];
}
//main
int main() {
char str1[] = "sunflower";
char str2[] = "sunlight";
int size1 = strlen(str1);
int size2 = strlen(str2);
int min_cost = editDistance(str1,size1+1,str2,size2+1);
cout<<"\nMinimum edits required to convert "<<str1<<
" to "<<str2<<" is "<<min_cost;
cout<<endl;
return 0;
}

write code to find square-root using bisection method in c++? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Bisection is as far as i know narrowing your search and reach the specific value in interval. please give me a sample of that how to make a generic code to find square-root. the way i think is taking three variables low, mid, high. high = userinput, low = 0, mid (low + high) /2, problem is how to how to change values then.
#include <iostream>
using namespace std;
int main() {
int val;
cout << "Enter the number: ";
cin >> val;
if( val< 0) {
cout<< "According to my maths its not possible." << endl;
} else {
float low = 0, high = val;
float mid = (low + high)/2;
int c = 0;
while (c != 1) {
if(mid * mid = val) {
cout << "Square root is: " << mid <<endl;
c = 1;
} else {
if(mid * mid > val) {
high = mid;
mid = (low + high)/2;
} else {
low = mid;
mid = (low + high)/2;
}
}
}
}
return 0;
}
Lets say the we are looking for sqrt(N)
As described here, you have to find the average of LOW and HIGH, if square of average is greater than N, we change the high value with the average we just found, if it is less than N, we change the low value with the average. And we repeat the steps as many times to satisfy the required precision.