Array and Loops

Jul 25, 2016 at 4:18pm
Having problem it says "mark is undefined.
line #9

1
2
3
4
5
6
7
8
9
10
11
12
13
  #include<stdio.h>
#include<conio.h>

void main()
{
clrscr();
for(int a=0;a<3;a++)
{
 printf("Subject %d:"); scanf("%d", &mark[a]);
 int tot=mark[1]+mark[2]+mark[3];
 printf("%d",tot); }
 getch();
 }
Jul 25, 2016 at 4:19pm
Hi,

could you explain this?

printf("Subject %d:");
Jul 25, 2016 at 4:21pm
printf("Subject %d:",a);
corrected it
still same error that mark is undefined

Jul 25, 2016 at 4:23pm
remove the , (comma operator) and try
Jul 25, 2016 at 4:24pm
still the same error
Jul 25, 2016 at 4:28pm
Probably that is because you try to use a variable called mark at line 9 and 10:

1
2
scanf("%d", &mark[a]);
int tot=mark[1]+mark[2]+mark[3];


But you don't create a variable called mark before you try to use it, so for the compiler the variable mark is indeed undefined.
You should either remove these lines or create an array of integers called mark somewhere before line 7.
Last edited on Jul 25, 2016 at 4:30pm
Jul 25, 2016 at 4:29pm
how to create it?
Jul 25, 2016 at 4:30pm
You haven't declared mark[], you have to declare it first to use it
Jul 25, 2016 at 4:36pm
please correct the code someone
i want to take output from user
for example
subject 1: 78 etc
and add them all and give output its sum.
using array and loops
Jul 25, 2016 at 4:44pm
Warning I haven't learnt C yet, so there may be some errors which I can't see

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 #include<stdio.h>
#include<conio.h>

void main()
{
clrscr();
int mark[3],b=0,tot=0;
for(int a=0;a<3;a++)
{b=a+1;//for index

 printf("Subject %d:",&b);
 scanf("%d", &mark[a]);
 tot+=mark[a];

}


 printf("%d",tot); }
 getch();
 }


HOPE IT HELPS :)
Jul 25, 2016 at 4:47pm

I don't know C but in C++ you can use dynamic arrays with runtime size to do something like this. run it on cpp.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>

int main()
{
    int sum=0;
    int ENTRY;
    std::cout<<"Enter how many numbers you want to add: " ;
    std::cin>>ENTRY;
    int *input= new int[ENTRY];
    for(int i=0; i<ENTRY; ++i)
    {
        std::cout<<"Enter entry no. "<<i+1<<"\n";
        std::cin>>input[i];
        sum+=input[i];
    }
    std::cout<<"Sum = "<<sum<<"\n";
    delete[] input;

}
Last edited on Jul 25, 2016 at 6:50pm
Topic archived. No new replies allowed.