Search This Blog

Tuesday 28 June 2011

Silly Pieces - Part 2 (Array Manipulation )

Searching an element in an Array :

  1. int main()
  2. {
  3.         int *array;                                           //array
  4.         int n;                                                   //array-length
  5.         int x;                                                   //number to be searched

  6.         printf "Enter the number of elements: " );
  7.         scanf ("%d" , &n);

  8.         array = (int*)malloc( n * sizeof(int));
  9.         for(int i=0 ; i < n ; i++ ){
  10.               scanf ("%d",&array[i]);
  11.         }

  12.          printf( "Enter the number to be searched: ");
  13.          scanf"%d" , &x);

  14.          for(int i=0 ; i<n ; i++){
  15.               if( x == array[i]){
  16.                    printf ("The number is found in the list at place %d",i+1);
  17.                    break;
  18.               }
  19.          }

  20.          return 0;
  21.  }

Sorting the elements in an arrray :

  1. int main()
  2. {
  3.        int *array;
  4.        int n;
  5.        int i,j;

  6.        printf "Enter the number of elements: " );
  7.        scanf ("%d" , &n);

  8.        array = (int*)malloc( n * sizeof(int));
  9.        fori=0 ; i<n ; i++ ){
  10.              scanf("%d",&array[i]);
  11.        }

  12.        int temp;
  13.        fori=0 ; i<n ; i++){
  14.              forj=i ; j<n ; j++){
  15.                      if(a[i]>a[j]){
  16.                            temp = array[i];
  17.                            array[i] = array[j];
  18.                            array[j] = temp;
  19.                      }
  20.              }
  21.        }

  22.        fori=0 ; i<3 ; i++){
  23.             printf(" %d",array[i]);
  24.        }

  25.        return 0;
  26. }
Binary Search:

  1. int main()
  2. {
  3. int *array;
  4. int n;
  5. int i,j,

  6. printf("Enter the number of elements: \n");
  7. scanf("%d",&n);

  8.     array = (int*)malloc(n*sizeof(int)); 
  9. printf("Enter the elements one by one:\n");
  10. for(i=0; i<n ;i++){
  11. scanf("%d",&array[i]);
  12. }
  13. printf("Given array elements\n");
  14. for (i=0; i <n ; i++){
  15. printf("%d\n",array[i]);
  16. }

  17. /* Bubble sorting begins */
  18. int temp;
  19. for(i=0; i< n ; i++){
  20. for(j=0; j< (n-i-1) ; j++){
  21. if(array[j] > array[j+1]){
  22. temp = array[j];
  23. array[j] = array[j+1];
  24. array[j+1] = temp;
  25. }
  26. }
  27. }

  28. printf("Sorted array is...\n");
  29. for(i=0; i<n ; i++ ){
  30. printf("%d\n",array[i]);
  31. }

  32. printf("Enter the element to be searched\n");
  33. scanf("%d", &keynum);

  34. /* Binary searching begins */

  35. int keynum;
  36.      int low,mid,high;

  37. low=1;
  38. high=n;

  39. do {
  40. mid= (low + high) / 2;
  41. if ( keynum < array[mid] )
  42. high = mid - 1;
  43. else if ( keynum > array[mid])
  44. low = mid + 1;
  45. } while( keynum!=array[mid] && low <= high); 

  46. if( keynum == array[mid] )
  47. printf("SUCCESSFUL SEARCH\n");
  48. else
  49. printf("Search is FAILED\n");
  50.              return 0 ;
  51. }
Variance :

  1. #include<math.h>   //for sqrt();
  2. int main()
  3. {
  4.     float elements[10],mean,SD,variance,sum;
  5.     int i,n;

  6.     printf("Enter the number of elements: ");
  7.     scanf("%d",&n);

  8.     printf ("Enter the entries: \n");
  9.     for( i=0 , sum = 0; i<n ; i++){
  10.         scanf ("%d",&elements[i]);
  11.         sum += elements[i];
  12.     }

  13.     mean=(float)(sum)/(float)(n);

  14.     float numerator;
  15.     for( i=0 , numerator = 0 ; i<n ; i++ ){
  16.         numerator+=(float)((mean-elements[i])*(mean-elements[i]));
  17.         variance = float(numerator / n);
  18.         SD=sqrt(variance);
  19.     }

  20.     printf("\nMean: %.2f\nVariance:  %.2f\nStandard Deviation: .2f\n",mean,variance,SD);
  21.     return 0; 
  22. }


