Displaying first element user input in an Array

how to store user input into an array in java
how to fill an array from user input c#
how to get integer array input from user in c#.
how to take array input in console application in c#
how to get integer array input from user in java
how to print user input array in java
4.6.3: printing array elements with a for loop.
how to scan in an array

We can define the term 'value of a name' as the average position of the letters in the name, calculating 'A' as 1, 'B' as 2, 'C' as 3, and so on. The value of "BOB" would be (2 + 15 + 2)/ 3 = 6. According to this value, the names will be arranged from the smallest towards the biggest in the output. When two or more names have the same value, the name which is in the first position in the original list (the first one the user inputs) should show up first in the sorted list (the output).

Input In the first line we have an integer N (1 <= N <= 100), which is the number of names. In every of the N lines we have one name ([A-Z], no empty spaces). Names contain 1 - 200 letters.

Output Print out the sorted list (one name in a line).

Test-case

Input: 3 BOB AAAAAAA TOM Output: AAAAAAA BOB TOM

I tried something, and the code seemed to work, I just had a problem with the output. I couldn't find a way to arrange the names with the same value, according to their position in the original list. Here's the other test-case I tried, but didn't figure out:

Input:


 10
 COSOPYILSPKNKZSTUZVMEERQDL
 RRPPNG
 PQUPOGTJETGXDQDEMGPNMJEBI
 TQJZMOLQ
 BKNGFEJZWMJNJLSTUBHCFHXWMYUPZM
 YNWEPZKNBOOXNZVWKIUS
 LV
 CJDFYDMYZVOEW
 TMHEJLIDEHT
 KGTGFIFWYTKPWTYQQPGKRRYFXN
Output:
TMHEJLIDEHT
PQUPOGTJETGXDQDEMGPNMJEBI
BKNGFEJZWMJNJLSTUBHCFHXWMYUPZM
CJDFYDMYZVOEW
RRPPNG
COSOPYILSPKNKZSTUZVMEERQDL
KGTGFIFWYTKPWTYQQPGKRRYFXN
TQJZMOLQ
YNWEPZKNBOOXNZVWKIUS
LV

My output:

TMHEJLIDEHT 
PQUPOGTJETGXDQDEMGPNMJEBI
CJDFYDMYZVOEW // these two
BKNGFEJZWMJNJLSTUBHCFHXWMYUPZM // should be arranged with their places switched
RRPPNG 
COSOPYILSPKNKZSTUZVMEERQDL 
KGTGFIFWYTKPWTYQQPGKRRYFXN 
TQJZMOLQ 
YNWEPZKNBOOXNZVWKIUS 
LV
#include <iostream>
#include <string>

using namespace std;

int main() {

int N;
cin >> N;

string words[N];

int res[N];

for (int i = 0; i < N; i++) {
    int sum = 0;
    int value = 0;
    int temp = 0;
    string word;
    cin >> words[i];
    word = words[i];
    for (int j = 0; j < word.length(); j++) {
        sum += (int)word[j] - 64;
    }
    value = sum / word.length();
    res[i] = value;
}

for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
        if (res[i] < res[j]) {
            swap(res[i], res[j]);
            swap(words[i], words[j]);
        }
    }
}

for (int i = 0; i < N; i++) {
    cout << words[i] << endl;
}

return 0;
}
string words[N];
int res[N];

This here is not valid C++, you can not size a stack array using a runtime variable, although some compilers might support such a feature. You might use say std::vector instead, which behaves much like an array.

vector<string> words;
vector<int> res;

for (int i = 0; i < N; i++) {
    int sum = 0;
    int value = 0;
    int temp = 0;
    string word;
    cin >> word;
    words.push_back(word);
    for (int j = 0; j < word.length(); j++) {
        sum += (int)word[j] - 64;
    }
    value = sum / word.length();
    res.push_back(value);
}

for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
        if (res[i] < res[j]) {
            swap(res[i], res[j]);
            swap(words[i], words[j]);
        }
    }
}

The ordering is because your sorting algorithm is not stable. Stable means that items with equal values will maintain the same order relative to each other.

for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
        if (res[i] < res[j]) {
            swap(res[i], res[j]);
            swap(words[i], words[j]);
        }
    }
}

