Monday, March 11, 2013
Sunday, March 10, 2013
Functions in C examples
A function provides a convenient way to encapsulate some computation, which can then be used without worrying about its implementation. With properly designed functions, it is possible to ignore how a job is done; knowing what is done is sufficient. C makes the sue of functions easy, convenient and efficient; you will often see a short function defined and called only once, just because it clarifies some piece of code.
A function definition Syntax:
return-type function-name(parameter declarations, if any)
{
declarations
statements
}
Example:
/*
power.c: This program will give you brief idea about functions.
Author: Afiz S
Date: 11/08/10
*/
#include
int power(int a, int b); //prototype of the function.
main()
{
int a,b;
printf("Enter your 2 number base and exponent\n");
scanf("%d%d",&a,&b);
printf("%dpower %d is = %d\n",a,b,power(a,b)); // calling function.
}
int power(int a, int b) // function defination
{
int i,base=a;
for(i=1;i
{
//printf("%d\n",a);
a=a*base;
}
return a;
}
C format specifiers
| Format Specifiers in C | |
| %i or %d | int |
| %c | char |
| %f | float |
| %lf | double |
| %s | string |
| %hi | short |
| %ld | long int |
| %d,%hu | unsinged short |
| %u | unsinged int |
- \n (newline)
- \t (tab)
- \v (vertical tab)
- \f (new page)
- \b (backspace)
- \r (carriage return)
Format Specifier for int and short in C example
/*
* FormatSpecifiers.c
* Copyright 2013 Afiz <afiz@afiz-Extensa-4620>
*/
#include <stdio.h>
int main(int argc, char **argv)
{
int a =109990909;
short b = 23;
printf("%d,%hi\n",a,b);
return 0;
}
Monday, March 12, 2012
Facts about Sorting Techniques
Bubble sort: comparisons O(n2), Swaps O(n2)
Selection Sort: Comparisons O(n2), swaps O(n)
Insertion Sort: Comparisons O(n2) , no swaps
Insertion sort is best basic sorts.
Selection Sort example program in C
/*
This is a basic program of Selection sort.
Author: Afiz
Date:
*/
#include<stdio.h>
main()
{
int a[5]={9,7,4,8,1};// array with 5 elements.
int out,in,min,i;// local variable declarations
for(out =0;out<4;out++)// outer loop
{
min =out;
for(in=out+1;in<5;in++)// inner loop
{
if(a[in]<=a[min])
min=in;
}
int tmp = a[min]; // swap ....
a[min]=a[out];
a[out]=tmp;
}
//printing array
for(i=0;i<5;i++)
{
printf("%d\n",a[i]);
}
}
Insertion Sort Example program in C
/*
This is a basic program of Insertion sort.
Author: Afiz
Date:
*/
#include<stdio.h>
main()
{
int a[5]={9,7,4,8,1};// array with 5 elements.
int out,in,min,i;// local variable declarations
for(out=1;out<5;out++) // outer loop
{
temp = a[out];
in =out;
while(in>0 && a[in-1]>=temp) // inner loop
{
a[in]=a[in-1];
--in;
}
a[in]=temp;
}
//printing array ..
for(i=0;i<5;i++)
{
printf("%d\n",a[i]); //
}
}
Subscribe to:
Posts (Atom)
