+ 2

How can I input more than one mark ?

Now I have five marks , and I want to input them and get their sum . first : int marks[5]; second : cin>>first mark; cin>>second mark; cin>>third mark; cin>>fourth mark; cin>>fifth mark; third : sum= first mark + second mar...... how can I write them in c++?

30th Apr 2017, 7:27 AM
Enas Emad
Enas Emad - avatar
18 Antworten
+ 18
@enas, That's why I'm here 😉
30th Apr 2017, 7:58 AM
Sachin Artani
Sachin Artani - avatar
+ 17
Yes you can and you should.
30th Apr 2017, 7:49 AM
Sachin Artani
Sachin Artani - avatar
+ 17
if it is the real code, you must include the appropriate header files, put all above stuff in main() function and inside main() function body, you MUST declare the array as- int marks[5];
30th Apr 2017, 7:53 AM
Sachin Artani
Sachin Artani - avatar
+ 16
Use loops, eg. of for loop, int sum=0; for(int i=0;i<5;i++) { cin>>marks[i]; sum=sum+marks[i]; } cout<<"Sum= "<<sum;
30th Apr 2017, 7:31 AM
Sachin Artani
Sachin Artani - avatar
+ 16
@enas, In your code, you declare variable i twice, once above for loop and once inside for loop, it causes error. just declare variable i at line 1 and initialise it with 0 (as i=0, not int i=0) inside for loop.
30th Apr 2017, 7:41 AM
Sachin Artani
Sachin Artani - avatar
+ 15
@Sachin's way is correct. Just FYI, array index 0 corresponds to first element, and 1 corresponds to second element, and so on. E.g. cin >> marks[0]; cin >> marks[1]; sum = marks[0] + marks[1];
30th Apr 2017, 7:38 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
your code is good .but it is missing (cout<<) and (n)isn't declared in the scope .. nice try 👍
3rd May 2017, 8:12 AM
Enas Emad
Enas Emad - avatar
+ 5
great . but I made some modification.
30th Apr 2017, 7:37 AM
Enas Emad
Enas Emad - avatar
+ 5
int sum=0,i=0,marks[5]; for(int i=0;i<5;i++) { cin>>marks[i]; sum=sum+marks[i]; } cout<<"Sum= "<<sum;
30th Apr 2017, 7:37 AM
Enas Emad
Enas Emad - avatar
+ 5
thank you @Sachin Artani very much.
30th Apr 2017, 7:38 AM
Enas Emad
Enas Emad - avatar
+ 5
AAh ,another perfect one ,thank you Hatsy Rei.
30th Apr 2017, 7:41 AM
Enas Emad
Enas Emad - avatar
+ 5
@Sachin Artani . you are right
30th Apr 2017, 7:46 AM
Enas Emad
Enas Emad - avatar
+ 5
but I should write int marks[5] . right ?
30th Apr 2017, 7:48 AM
Enas Emad
Enas Emad - avatar
+ 5
I hope I didn't annoy you !..thank you :)
30th Apr 2017, 7:55 AM
Enas Emad
Enas Emad - avatar
+ 5
you Illuminate my post 😀.good luck .
30th Apr 2017, 8:00 AM
Enas Emad
Enas Emad - avatar
+ 4
I had a mistake
30th Apr 2017, 7:47 AM
Enas Emad
Enas Emad - avatar
+ 3
@Sachin Artani .actually, I ran the code without writing i in the first line ( with int ),but it didn't work... did you run my code.?
30th Apr 2017, 7:44 AM
Enas Emad
Enas Emad - avatar
+ 1
#include <iostream> using namespace std; main (){ int mark[5]; for (int i = 0; i<5; i++) cin >> mark[n]; return 0; }
3rd May 2017, 12:36 AM
Hunt Guo
Hunt Guo - avatar