Monday, November 24, 2014

C array elements



C Program to Read Array Elements


#include
#include
int main()
{
int i,arr[50],num;
printf("\n Enter no of elements: ");
scanf("%d"&,num);
printf("\n Enter the values: ");
for(i=0;i
{
scanf("%d",&arr[i]);
}
for(i=0;I,num;i++)
{
printf("\n Arr[%d]=%d",i,arr[i]);
}
return(0);
}

C Program to Search an element in Array


#include
#include
int main()
{
int a[3],ele,num,i;
printf("\n Enter no of elements: ");
scanf("%d",&num);
printf("\n Enter the values: ");
for(i=0;i
{
scanf("%d",&a[i]);
}
printf("\n Enter the elements to be searched : ");
scanf("%d",&ele);
i=0;
while(i
{
i++;
}
if(i
{
printf("Number found at the location = %d",i+1);
}
else
{
printf(“Number not found");
}
return (0);
}

Output

Enter no of elements : 5
11      22      33      44      55
Enter the elements to be searched : 44
Number found at the location =4

Print the Program Name and All its Arguments


#include
#include
           void main(int argc, char *argv[])   
{
int i;
for (i = 0;i < argc;i++)
{
   printf("%s ", argv[i]);       
}
printf("\n");
}

Compute First N Fibonacci Numbers using Command Line Arguments

 
#include 
#include
int first = 0;
int second = 1;
int third;
void rec_fibonacci(int);
void main(int argc, char *argv[])
{
int number = atoi(argv[1]);
printf("%d\t%d", first, second); 
rec_fibonacci(number);
printf("\n");
}
void rec_fibonacci(int num)
{
           if (num == 2)    
{
return;
}
third = first + second;
printf("\t%d", third);
first = second;
second = third;
num--;
rec_fibonacci(num);
}

Output
  
 0       1       1       2       3       5       8       13      21      34

Generate Fibonacci Series of N Numbers using Command-Line Argument

 
#include 
#include   
void main(int argc, char * argv[])
{
int n, last = 0, prev = 1, curr, cnt;
n = atoi(argv[1]);
printf("Printing first %d fibonacci nos. -> ", n);
printf("%d ", last);
printf("%d ", prev);
cnt = 2;
while (cnt< = n-1)
{
curr = last + prev;
last = prev;
prev = curr;
cnt++;
printf("%d ", curr);
}
printf("\n");
}

Output
 
Printing first 10 fibonacci nos. -> 0 1 1 2 3 5 8 13 21 34

Input 3 Arguments and Operate Appropriately on the Numbers

 
#include 
#include  
void main(int argc, char * argv[])
{
int a, b, result;
char ch;
printf("arguments entered: \n");
a = atoi(argv[1]);
b = atoi(argv[2]);
ch  = *argv[3];
printf("%d %d %c", a, b, ch);
switch (ch)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case 'x':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
printf("Enter a valid choice");
}
printf("\nThe result of the operation is %d", result);
printf("\n");    
}
 
Output
 
5 4 +
arguments entered:
5 4 +
The result of the operation is 9

No comments:

Post a Comment