my code not enter else if condition. How to enter else if condition - if-statement

function findingBadData(findNegativeNumber){
let badDataStore = [];
for(let i = 0; i < findNegativeNumber.length; i++){
const element = findNegativeNumber[i];
if(Array.isArray(findNegativeNumber) === true && element < 0){
badDataStore.push(element);
}
else if(Array.isArray = findNegativeNumber.length === false){
return "input type is not a array";
}
}
return badDataStore.length;
}
const ages = findingBadData(23, -34, 21, 29, -25, 56, -45);
console.log(ages);
i want to try my code return return "input type is not a array";
but i got output 0
plz help me

Related

To Compare two Integer Arrays are equal Or Not

#include <iostream>
using namespace std;
bool equal_arr(int* arr, int* arr2, int m, int n)
{
if (m != n)
{
return false;
}
int i = 0, j = 0;
bool res = false;
while (i < n)
{
if (arr[i] == arr2[j])
{
res = true;
i++;
j++;
}
else
{
i++;
j++;
res = false;
}
return res;
}
}
int main(void)
{
int arr[5] = { 4, 4, 4, 4, 4 };
int arr2[5] = { 4, 5, 2, 8, 6 };
if (equal_arr(arr, arr2, 5, 5))
cout << "true" << endl;
else
cout << "false";
return 0;
}
the above code should print true or false while comparing between two arrays, but it gives a wrong output while at any occurance if both element between the arrays is same it returns true for some logical issues,in my sample testcase you can see it.
Your logic is wrong. This
if (arr[i] == arr2[j])
{
res = true;
i++;
j++;
}
else
{
i++;
j++;
res = false;
}
would make your comparison function return the comparison of the last elements, because with each iteration you are overriding the previous result. And the return statement in the end of the loop makes it even less clear: you are always comparing only first element (because you return after the first iteration).
Better like this:
for (int i = 0; i < n; i++)
{
if (arr[i] != arr2[i]) return false;
}
return true;
because just one pair of elements that are not equal is enough to return false.

Heap sort it not working or incorrect calculation