Matrix Transpose
  1. int main()
  2. {
  3.       int matrix[5][5].n;
  4.       int temp;
  5.       int i,j;
  6.  
  7.       printf("Enter the no. of rows (or) columns: ");
  8.       scanf("%d",&r);
  9.  
  10.       printf("\n\nEnter the entries: \n");
  11.       fori=0 ; i<r ; i++)
  12.            forj=0 ; j<r ; j++)
  13.                 scanf ( "%d",&a[i][j] );
  14.  
  15.       fori=0 ; i<r ; i++)
  16.             forj=i+1 ; j<r ; j++){
  17.                  temp=a[i][j];
  18.                  a[i][j]=a[j][i];
  19.                  a[j][i]=temp;
  20.            }
  21.          printf ("\n\n");
  22.      }
  23.      
  24.     for(i=0;i<r;i++){
  25.            for(j=0;j<r;j++){
  26.                 printf" %d",a[i][j]);
  27.            }
  28.            printf ("\n");
  29.     }
  30.  
  31.     return 0;
  32.  }

Matrix Multiplication

  1. int main()
  2. {
  3.         int a[5][5],b[5][5],c[5][5];
  4.         int i,j,k;
  5.         int r1,r2,c1,c2;

  6.         printf("Enter the number of rows and columns of matrices A and B:");
  7.         scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
  8.  
  9.         ifc1 == r2 ) {
  10.                printf("Enter the entries for matrix A:\n");
  11.                fori=0 ; i<r1 ; i++)
  12.                       forj=0 ; j<c1 ; j++)
  13.                             scanf("%d",&a[i][j]);
  14.    
  15.             printf("\nEnter the entries for matrix B:\n");
  16.              fori=0 ; i<r2 ; i++)
  17.                    forj=0 ; j<c2 ; j++)
  18.                           scanf("%d",&b[i][j]);
  19.               
  20.               //matrix multiplication 
  21.               fori=0 ; i<r1 ; i++){
  22.                   forj=0 ; j<c2 ; j++){
  23.                       c[i][j] = 0;
  24.                       fork=0 ; k<r2 ; k++ )
  25.                             c[i][j] += a[i][k] * b[k][j] ;
  26.                   }
  27.               }

  28.                printf("\n\nThe product matrix: \n");
  29.                fori=0 ; i<r1 ; i++){
  30.                     forj=0 ; j<c2 ; j++)
  31.                           printf("  %d",c[i][j]);
  32.                     printf("\n");
  33.                }
  34.           }else
  35.                    printf("\n\nThe matrices cannot be multiplied......");

  36.           return 0;
  37.  }

Silly Pieces - Part 1

Temperature Conversion from Farenheit to Celcius :
        T(in F) = (9/5) T (in C) + 32
  1. int main()
  2. {
  3.        float T_C,T_F;
  4.  
  5.        printf ("Enter temperature in celsius: ");
  6.        scanf("%f",&T_C);
  7.  
  8.        T_F=(1.8*T_C)+32;
  9.        printf("\n\nTemperature in farenheit: %.2f",f);
  10.  
  11.        return 0;
  12. }
Factorial of a Number :
        Factorial of a number, n = n! = n.(n-1).(n-2).(n-3)...3.2.1
                 This  method is iterative(looping) method. Another method called recursive method
 is shown in exponential series evaluation.
  1. int main()
  2. {
  3.         int number,fac_num;

  4.         printf ("Enter a number: ");
  5.         scanf("%d",&number);
  6.          
  7.         int i;
  8.         for( i = 1 ;i <= number ; i++ ){
  9.               fac_num*=i;
  10.         }
  11.         printf("Factorial: %d",fac_num);
  12.         return 0; 
  13. }
