Search
 
SCRIPT & CODE EXAMPLE
 

CPP

find second smallest number in array javascript using for loop

const array = [32, 22, 53, 92, 20, 34, 23, 11, 17];
let smallestNum = array[0];
let secondSmallestNum = 0;
for (let i = 1; i < array.length; i++) {
  if (array[i] < smallestNum) {
    secondSmallestNum = smallestNum;
    smallestNum = array[i];
  } else if (array[i] !== smallestNum && array[i] < secondSmallestNum) {
    secondSmallestNum = array[i];
  }
}
console.log(smallestNum);
console.log(secondSmallestNum);
Comment

how to find second smallest element using single loop


#include <iostream>
#include<vector>
using namespace std;

int main() {
	vector<int> v;
    int n;

    cout<<"Enter total element: ";
    cin>>n;

    // Initializing array
    cout<<"Enter values: "<<endl;
    for(int i=0;i<n;i++){
        int temp;
        cin>>temp;
        v.push_back(temp);
    }

    // Finding second smallest using single loop
    int smallest=v[0];
    int secondSmallest=v[1];
    for(int i=0;i<n;i++){
        if(v[i]<smallest){
            secondSmallest=smallest;
            smallest=v[i];
        }
        if(v[i]<secondSmallest && v[i]!=smallest){
            secondSmallest=v[i];
        }
    }

    cout<<"Smallest Number: "<<smallest<<endl;
    cout<<"Second Smallest Number: "<<secondSmallest<<endl;

	return 0;
}


Comment

PREVIOUS NEXT
Code Example
Cpp :: use ster when declaring variables cpp 
Cpp :: use textchanged qt cpp 
Cpp :: c++ online 
Cpp :: scope resulation operator :: in c++ 
Cpp :: Road sign detection and recognition by OpenCV in c 
Cpp :: remove a element from an array c++ 
Cpp :: #include <iostream #include <stdio.h using namespace std; int main() { int a[5]; a[0]=12; a[1]=13; a[2]=14; a[3]=15; 
Cpp :: sfml disable message 
Cpp :: triangle angle sum 
Cpp :: vector and algorithm 
Cpp :: C++ using a member function of a class to pass parameters to a thread 
Cpp :: dream speedrun song mp4 
Cpp :: 10^18 data type in c++ 
Cpp :: grepper users assemble 
Cpp :: is variable sized array are not allowed in c++? 
Cpp :: how to fix in c++ "cannot open imgui.h" 
Cpp :: cpp stacks 
Cpp :: loops in c++ with example 
Cpp :: qt get wireless interface name 
Cpp :: distinct numbers cses 
Cpp :: Data Encapsulation in C++ 
Cpp :: the statement vector vector int matrix(100 vector int (50 100) ) declares 
Cpp :: C++ Rectangular Form 
Cpp :: __aeabi_assert() 
Cpp :: print the elements of the array without using the [] notation in c++ 
Cpp :: sort array using stl 
Cpp :: c++ CRL multiline string 
Cpp :: c++ program to use nmap 
Cpp :: C++ if...else Statement 
Cpp :: arrays to function c++ 
ADD CONTENT
Topic
Content
Source link
Name
9+3 =