- 2

Rewrite this code in c++

Выделить код 1 2 3 4 5 6 7 8 9 10 11 12 13 14 import java.util.Scanner;   public class q1 {     public static void main(String[] args){     Scanner f = new Scanner(System.in);     int N = f.nextInt();     int M = N*(N+1)/2;     int K = 0;     for(int i = 0; i<N-1; i++){         K+=f.nextInt();}     System.out.println(M-K);     f.close();   }}

6th Jul 2017, 9:24 PM
Maria
Maria - avatar
3 ответов
+ 7
@Maria, Seems like the copy and paste for you question gave a strange format so I copied and reformatted it and hope it comes out below correctly (happens when code is xferred between browser, unix and windows). Anyways, I compiled and ran it and found it fascinating. I recognized that M=N(N+1)/2 (see http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/runsums/triNbProof.html) but if you could describe what this code is doing, your rationale for a C++ version.... and this is not a homework assignment is it? (hope you don't mind me asking). But like I said this code is fascinating. Reason for asking about details of the code aside from SoloLearns faq about posting questions, etc. is that to write in another computer language one should have a feel for the goal and purpose of the program so that certain choices are made. import java.util.Scanner; public class q1 { public static void main(String[] args){ Scanner f = new Scanner(System.in); int N = f.nextInt(); int M = N*(N+1)/2; int K = 0; for(int i = 0; i<N-1; i++){ K+=f.nextInt(); } System.out.println(M-K); f.close(); } }
7th Jul 2017, 12:19 AM
cyber33
cyber33 - avatar
+ 6
Thanks Maria, will look into it. UPDATE: Ok here is C++ version them works with the two examples given... let me know if that works for you... and one way (maybe a few) to write it... Example runs: D:\SoloLearn>q1cpp 5 1 2 3 4 5 D:\SoloLearn>q1cpp 4 1 3 4 2 D:\SoloLearn> Code: #include<iostream> using namespace std; int main(int argc, char ** argv){ int N, M, K=0, H; cin >> N; M = N*(N+1)/2; for(int i = 0; i<N-1; i++){ cin >> H; K+=H; } cout << M-K; return 0; }
10th Jul 2017, 5:40 AM
cyber33
cyber33 - avatar
+ 1
@cyber33, With this code you can find the missing element of the sequence. For example you have: input - 5 (number of the elements) 1234 so output will be - 5 or input - 4 134 and output is - 2
7th Jul 2017, 6:56 AM
Maria
Maria - avatar