Wednesday 9 November 2016

C Programs

  1. 1] if Loop
  2. To print an Even number
  3. #include<stdio.h>  
  4. #include<conio.h>  
  5. void main()
  6. {  
  7. int number=0;  
  8. clrscr();
  9. printf("enter a number:");  
  10. scanf("%d",&number);  
  11. if(number%2==0)
  12. {  
  13. printf("%d is even number",number);  
  14. }
  15. getch();  
  16. }
  17. Output:
  18. Enter a number 4
  19. 4 is even number
  20. Enter a number 5

  21. 2] While Loop
  22. To print numbers from 1 to 10
  23. #include <stdio.h>      
  24. #include <conio.h>      
  25. void main()
  26. {      
  27. int i=1;    
  28. clrscr();      
  29. while(i<=10)
  30. {
  31. printf("%d \n",i);    
  32. i++;    
  33. getch(); 
  34. }
  35. Output:
  36. 1
  37. 2
  38. 3
  39. 4
  40. 5
  41. 6
  42. 7
  43. 8
  44. 9
  45. 10     
  46. 3)Array [1D-Array]
  47. To print the marks of a student
  48. #include <stdio.h>    
  49. #include <conio.h>    
  50. void main(){    
  51. int i=0;  
  52. int marks[5];//declaration of array  
  53. clrscr();    
  54.  marks[0]=80;//initialization of array  
  55. marks[1]=60;  
  56. marks[2]=70;  
  57. marks[3]=85;  
  58. marks[4]=75;//traversal of array  
  59. for(i=0;i<5;i++){    
  60. printf("%d \n",marks[i]);  
  61. }//end of for loop  
  62. getch();    
  63. }
  64. Output:
  65. 80
    60
    70
    85
    75
  66. 4]Without recursion
  67. #include<stdio.h>  
  68. #include<conio.h> 
  69. void main()  
    1. {  
    2.  int n1=0,n2=1,n3,i,number;  
    3.  clrscr();  
    4.  printf("Enter the number of elements:");  
    5.  scanf("%d",&number);  
    6.  printf("\n%d %d",n1,n2);//printing 0 and 1  
    7.   
    8.  for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed  
    9.  {  
    10.   n3=n1+n2;  
    11.   printf(" %d",n3);  
    12.   n1=n2;  
    13.   n2=n3;  
    14.  }  
    15. getch();  

No comments:

Post a Comment