Refreshment
The Pan Am 73 flight from Bombay to New York en route Karachi and Frankfurt was hijacked by a few Palestinian terrorists at the Karachi International Airport.
Despite the alarming situation prevailing inside the flight, the senior flight purser Neerja Banhot had to wither her fear and rise to the occasion to take extra care of her passengers on board.
Firstly, she and her crew decided to provide food and drinks to the passengers. Given n the number of rows of seats in the aircraft and the total number of people in each row, can you determine the total number of passengers in the flight.
Input Format :
The first line of input consists of an integer n, corresponding to the number of rows in the aircraft.
The next n lines of input consist of integers that correspond to the number of people in each row.
Output Format :
The first line of output consists of n integers corresponding to the number of people in each row.
The second line of output consists of an integer corresponding to the total number of people in the aircraft.
Print Invalid Input and terminate the process of getting inputs if any of the inputs is not a positive number.
Refer sample input and output for further specifications.
Sample Input 1:
5
12
28
30
20
45
Sample Output 1:
12 28 30 20 45
135
Sample Input 2:
6
12
28
30
20
-45
Sample Output 2:
Invalid Input
Sample Input 3:
-6
Sample Output 3:
Invalid Input
Answers
Answer:
Explanation:
In C++ :
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;cin>>n;
int sum = 0;
int arr[n];
if(n<0)
{
cout<<"Invalid Input";
}
else
{
for(int i =0;i<n;i++)
{
int a = 0;cin>>a;
if(a>0)
{
arr[i] = a;
sum += arr[i];
}
else if(a<0)
{
cout<<"Invalid Input";
exit(0);
break;
}
}
int arrSize = *(&arr + 1) - arr;
if(arrSize-1 == (n-1))
{
for(int i =0;i<n;i++)
{
int temp;
temp = arr[i];
if(temp<0)
{
break;
}
else
{
cout<<arr[i]<<" ";
}
}
cout<<"\n";
cout<<sum;
}
}
return 0;
}
In JAVA:
import java.io.*;
import java.util.*;
class Refreshment {
public static void main(String [] args) {
int i,n,sum=0,count=0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
if(n<0) {
System.out.println("Invalid Input");
}
else {
int a[] = new int[n];
for(i=0;i<n;i++) {
a[i] = sc.nextInt();
if(a[i] <0) {
System.out.println("Invalid Input");
break;
}
else {
count++;
sum = sum+a[i];
}
}
if(count == n) {
for(i=0;i<n;i++) {
System.out.print(a[i]+" ");
}
System.out.println();
System.out.println(sum);
}
}
}
}
Algorithm
Explanation:
# Python Solution
n = int(input())
passengers = []
neg_flag = 0
if(n>=0):
for i in range(n):
x = int(input())
passengers.append(x)
if(x<0):
neg_flag = 1
break
if(neg_flag):
print("Invalid Input")
else:
print(*passengers)
print(sum(passengers))
else:
print("Invalid Input")