What you have is very close to bubble sort, which is stable.

for (int i = 0; i < N; i++) {
    for (int j = 0; j < N - i - 1; j++) { // i elements sorted so far
        if (res[j] > res[j + 1]) {
            swap(res[j], res[j + 1]);
            swap(words[j], words[j + 1]);
        }
    }
}

C++ also provides a stable sort in <algorithm>, but it can't function directly on two arrays like this unfortunately, one option is to compute the value on the fly, another could be to make a class holding both items and sort that, or another to sort the indices.

std::stable_sort(words.begin(), words.end(), [&](auto &a, auto &b)
{
    int suma = 0, sumb = 0; // better yet, make a "int value(const string &str)" function.
    for (int j = 0; j < a.length(); j++) {
        suma += (int)a[j] - 64;
    }
    for (int j = 0; j < b.length(); j++) {
        sumb += (int)b[j] - 64;
    }
    int valuea = suma / a.length();
    int valueb = sumb / b.length();
    return valuea < valueb;
});

A class containing both items is pretty straight forward, for indices, make a 3rd array and sort that.

vector<size_t> indices;
...
    string word;
    cin >> word;
    indices.push_back(words.size());
    words.push_back(word);
...
std::stable_sort(indices.begin(), indices.end(), [&](auto a, auto b){ return res[a] < res[n]; });
for (int i = 0; i < N; i++) {
    cout << words[indices[i]] << endl;
}

