Uploaded by saha.kanak07

Solved C programming questions

advertisement
CSE2010-Advanced C -LAB 2 Practice problems
Name: Nitish J S
Reg No:20BCE0182
1) Take n elements, arrange the even elements from the beginning in sorted order and the odd
numbers from the last in sorted order. Ex: 2 4 6 9 7 5
#include<stdio.h>
int main()
{
int n;
printf("Enter number of elements in the array: ");
scanf("%d",&n);
printf("Enter the numbers present in the array:\n");
int num[n];
for(int i=0;i<n;i++)
{
scanf("%d",&num[i]);
}
int odd[n];
int even[n];
int j=0,k=0;
for(int i=0;i<n;i++)
{
if(num[i]%2==0)
{
even[j]=num[i];
j++;
}
else{
odd[k]=num[i];
k++;
}
}
int odd_len=k,even_len=j;
for(int i=1;i<even_len;i++)
{
int temp=even[i];
k=i-1;
while(k>=0 && even[k]>temp)
{
CSE2010-Advanced C -LAB 2 Practice problems
even[k+1]=even[k];
k--;
}
even[k+1]=temp;
}
for(int i=1;i<odd_len;i++)
{
int temp=odd[i];
j=i-1;
while(j>=0 && temp>odd[j])
{
odd[j+1]=odd[j];
j--;
}
odd[j+1]=temp;
}
for(int i=0;i<even_len;i++)
{
// printf("%d ",even[i]);
num[i]=even[i];
}
// printf("\n");
for(int i=0;i<odd_len;i++)
{
// printf("%d ",odd[i]);
num[i+even_len]=odd[i];
}
printf("The final array is sorted as per question :\n");
for(int i=0;i<n;i++)
{
printf("%d ",num[i]);
}
}
Output:
CSE2010-Advanced C -LAB 2 Practice problems
2) Find the sum of the elements of the principal diagonal of a 2d array
#include<stdio.h>
int main()
{
printf("Enter number of rows in the matrix:");
int m;
scanf("%d",&m);
printf("Enter number of coloumns in the matrix:");
int n;
scanf("%d",&n);
printf("Enter the elements of the 2d array");
int mat[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
scanf("%d",&mat[i][j]);
}
}
int sum=0;
for(int i=0;i<m;i++){
for(int j=0;j<m;j++)
{
if(i==j)
{
sum+=mat[i][i];
}
}
}
printf("The sum of principal diagonal elements in the 2d array
is: %d",sum);
}
Output:
CSE2010-Advanced C -LAB 2 Practice problems
3) Read n names from the user and sort the names in alphabetical order using insertion sort
#include<stdio.h>
#include<string.h>
int main()
{
int n;
printf("Enter number of students:");
scanf("%d",&n);
char names[100][100];
printf("Enter the names:\n");
for(int i=0;i<n;i++)
{
scanf("%s",names[i]);
}
char temp[100];
printf("\nThe sorted names are:\n");
for(int i=1;i<n;i++)
{
strcpy(temp,names[i]);
int j=i-1;
while(j>=0 && strcmp(names[j],temp)>0)
{
strcpy(names[j+1],names[j]);
j--;
}
strcpy(names[j+1],temp);
}
for(int i=0;i<n;i++)
{
printf("%s\n",names[i]);
}
}
CSE2010-Advanced C -LAB 2 Practice problems
Output:
Download