Specification9:
Accept "n" elements into an array append a new
element to the array and print the resultant array.
Logic:
Appending is adding a new element at the end.
Because a[n-1] is the last element, new element must be
added at a[n]
Now
the number of elements would be n+1
|
Program:
#include
void main()
{
int a[50],i,n;
printf("How many elements?");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i
Specification10:
Accept "n" elements into an array and print the
element at a required position.
Logic:
From the user point of view valid position is from 1 to n
From the programmer point of view index of element is from 0
to n-1.
Here index is 1 less than position.
Program:
#include<stdio.h>
void main()
{
int n,i,pos,a[50];
printf("How many elements?");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the position:");
scanf("%d",&pos);
/* according to the user, position must be between 1 and n
*/
if(pos<1 || pos>n) /*checking for valid position*/
printf("Invalid
position");
else
{
pos--; /* index is 1 less than position */
printf("The
element is %d",a[pos]);
}
}
Execution1:
How many elements? 6
34 45 67
22 65 23
Enter the position: 2
The element is 45
Execution explained:
Here 2 is a valid position
Because index is 1 less than position printing a[1] (45) as
output.
Execution2:
How many elements? 6
34 45 67
22 65 23
Enter the position: 0
Invalid position
Execution3:
How many elements? 6
34 45 67
22 65 23
Enter the position: 7
Invalid position
Specification11:
Accept "n" elements into an array and modify the
element at a required position and print the resultant array.
Logic:
When a value is assigned to any element of array, then it will
be overwriting on the existed value.
Program:
#include<stdio.h>
void main()
{
int n,i,a[50],pos;
printf("How many elements?");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the position:");
scanf("%d",&pos);
if(pos<1 || pos>n)
printf("Invalid
position");
else
{
pos--;
printf("Enter
the new element:");
scanf("%d",&a[pos]);
printf("The
resultant array :\n");
for(i=0;i<n;i++)
printf("%5d",a[i]);
}
}
Execution:
How many elements? 7
12 67 54
34 98 27
15
Enter the position: 4
Enter the new element: 55
The resultant array:
12 67 54
55 98 27
15
Specification12:
Accept "n" elements into an array, insert an
element at a required position and print the resultant array.
Logic:
We need to shift the entire elements one place right from
the position.
New value is overwritten at the specified position.
Total
number of elements is incremented by 1
Program:
#include
0 comments:
Post a Comment