The max-heap function is working fine but heapsort is not working.
When I run this code. it shows incorrect calculation.
Your input is:
9 79 42 86 33 75
Your max-heap is:
86 79 42 75 33 9
Ascending numerical order:
86 79 42 75 33 9
As you can see my last output, the Ascending numerical order is the same value as max-heap but this is not what I am expecting.
My task is that I have to sort a number from the max-heap. Also, I have to swap first and last element from the max-heap array and then ignore the last element. Also, once the last element is ignored I have to do max-heap function again.
An example of how the calculation works. max-heap is: 86, 79, 42, 75, 33, 9. In the sorting section, I have to swap first and last element and then ignore the last element, so the heap sort result should be: 9, 79, 42, 75, 33, [86] (square bracket mean ignored or removed). I have to do max-heap again from the previous sorting. The second max-heap result would be 79, 75, 9, 42, 33. when I come back to the sorting I have to swap the first and last element and then ignore the last element again so the max-heap is 79, 75, 9, 42, 33 and the heap sort result should be: 33, 75, 9, 42, [79], [86]. I have to do the same step all over again until all the number sorted.
An example of output that I want to display on:
My input is 9, 79, 42, 86, 33, 75
Max- heap should be: 86, 79, 42, 75, 33, 9.
Ascending number should be: 9, 33, 42, 75, 79, 86.
For more example, Please visit the website https://en.wikipedia.org/wiki/Heapsort#Example, See example 2 - Sorting
And Here the code of incorrect calculation:
#include "stdafx.h"
#include <iostream>
using namespace std;
int heap[30];
void main()
{
int n, index, parent, flag, dummy;
n = 7; //size of table
// user input number
for (index = 1; index < 7; index++)
{
cout << "Enter value " << index << ": ";
cin >> heap[index];
}
// output for user element
cout << "\nYour input is:\n";
for (index = 1; index < 7; index++)
{
cout << heap[index] << " ";
}
flag = 1;
while (flag == 1)
{
flag = 0;
//heapify
for (index = 7; index >1; index--)
{
parent = index / 2;
if (heap[parent] < heap[index])
{
dummy = heap[parent];
heap[parent] = heap[index];
heap[index] = dummy;
flag = 1;
}
// Sorting --> swap first and last of the array and then ignore the
//last array and reheap from above until all number sorted.
while (heap[0] >= 1)
{
int last = heap[0];
int temp1 = heap[1];
heap[1] = heap[last - 1];
heap[last - 1] = temp1;
heap[0]--;
}
}
}
cout << "\n\nYour max-heap is:\n";
for (index = 1; index < 7; index++) // output for after heap
{
cout << heap[index] << " ";
}
cout << "\n\nAscending numerical order:\n";
for (index = 1; index < 7; index++) //output for sorting.
{
cout << heap[index] << " ";
}
getchar();
getchar();
}
Also the code that I can not change or replace which are
while (flag == 1)
{
flag = 0;
//heapify
for (index = 6; index >1; index--)
{
parent = index / 2;
if (heap[parent] < heap[index])
{
dummy = heap[parent];
heap[parent] = heap[index];
heap[index] = dummy;
flag = 1;
}
}
}
You have many bugs in your code.
First one i have noticed is in your while loop
while (heap[0] >= 1) //heap[0] = 0 since you declared your array statically
{
int last = heap[0]; // last = 0
int temp1 = heap[1];
heap[1] = heap[last - 1]; //trying to find element heap[-1] ERROR
heap[last - 1] = temp1; //heap[-1] = heap[1]
heap[0]--; //heap[0] = -1 why?
}
Second one is that you are starting from index 1 and go to index 6 in your input loop (first for loop in code), but when you are trying to make some difference in your heap in third for loop you are starting from index 7 and you go to index 2.
I couldn't find a way in your code so i will post mine. It is following the algorithm in that wiki page you posted.
#include <iostream>
using namespace std;
void build_heap(int *heap, int index)
{
if(index>1)
{
int new_input = heap[index], tmp = 0;
//since your index starts from 1 and goes up to n in heap
//parent from index k is (k%2==1) ? (k-1)/2 : k/2
if(index % 2 == 1)
index--;
if(heap[index/2] < new_input)
{
tmp = heap[index/2];
heap[index/2] = new_input;
heap[index] = tmp;
build_heap(heap, index/2);
}
}
}
void make_order_in_heap(int *heap, int n)
{
if(n>1)
{
int index = 1;
int child_index;
bool work = true;
while(work && index < n)
{
//finding child_index
if( index * 2 + 1 <= n)
{
child_index = heap[index*2] > heap[index*2+1] ? index*2 : index*2+1;
}
else if(index * 2 <= n)
{
child_index = index*2;
}
else
{
//this index has no children
return;
}
work = false;
if(heap[child_index] > heap[index])
{
int tmp = heap[index];
heap[index] = heap[child_index];
heap[child_index] = tmp;
index = child_index;
work = true;
}
}
}
}
void swap_first_and_last(int *heap, int n)
{
if(n>1)
{
int tmp = heap[1];
heap[1] = heap[n];
heap[n] = tmp;
}
}
void sort_heap(int *heap, int n)
{
if(n>1)
{
swap_first_and_last(heap, n);
//we swaped first and last element in heap with n elements
//so now first element in heap of n-1 elements is not on his possiton
make_order_in_heap(heap, n-1);
sort_heap(heap, n-1);
}
}
int main()
{
int heap[30];
int n, index, parent, flag, dummy;
n = 7;
for (index = 1; index <= n; index++)
{
cout << "Enter value " << index << ": ";
cin >> heap[index];
build_heap(heap, index);
}
cout << "\nYour input is:\n";
for (index = 1; index <= n; index++)
{
cout << heap[index] << " ";
}
sort_heap(heap, n);
cout << "\n Sorted array is:\n";
for (index = 1; index <= n; index++)
{
cout << heap[index] << " ";
}
return 0;
}

Returns false every time in C++

I made a simple sequential search function, so as i'm testing it, if I put 25 into my search item it returns true, but the other numbers 90, 21 are always false and I can't understand why it's doing that.
int a[] = {25,90,21};
int searchItem = 90;
if(sequentialSearch(searchItem, a, 3) == 1)
{
cout << "Found Item" << endl;
}
else
{
cout << "Item Not Found" << endl;
}
bool sequentialSearch(int searchItem, int * a, int size)
{
for(int i = 0; i < size; i++)
{
if(searchItem == a[i])
{
return true;
}
else
{
return false;
}
}
}
you return false if your element is not at first position. Try this
bool sequentialSearch(int searchItem, int * a, int size)
{
for(int i = 0; i < size; i++)
{
if(searchItem == a[i])
{
return true;
}
}
return false;
}
Your for loop ends up only checking the first item, and then returning true or false. You need to change your logic to do something like
for( . . . )
{
if(searchItem == a[i]) return true;
}
return false;
This way it will test each item in the array and then return false if nothing found.

