C Practical File
C Practical File
Array Declaratoo
Types of array
Iotalizatoo Of Array
Data_type array_oame = array_size
// Program to find the average of n (n < 10) numbers
using arrays
1.
2. #include <stdio.h>
3. int main()
4. {
5. int marks[10], i, n, sum = 0, average;
6. printf("Enter n: ");
7. scanf("%d", &n);
8. for(i=0; i<n; ++i)
9. {
10. printf("Enter number%d: ",i+1);
11. scanf("%d", &marks[i]);
12. sum += marks[i];
13. }
14. average = sum/n;
15.
16. printf("Average = %d", average);
17.
18. return 0;
19. }
C Programing
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
Output
Output
Enter elements: 1
2
3
5
4
You entered:
1
2
3
5
4
C Programing
Output
C strlen() function
1. #include <stdio.h>
2. #include <string.h>
3. int main()
4. {
5. char a[20]="Program";
6. char b[20]={'P','r','o','g','r','a','m','\0'};
7. char c[20];
8.
9. printf("Enter string: ");
10. gets(c);
11.
12. printf("Length of string a = %d \n",strlen(a));
13.
14. //calculates the length of string before null charcter.
15. printf("Length of string b = %d \n",strlen(b));
16. printf("Length of string c = %d \n",strlen(c));
17.
18. return 0;
19. }
Output
Length of string a = 7
Length of string b = 7
Length of string c = 6
1. include <stdio.h>
2. #include <stdlib.h>
3.
4. int main()
5. {
6. int n, i, *ptr, sum = 0;
7.
8. printf("Enter number of elements: ");
9. scanf("%d", &n);
10.
11. ptr = (int*) malloc(n * sizeof(int));
12. if(ptr == NULL)
13. {
14. printf("Error! memory not allocated.");
15. exit(0);
16. }
17.
18. printf("Enter elements: ");
19. for(i = 0; i < n; ++i)
20. {
21. scanf("%d", ptr + i);
22. sum += *(ptr + i);
23. }
24.
25. printf("Sum = %d", sum);
26. free(ptr);
27. return 0;
28. }
1. #include <stdio.h>
2. #include <stdlib.h>
C Programing
3.
4. int main()
5. {
6. int n, i, *ptr, sum = 0;
7. printf("Enter number of elements: ");
8. scanf("%d", &n);
9.
10. ptr = (int*) calloc(n, sizeof(int));
11. if(ptr == NULL)
12. {
13. printf("Error! memory not allocated.");
14. exit(0);
15. }
16.
17. printf("Enter elements: ");
18. for(i = 0; i < n; ++i)
19. {
20. scanf("%d", ptr + i);
21. sum += *(ptr + i);
22. }
23.
24. printf("Sum = %d", sum);
25. free(ptr);
26. return 0;
27. }
realloc()
1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. int main()
5. {
6. int *ptr, i , n1, n2;
7. printf("Enter size of array: ");
8. scanf("%d", &n1);
9.
10. ptr = (int*) malloc(n1 * sizeof(int));
11.
12. printf("Addresses of previously allocated memory: ");
13. for(i = 0; i < n1; ++i)
14. printf("%u\n",ptr + i);
15.
16. printf("\nEnter new size of array: ");
17. scanf("%d", &n2);
18. ptr = realloc(ptr, n2 * sizeof(int));
19.
20. printf("Addresses of newly allocated memory: ");
21. for(i = 0; i < n2; ++i)
22. printf("%u\n", ptr + i);
C Programing
23. return 0;
24. }