C/C++ Programming Learning-Week 5② Align to the left

Topic link

Title description

In physical education class, n children in a certain class line up. As the physical education teacher said "Look to the left", the students all looked to the left. Now every student wants to know how many of the students on the left are shorter than themselves.

Input format
Enter an integer n (n≤100) in the first line, which represents the number of students in the class.

Enter n integers in the second line, separated by spaces, indicating the height of each student from left to right (height is in the range of [1,200]).

Output format
Output n integers in one line, separated by spaces, indicating in turn the number of students whose left side is shorter than themselves.

Sample Input

5
3 7 2 5 1

Sample Output

0 1 0 2 0

Ideas

Double for loop, compare the height, if it is shorter than the current classmate, count +1, and finally output the count.

C language code:

#include <stdio.h>
#include <math.h>
#include <string.h>
const long long N = 1e6 + 10;
long long n, cnt = 0;
int main()
{
    
    
    long long a[N];
	scanf("%d", &n);
	for(long long i = 0; i < n; i++)
		scanf("%d", &a[i]);		//输入身高
	for(long long i = 0; i < n; i++)
	{
    
    
		cnt = 0;
		for(long long j = i; j >= 0; j--)	//遍历第i个人左边的人
			if(a[i] > a[j]) cnt++;	//比他矮,就加一
		printf("%d ",cnt);		//输出
	}
	return 0;
}

C++ code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	int n, num[105];
	while(cin >> n)
	{
    
    
		for(int i = 0; i < n; i++)
		{
    
    
			cin >> num[i];
			int cnt = 0;
			if(i > 0)
			{
    
    
				for(int j = 0; j < i; j++)
					if(num[j] < num[i]) cnt++;
				cout << " " << cnt;
			}
			else cout << cnt;
		}
		cout << endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/112909365