Issue returning values from function

My program calculates the average score for each student. It outputs the numeric average and the letter grade. With these two functions, I am able to get the letter grade for each student just fine, but I can't figure out how to obtain the total amount of each letter grade. (please note that I'm not allowed to use structures, or arrays or vectors, etc. for this assignment :( )
#include <iostream>
string letterScore(double&);
int scoreCounter(string&);
using namespace std;
int main() {
/* repeat for 5 students */
for (int i = 0; i < 5; i++) {
/* for simplicity, assume avgScore has already been calculated
and that function returned the average scores received for
each student: 90, 80, 70, 60, and 50 respectively */
// pass the average score to figure out letter grades
string letterscore = letterScore(avgScore);
}
return 0;
}
string letterScore(double& avgScore) {
int As, Bs, Cs, Ds, Fs = 0;
string letterscore;
if (avgScore >= 90)
{
letterscore = "A";
As = scoreCounter(letterscore);
}
else if (avgScore >= 80 && avgScore <= 89)
{
letterscore = "B";
Bs = scoreCounter(letterscore);
}
else if (avgScore >= 70 && avgScore <= 79)
{
letterscore = "C";
Cs = scoreCounter(letterscore);
}
else if (avgScore >= 60 && avgScore <= 69)
{
letterscore = "D";
Ds = scoreCounter(letterscore);
}
else if (avgScore >= 50 && avgScore <= 59)
{
letterscore = "F";
Fs = scoreCounter(letterscore);
}
return letterscore;
}
int scoreCounter(string& letterscore) {
int counter = 0;
if (letterscore == "A")
{
counter++;
}
else if (letterscore == "B")
{
counter++;
}
else if (letterscore == "C")
{
counter++;
}
else if (letterscore == "D")
{
counter++;
}
else if (letterscore == "F")
{
counter++;
}
return counter;
}
I know the problem lies in the second function and how I am connecting the two. Right now, the output for As, Bs, Cs, Ds, Fs is 0 instead of 1 for each (assuming the average received of 90, 80, 70, 60, and 50 mentioned above). How can I get back in main() the total count for each letter grade? Thank you!
I do not know exactly what you are allowed to do or not to do.
Considering you cannot use arrays nor structures, you can solve your problem only with your letterScore function by passing your counters in parameters as reference :
string letterScore(double& avgScore, int& countA, int& countB, int& countC, [etc...]) {
string letterscore;
if (avgScore >= 90)
{
letterscore = "A";
countA++; // here is the counter !
}
[etc...] // do the same for other blocks
and in your main() :
int countA = countB = [etc...] = 0;
for (int i = 0; i < 5; i++) {
string letterscore = letterScore(avgScore, countA, countB, [etc...]);
}

check if array element value already existed when user input

How do i check if array already contains a value?
for example,
Input:1
Output:1
Input:1
Error!: Number existed
Input:2
Output:2
When the user input already existed in the array, it will show error and ask them to input again, until they entered a different value. when a different value is entered, that value will be added to array. if the value entered is same as any element value, it will not be added to the array.
int num[5], temp;
bool val = true, existed = false;
for(int i = 0; i < 5; i++){
val = true;
while(val){
cout << "\nPlease enter a number:";
cin >> temp;
for(int x = 0; x < 5; x++){
if(temp == num[x]){
existed = true;
}
}
if(existed){
cout << "Number existed";
} else {
num[i] = temp;
cout << "Your number" << num[i];
val = false;
}
}
}
You can write a short function to do the check:
bool alreadyExists(int *array, int array_size, int value)
{
for (int i = 0; i < array_size; i++)
if (array[i] == value)
return true; // we found the same value, return true
return false; // if we get here we have not found it
}
Call it with
int input = 1;
if alreadyExists(num, 5, input)
{
printf("already exists\n");
}
else
{
printf("Ok to add...");
}