Creating and Using Arrays, that creates the array, puts some values in it, and displays the values. public class ArrayDemo { public static void main(String[] args) { int[] anArray; // declare an� Displaying first element user input in an Array We can define the term value of a name as the average position of the letters in the name calculating A as 1 B as 2 C as 3 and so on The value of BOB would be 2 15 2 3 6 According to this

A possible solution could be order the result array during construction.

When you add the words in the result array, use the result obtained to add the word in the right place. In this way you can check if exist already the same value and add the new word after the previous with the same value.

Java Program to Print Array Elements, Alternatively, write a Java program to Print Elements in an Array using For Loop This program in Java allows the user to enter the Size and elements of an Array. This Java program to display array elements is the same as the first example. In this video we will see how to insert or add an element in array using user input in c. Disclaimer - The music / audio used in this video is not a property of Learn Programming Yourself. All

After reading the next word use insertion sort (wiki) which is stable

  1. read word
  2. calculate value
  3. insert in a right place in the array
  4. go to 1 until i < N otherwise print out

Doesn't require additional sorting procedure.

Java Program to fill an array of characters from user input, For user input, use the Scanner class with System.in. Now, display it until the length of the character array i.e. number of elements input by the user − Scanner(System.in); System.out.println("First add some characters"); char[] a = s .next().toCharArray(); System.out.println("Elements = "); for (int i = 0;� To access any an array element we use. array[0] = 10 array[1] = 20 array[2] = 30 array[9] = 100. Since array index is an integer value. Hence, rather hard-coding constant array index, you can use integer variable to represent index. For example, int i = 0; array[i] = 10; // Assigns 10 to first array element Program to input and print array elements

in python:

def sort_list(list1, list2): 

    zipped_pairs = zip(list2, list1) 

    z = [x for _, x in sorted(zipped_pairs)] 

    return z

times = int(input())

entries = []
ordered = []

for x in range(times):
    entries.append(input())

for x in entries:
    chars = []
    for y in x:
        chars.append(ord(y) - 96)
    ordered.append(sum(chars))

print(sort_list(entries,ordered))

C# Sharp Exercises: Read and Print elements of an array , Write a program in C# Sharp to store elements in an array and print it. Write(" Input 10 elements in the array :\n"); for(i=0; i<10; i++) { Console. Write a C program to input elements in an array and print array using pointers. How to input and print array using pointer in C programming. Learn C programming, Data Structures tutorials, exercises, examples, programs, hacks, tips and tricks online.

If you use a std::multimap<int, std::string>, there would be no need to sort, as the key would already serve as the sorting criteria.

Here is a solution using std::multimap:

#include <string>
#include <numeric>
#include <iostream>
#include <sstream>
#include <map>

// Test data
std::string test = "10\n"
"COSOPYILSPKNKZSTUZVMEERQDL\n"
"RRPPNG\n"
"PQUPOGTJETGXDQDEMGPNMJEBI\n"
"TQJZMOLQ\n"
"BKNGFEJZWMJNJLSTUBHCFHXWMYUPZM\n"
"YNWEPZKNBOOXNZVWKIUS\n"
"LV\n"
"CJDFYDMYZVOEW\n"
"TMHEJLIDEHT\n"
"KGTGFIFWYTKPWTYQQPGKRRYFXN\n";

int main()
{
    std::istringstream strm(test);

    // Read in the data
    std::multimap<int, std::string> strmap;
    int N;
    strm >> N;
    std::string word;
    for (int i = 0; i < N; ++i)
    {
        strm >> word;

        // get the average using std::accumulate and divide by the length of the word
        int avg = std::accumulate(word.begin(), word.end(), 0,
                    [&](int total, char val) { return total + val - 'A' + 1; }) / word.length();

        // insert this value in the map
        strmap.insert({ avg, word });

    }

    // output results 
    for (auto& w : strmap)
        std::cout << w.second << "\n";
}

Output:

TMHEJLIDEHT
PQUPOGTJETGXDQDEMGPNMJEBI
BKNGFEJZWMJNJLSTUBHCFHXWMYUPZM
CJDFYDMYZVOEW
RRPPNG
COSOPYILSPKNKZSTUZVMEERQDL
KGTGFIFWYTKPWTYQQPGKRRYFXN
TQJZMOLQ
YNWEPZKNBOOXNZVWKIUS
LV

The std::accumulate is used to add up the values to get the average.

Chapter 7: Arrays, The following displays the indexes and values in an array with 10 elements of Write a program that inputs the length of a int array from the user and assigns 1 at We could have combined the first two loops into one loop, but it is cleaner to� Access Array Elements. You can access elements of an array by indices. Suppose you declared an array mark as above. The first element is mark[0], the second element is mark[1] and so on. Few keynotes: Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element. If the size of an array is n, to access the last element, the n-1 index is used

Solved: For This Lab, You Will Create A Basic Array Of Num , User For Input, Sort The Elements Of Array And Display The Sorted Elements which means that the first element in the array is stored at the 0th position in� Improve this sample solution and post your code through Disqus. Previous: C Array Exercises Home Next: Write a program in C to read n number of values in an array and display it in reverse order.

Problem Description For this lab, you will create a basic Array of , User For Input, Sort The Elements Of Array And Display The Sorted Elements Arrays indexes in Java are zero-based, which means that the first element in� See the Pen JavaScript: Add items in a blank array and display the items - array-ex-13 by w3resource (@w3resource) on CodePen. Improve this sample solution and post your code through Disqus. Previous: Write a JavaScript program to compute the sum and product of an array of integers.

How to save user input inside an array in Java, I personally like using buffered reader to take user inputs instead of using scanner class for (int i=0;i<5;i++) // for loop to display values Now to understand what is going on, first we need to know how many names do i need to save. We can� As the iterations increases, the size of array increase and user inputted value is assigned to array element. Finally, we print out the value of the array using console.log(), but you can use this array for other purposes as well. Hope you like the article. Share your thoughts in the comments below.

Comments
  • use stable_sort in the stl, alternatively use merge sort (n log n time complexity means it will perform quite fast)
  • Your sorting function sorts, but doesn't preserve order of equivalent elements. So use a different algorithm, such as bubble sort.
  • Use std::multimap<int, string>
  • int N; cin >> N; string words[N]; -- This is not valid C++. Arrays in C++ must have their size denoted by a constant, not a runtime value. Use std::vector<std::string> words(N); instead.
  • The issue with your stable_sort predicate is that it is calculating the average each and every time it's called for both words. The average will not change, so why calculate it repeatedly?
  • @PaulMcKenzie Why I said it's unfortunate you can't just use it "directly" in any way I can think of, the indices array for example avoids that repeat, as would a struct { value, string }, maybe a map as well.
  • How would that work? Would it be okay for you to edit my code?