Number Reversal :
     If u give input = 123 , the output will be 321
        123 = 1( 100)+2(10)+3(1) 
        321 = 3( 100)+2(10)+1(1) 
  1. int  main()
  2. {
  3.        int digit,number,reversed;
  4.  
  5.        printf ("Enter a number: ");
  6.        scanf ("%d",&number);

  7.        reversed = 0;
  8.        while(number>0) {
  9.                  digit = number % 10;
  10.                  reversed = ( reversed * 10 ) + digit;
  11.                  number /= 10;
  12.        }
  13.  
  14.        printf ("The reverse of the number : %d ,reversed);
  15.        return 0;
  16. }
Evaluation of Exponential Series ( up-to 50 terms) : 
                  e^x = \sum_{n = 0}^{\infty} {x^n \over n!} = 1 + x + {x^2 \over 2!} + {x^3 \over 3!} + {x^4 \over 4!} + \cdots.
  1. //function to calculate factorial (recursive )
  2. float fac(float i)
  3.   {
  4.      if( i == 1)
  5.         return( 1 );
  6.      else
  7.         return( i * fac (i-1) );
  8.   }

  9. int main()
  10. {
  11.    float x, exp_x, numer , denom ;
  12.    float n;

  13.    printf ("\n Enter the value of x: ") ;
  14.    scanf ("%f",&x) ; 

  15.    for(n = 0 ; n <= 50 ; i++ ){
  16.         numer  = pow (x,n);
  17.         denom = fac ( n );
  18.         exp_x = exp_x+numer/denom;
  19.       }

  20.    printf ("\n e^%f=%e",x,exp_x);
  21.    return 0;
  22. }
Binary to Decimal Conversion:
           For conversion from any number system to decimal system the formula is 
                  Decimal Value = Dn( nth-Weight ) +. . . . .+ D1( 1st-Weight ) + D0(0th-Weight).
           For 4 digit binary number
                  Decimal Value = D3 ( 8 ) + D2 ( 4 ) + D1 ( 2 ) + D0 ( 1 ).

  1. int main()
  2. {
  3.       int decimal,binary;
  4.     
  5.       printf ("Enter the binary code:");
  6.       scanf ( "%d",&binary);
  7.  
  8.       int temp, i;
  9.       decimal = 0;
  10.       while(binary > 0){
  11.                 temp = binary % 10 ;
  12.                 decimal += temp * pow(2,i);
  13.                 binray /= 10;
  14.                 i++;
  15.       }
  16.  
  17.       printf("\n\nEquivalent decimal value: %d",decimal);
  18.  
  19.       return 0; 
  20. }

Odd or Even


 This is a simple program to illustrate the coding flow.

 Since all even numbers are divisible by 2 
 Algorithm:
           READ input into number
           IF MOD( number , 2 ) IS EQUAL TO ZERO THEN number IS even
           IF MOD( number , 2 ) IS NOT EQUAL TO ZERO THEN number IS odd.

Code Listing:

  1. int main()
  2. {
  3.     int n;
  4.     
  5.     printf ("Enter a number: ");
  6.     scanf ("%d",&n);
  7.  
  8.     if (n%2 ==0 ) {
  9.             printf ("The number is Even");
  10.     } else {
  11.             printf ("The number is Odd");
  12.     }

  13.    getch();
  14.    return 0;
  15.  
  16. }

C - Review

From Wikipedia 
C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. Although C was designed for implementing system software, it is also widely used for developing portable application software.
C is one of the most popular programming languages. It is widely used on many different software platforms, and there are few computer architectures for which a C compiler does not exist. C has greatly influenced many other popular programming languages, most notably C++, which originally began as an extension to C.




From CProgramming 
Third, C is reasonably close to the machine. When you're working with pointers, bytes, and individual bits, things like optimization techniques start to make a lot more sense. There's also utility in knowing exactly how something works underneath the hood -- this helps a great deal when something you're trying to do in a higher level language seems way slower than expected, or just doesn't work at all. You also tend to get a better picture of advanced topics like exactly how networking works. A higher level language will make it a little bit simpler, but it'll be harder to understand what's going on, and when things stop working, it's much better to know exactly what's going on so you can fix it. Additionally, if you like computer science as a discipline, or just like knowing how things work learning the details of the system is great fun.  



From Crasseux
  • Before C, machine-language programmers criticized high-level languages because, with their black box approach, they shielded the user from the working details of the computer and all its facilities. C, however, was designed to give access to any level of the computer down to raw machine language, and because of this, it is perhaps the most flexible high-level language.
  • C has features that allow the programmer to organize programs in a clear, easy, logical way. For example, C allows meaningful names for variables without any loss of efficiency, yet it gives a complete freedom of programming style, including flexible ways of making decisions, and a set of flexible commands for performing tasks repetitively (forwhiledo).
  • C is succinct. It permits the creation of tidy, compact programs. This feature can be a mixed blessing, however, and the C programmer must balance simplicity and readability.
  • C allows commands that are invalid in other languages. This is no defect, but a powerful freedom which, when used with caution, makes many things possible. It does mean that there are concealed difficulties in C, but if you write carefully and thoughtfully, you can create fast, efficient programs.
  • With C, you can use every resource your computer offers. C tries to link closely with the local environment, providing facilities for gaining access to common peripherals like disk drives and printers. When new peripherals are invented, the GNU community quickly provides the ability to program them in C as well. In fact, most of the GNU project is written in C (as are many other operating systems). 
From Answers


  • Speed of the resulting application. C source code can be optimized much more than higher-level languages because the language set is relatively small and very efficient (other reasons too, discussed later). It is about as close as you can get to programming in assembly language, without programming in assembly language (if you don't know what assembly is just Google it). Heck you can even use assembly and C together!

  • That leads to a second advantage that C has which is its application in Firmware programming (hardware). That is due to its ability to use/work with assembly and communicate directly with controllers, processors and other devices.

  • C is a building bock for many other currently known languages. Look up the history of C and you will find that it has been around for some time (as programming languages go anyway). Take a look at Python for example a fully Object-Oriented High-Level programming language. It is written in C (perhaps C++ too). That tells you if you ever want to know what is going on under the hood in other languages; understanding C and how it works is essential.

  • That leads to the final advantage that I will touch on (there are no doubt others and disadvantages as well); C is a compiled language versus an interpreted language. Explained simply, this means that the code is compacted into executable instruction (in the case of windows anyway) rather than being "translated" on the fly at run time. This feature also lends heavily to the speed of C programs.
It is important to remember that each language however has its application, strengths and weaknesses. It really all boils down to what your end result goals are. Driving a Lamborghini 25 mph to and from work isn't what that car is intended for… 

Learning C is the is entry point into Programming world