Exercise 23 HarshKumar 23
Exercise 23 HarshKumar 23
138. Write a function using pointers to add two matrices and to return the resultant
matrix to the calling function.
Program:
#include <stdio.h>
#include <conio.h>
int a[5][5], b[5][5], row, col;
void add(int (*)[5]);
int main()
{
int c[5][5], i, j;
clrscr();
printf("Enter row : ");
scanf("%d", &row);
printf("Enter column : ");
scanf("%d", &col);
printf("Enter matrix A :\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter matrix B :\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
scanf("%d", &b[i][j]);
}
}
add(c);
printf("Addition :\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("%d\t", c[i][j]);
}
printf("\n");
}
getch();
return 0;
}
void add(int c[5][5])
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
Output:
139. C program to find length of a string using pointer
Program:
#include<stdio.h>
int main(){
char str[50] = "Hello";
int c=0;
char *ptr;
ptr = &str[0];
while((*ptr) != '\0'){
c++;
ptr ++;
}
printf("Lenght of string : %d",c);
return 0;
}
Output:
Lenght of string : 5
140. C program to copy one string to another string using pointer.
Program:
Output:
char *a = str1;
char *b = str2;
while(*a)
{
a++;
}
while(*b)
{
*a = *b;
b++;
a++;
}
*a = '\0';
printf("\n\n\nThe string after concatenation is: %s ", str1);
return 0;
}
Output:
Enter the first string: hello
char str1[20],str2[20],i,j,flag=0;
i=0;
j=0;
while(str1[i]!='\0')
{
i++;
}
while(str2[j]!='\0')
{
j++;
}
if(i!=j)
{
flag=0;
}
else
{
for(i=0,j=0;str1[i]!='\0',str2[j]!='\0';i++,j++)
{
if(str1[i]==str2[j])
{
flag=1;
}
}
}
if(flag==0)
{
printf("\nStrings are not equal\n");
}
else
{
printf("\nStrings are equal.\n");
}
return 0;
}
Output:
Enter first string :: hello
int main()
{
int arr[MAX_SIZE];
int size;
return 0;
}
elemToSort++;
}
curElem++;
}
}
Output:
Enter array size: 10
Enter elements in array: 10 -1 0 4 2 100 15 20 24 -5
Elements before sorting: 10, -1, 0, 4, 2, 100, 15, 20, 24, -5,
Array in ascending order: -5, -1, 0, 2, 4, 10, 15, 20, 24, 100,
Array in descending order: 100, 24, 20, 15, 10, 4, 2, 0, -1, -5,
144. Write a program in C to compute the sum of all elements in an array using
pointers.
Program:
#include <stdio.h>
#include <malloc.h>
void main(){
int i, n, sum = 0;
int *ptr;
printf("Enter size of array : \n");
scanf("%d", &n);
ptr = (int *) malloc(n * sizeof(int));
printf("Enter elements in the List \n");
for (i = 0; i < n; i++){
scanf("%d", ptr + i);
}
//calculate sum of elements
for (i = 0; i < n; i++){
sum = sum + *(ptr + i);
}
printf("Sum of all elements in an array is = %d\n", sum);
return 0;
}
Output:
Enter size of array :
5
Enter elements in the List
1
2
3
4
5
Sum of all elements in an array is = 15
p = s;
while (*p)
{
if ((*p >= 65 && *p <= 90) || (*p >= 97 && *p <= 122))
{
return 0;
}
Output:
Enter the string : AEIOU aeiou
vowels = 10
consonants = 0