Ad

Chapter - 9: Arrays

Point out the errors, if any, in the following programs:


Ad
F
Sections
1
Exercises

(a)

#include<stdio.h>
int main()
{
	int array[6] = { 1, 2, 3, 4, 5, 6 };
	int i;
	for (i = 0; i <= 25; i++)
		printf("\n%d", array[i]);
	return 0;
}

Error: No error, but the garbage values will be printed after i = 5.


(b)

#include<stdio.h>
int main()
{
	int sub[50], i;
	for (i = 1; i <= 50; i++)
	{
		sub[i] = i;
		printf("\n%d", sub[i]);
	}
	return 0;
}

Error: No error but the program may crash after at i = 50, due to array overflow.


(c)

#include<stdio.h>
int main()
{
	int a[] = { 10, 20, 30, 40, 50 };
	int j;
	j = a; /* store the address of zeroth element */
	j = j + 3;
	printf("\n%d" *j);
	return 0;
}

Error: j is not a pointer. It cannot save the address.


(d)

#include<stdio.h>
int main()
{
	float a[] = { 13.24, 1.5, 1.5, 5.4, 3.5 };
	float *j;
	j = a;
	j = j + 4;
	printf("\n%d %d %d", j, *j, a[4]);
	return 0;
}

Error: No error, but warning that cannot use %d while printing address or a real number.


(e)

#include<stdio.h>
int main()
{
	int max = 5;
	float arr[max];
	for (i = 0; i < max; i++)
		scanf("%f", &arr[i]);
	return 0;
}

Error: Cannot use a variable in array index, i is not defined.

Ad

© 2024 Garbage Valuegarbage value logo