Sie sind auf Seite 1von 37

Fibonacci series in c using for loop

/* Fibonacci Series c language */


#include<stdio.h>

for( c = 1 ; c <= number ; c++ )


{
temp = c;
while( temp != 0 )
{
r = temp%10;
sum = sum + r*r*r;
temp = temp/10;
}
if ( c == sum )
printf("%ld\n", c);
sum = 0;
}

int main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}
Output of program:

return 0;
}

Prime number program in c language


#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers
required\n");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}

C programming code
#include <stdio.h>
int main()
{
int r;
long number = 0, c, sum = 0, temp;
printf("Enter an integer upto which you want to find
armstrong numbers\n");
scanf("%ld",&number);
printf("Following armstrong numbers are found from 1
to %ld\n",number);

return 0;
}

C Armtrong or not
#include <stdio.h>
int main()
{
int number, sum = 0, temp, remainder;

REVERSE
#include <stdio.h>
int main()
{
int n, reverse = 0;

printf("Enter an integer\n");
scanf("%d",&number);

printf("Enter a number to reverse\n");


scanf("%d",&n);

temp = number;

while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}

while( temp != 0 )
{
remainder = temp%10;
sum = sum + remainder*remainder*remainder;
temp = temp/10;
}
if ( number == sum )
printf("Entered number is an armstrong number.\n");
else
printf("Entered number is not an armstrong
number.\n");
return 0;
}

Palindrome number program c


#include <stdio.h>

printf("Reverse of entered number is = %d\n", reverse);


return 0;
}
C programming code
#include <stdio.h>
int main()
{
int n, sum = 0, c, value;
printf("Enter the number of integers you want to
add\n");
scanf("%d", &n);
printf("Enter %d integers\n",n);

int main()
{
int n, reverse = 0, temp;

for (c = 1; c <= n; c++)


{
scanf("%d", &value);
sum = sum + value;
}

printf("Enter a number to check if it is a palindrome or


not\n");
scanf("%d",&n);

printf("Sum of entered integers = %d\n",sum);

temp = n;
while( temp != 0 )
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp = temp/10;
}
if ( n == reverse )
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n", n);
return 0;
}

return 0;
}
C program to find nCr and nPr: This code calculate nCr
which is n!/(r!*(n-r)!) and nPr = n!/(n-r)!
C program to find nCr using function
#include<stdio.h>
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
main()
{

int n, r;
long ncr, npr;

printf("Factorial of %d = %d\n", n, fact);

printf("Enter the value of n and r\n");


scanf("%d%d",&n,&r);

ncr = find_ncr(n, r);


npr = find_npr(n, r);

Factorial program in c using function


#include <stdio.h>

printf("%dC%d = %ld\n", n, r, ncr);


printf("%dP%d = %ld\n", n, r, npr);

long factorial(int);

return 0;
}
long find_ncr(int n, int r)
{
long result;

return 0;

int main()
{
int number;
long fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &number);

result = factorial(n)/(factorial(r)*factorial(n-r));

printf("%d! = %ld\n", number, factorial(number));

return result;

return 0;

long find_npr(int n, int r)


{
long result;

long factorial(int n)
{
int c;
long result = 1;

result = factorial(n)/factorial(n-r);

for (c = 1; c <= n; c++)


result = result * c;

return result;
}
long factorial(int n)
{
int c;
long result = 1;
for( c = 1 ; c <= n ; c++ )
result = result*c;
return ( result );
}
Factorial program in c using for loop

return result;
}
Factorial program in c using recursion
#include<stdio.h>
long factorial(int);
int main()
{
int n;
long f;

Loop

printf("Enter an integer to find factorial\n");


scanf("%d", &n);

#include <stdio.h>

if (n < 0)
printf("Negative integers are not allowed.\n");
else
{
f = factorial(n);
printf("%d! = %ld\n", n, f);
}

int main()
{
int c, n, fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
fact = fact * c;

return 0;
}
long factorial(int n)
{

if (n == 0)
return 1;
else
return(n * factorial(n-1));

Output of program:

}
Recursion is a technique in which a function calls itself,
for example in above code factorial function is calling
itself. To solve a problem using recursion you must first
express its solution in recursive form. C program to find
hcf and lcm: The code below finds highest common factor
and least common multiple of two integers. HCF is also
known as greatest common divisor(GCD) or greatest
common factor(gcf).
C programming code

C program to find hcf and lcm using recursion


#include <stdio.h>
long gcd(long, long);
int main() {
long x, y, hcf, lcm;
printf("Enter two integers\n");
scanf("%ld%ld", &x, &y);

#include <stdio.h>
int main() {
int a, b, x, y, t, gcd, lcm;
printf("Enter two integers\n");
scanf("%d%d", &x, &y);
a = x;
b = y;
while (b != 0) {
t = b;
b = a % b;
a = t;
}
gcd = a;
lcm = (x*y)/gcd;
printf("Greatest common divisor of %d and %d =
%d\n", x, y, gcd);
printf("Least common multiple of %d and %d = %d\n",
x, y, lcm);
return 0;
}

hcf = gcd(x, y);


lcm = (x*y)/hcf;
printf("Greatest common divisor of %ld and %ld =
%ld\n", x, y, hcf);
printf("Least common multiple of %ld and %ld =
%ld\n", x, y, lcm);
return 0;
}
long gcd(long a, long b) {
if (b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}
C program to find hcf and lcm using function
#include <stdio.h>
long gcd(long, long);

Download HCF and LCM program.

int main() {
long x, y, hcf, lcm;
printf("Enter two integers\n");
scanf("%ld%ld", &x, &y);
hcf = gcd(x, y);
lcm = (x*y)/hcf;

printf("Greatest common divisor of %ld and %ld =


%ld\n", x, y, hcf);
printf("Least common multiple of %ld and %ld =
%ld\n", x, y, lcm);

printf("%ld ",factorial(i)/(factorial(c)*factorial(ic)));
printf("\n");
}

return 0;
}

return 0;
}

long gcd(long x, long y) {


if (x == 0) {
return y;
}
while (y != 0) {
if (x > y) {
x = x - y;
}
else {
y = y - x;
}
}
return x;
}
Pascal Triangle in c: C program to print Pascal triangle
which you might have studied in Binomial Theorem in
Mathematics. Number of rows of Pascal triangle to print
is entered by the user. First four rows of Pascal triangle
are shown below :-

long factorial(int n)
{
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
Code find maximum or largest element present in an
array. It also prints the location or index at which
maximum element occurs in array. This can also be done
by using pointers (see both codes).
C programming code
#include <stdio.h>
int main()
{
int array[100], maximum, size, c, location = 1;

1
11
121
1331
Pascal triangle in c
#include <stdio.h>
long factorial(int);
int main()
{
int i, n, c;
printf("Enter the number of rows you wish to see in
pascal triangle\n");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
for (c = 0; c <= (n - i - 2); c++)
printf(" ");
for (c = 0 ; c <= i; c++)

printf("Enter the number of elements in array\n");


scanf("%d", &size);
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]);
maximum = array[0];
for (c = 1; c < size; c++)
{
if (array[c] > maximum)
{
maximum = array[c];
location = c+1;
}
}
printf("Maximum element is present at location %d and
it's value is %d.\n", location, maximum);
return 0;
}
Download Maximum element in array program.

Output of program:

known as sequential search. It is very simple and works as


follows: We keep on comparing each element with the
element to search until the desired element is found or list
ends. Linear search in c language for multiple
occurrences and using function.
Linear search c program
#include <stdio.h>

C programming code using pointers

int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in array\n");
scanf("%d",&n);

#include <stdio.h>

printf("Enter %d integer(s)\n", n);

int main()
{
long array[100], *maximum, size, c, location = 1;

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter the number of elements in array\n");


scanf("%ld", &size);
printf("Enter %ld integers\n", size);
for ( c = 0 ; c < size ; c++ )
scanf("%ld", &array[c]);
maximum = array;
*maximum = *array;
for (c = 1; c < size; c++)
{
if (*(array+c) > *maximum)
{
*maximum = *(array+c);
location = c+1;
}
}
printf("Maximum element found at location %ld and it's
value is %ld.\n", location, *maximum);
return 0;
}
The complexity of above code is O(n) as the time used
depends on the size of input array or in other words time
to find maximum increases linearly as array size grows.
Linear search in c programming: The following code
implements linear search (Searching algorithm) which is
used to find whether a given number is present in an array
and if it is present then at what location it occurs. It is also

printf("Enter the number to search\n");


scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* if required element found
*/
{
printf("%d is present at location %d.\n", search,
c+1);
break;
}
}
if (c == n)
printf("%d is not present in array.\n", search);
return 0;
}
Download Linear search program.

Output of program:

Download Linear search multiple occurrence program.


Output of code:

C program for binary search


Linear search for multiple occurrences
In the code below we will print all the locations at which
required element is found and also the number of times it
occur in the list.

C program for linear search using function

#include <stdio.h>

#include <stdio.h>

int main()
{
int array[100], search, c, n, count = 0;

int linear_search(int*, int, int);

printf("Enter the number of elements in array\n");


scanf("%d",&n);

int main()
{
int array[100], search, c, n, position;

printf("Enter %d numbers\n", n);

printf("Enter the number of elements in array\n");


scanf("%d",&n);

for ( c = 0 ; c < n ; c++ )


scanf("%d",&array[c]);

printf("Enter %d numbers\n", n);


for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);

printf("Enter the number to search\n");


scanf("%d",&search);
for ( c = 0 ; c < n ; c++ )
{
if ( array[c] == search )
{
printf("%d is present at location %d.\n", search,
c+1);
count++;
}
}
if ( count == 0 )
printf("%d is not present in array.\n", search);
else
printf("%d is present %d times in array.\n", search,
count);
return 0;
}

printf("Enter the number to search\n");


scanf("%d",&search);
position = linear_search(array, n, search);
if ( position == -1 )
printf("%d is not present in array.\n", search);
else
printf("%d is present at location %d.\n", search,
position+1);
return 0;
}
int linear_search(int *pointer, int n, int find)
{
int c;

for ( c = 0 ; c < n ; c++ )


{
if ( *(pointer+c) == find )
return c;
}

#include <stdio.h>

return -1;

if ( x == 1 )
printf("x is equal to one.\n");
else
printf("For comparison use == as = is the assignment
operator.\n");

}
Time required to search an element using linear search

main()
{
int x = 1;

algorithm depends on size of list. In best case element is


present at beginning of list and in worst case element is
present at the end. Time complexity of linear search is
O(n).

return 0;
}
Output:
x is equal to one.

C program examples
Example 1 - C hello world program
/* A very simple c program printing a string on screen*/
#include <stdio.h>
main()
{
printf("Hello World\n");
return 0;
}

Example 4 - loop example


#include <stdio.h>
main()
{
int value = 1;
while(value<=3)
{
printf("Value is %d\n", value);
value++;
}

Output of above program:


"Hello World"
Example 2 - c program to take input from user using scanf

return 0;
}
Output:

#include <stdio.h>

Value is 1

main()
{
int number;

Value is 2

printf("Enter an integer\n");
scanf("%d",&number);
printf("Integer entered by you is %d\n", number);
return 0;
}
Output:
Enter a number
5
Number entered by you is 5
Example 3 - using if else control instructions

Value is 3
Example 5 - c program for prime number
#include <stdio.h>
main()
{
int n, c;
printf("Enter a number\n");
scanf("%d", &n);
if ( n == 2 )
printf("Prime number.\n");
else
{
for ( c = 2 ; c <= n - 1 ; c++ )
{

if ( n % c == 0 )
break;
}
if ( c != n )
printf("Not prime.\n");
else
printf("Prime number.\n");

void my_function();
main()
{
printf("Main function.\n");

}
return 0;

my_function();

printf("Back in function main.\n");

Example 6 - command line arguments

return 0;
}

#include <stdio.h>
main(int argc, char *argv[])
{
int c;
printf("Number of command line arguments passed:
%d\n", argc);

void my_function()
{
printf("Welcome to my function. Feel at home.\n");
}
Example 9 - Using comments in a program
#include <stdio.h>

for ( c = 0 ; c < argc ; c++)


printf("%d. Command line argument passed is %s\n",
c+1, argv[c]);

main()
{
// Single line comment in c source code

return 0;
}

printf("Writing comments is very useful.\n");

Above c program prints the number and all arguments


which are passed to it.
Example 7 - Array program

/*
* Multi line comment syntax
* Comments help us to understand code later easily.
* Will you write comments while developing
programs ?
*/

#include <stdio.h>
main()
{
int array[100], n, c;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
printf("Array elements entered by you are:\n");
for ( c = 0 ; c < n ; c++ )
printf("array[%d] = %d\n", c, array[c]);
return 0;
}
Example 8 - function program
#include <stdio.h>

printf("Good luck c programmer.\n");


return 0;
}
Example 10 - using structures in c programming
#include <stdio.h>
struct programming
{
float constant;
char *pointer;
};
main()
{
struct programming variable;
char string[] = "Programming in Software
Development.";
variable.constant = 1.23;
variable.pointer = string;

printf("%f\n", variable.constant);
printf("%s\n", variable.pointer);

#include <stdio.h>
#include <string.h>

return 0;

int main()
{
char a[100], b[100];

}
Example 11 - c program for Fibonacci series
#include <stdio.h>

printf("Enter the string to check if it is a


palindrome\n");
gets(a);

main()
{
int n, first = 0, second = 1, next, c;

strcpy(b,a);
strrev(b);
if( strcmp(a,b) == 0 )
printf("Entered string is a palindrome.\n");
else
printf("Entered string is not a palindrome.\n");

printf("Enter the number of terms\n");


scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;

return 0;
}
This c program generates pseudo random numbers using
rand and random function(Turbo C compiler only). As the
random numbers are generated by an algorithm used in a
function they are pseudo random, this is the reason why
pseudo word is used. Function rand() returns a pseudo
random number between 0 and RAND_MAX.
RAND_MAX is a constant which is platform dependent
and equals the maximum value returned by rand function.

}
Example 12 - c graphics programming

C programming code using rand


We use modulus operator in our program. If you evaluate

#include <graphics.h>
#include <conio.h>

a % b where a and b are integers then result will always

main()
{
int gd = DETECT, gm;

example

be less than b for any set of values of a and b. For


For a = 1243 and b = 100
a % b = 1243 % 100 = 43

initgraph(&gd, &gm,"C:\\TC\\BGI");

For a = 99 and b = 100

outtextxy(10,20, "Graphics source code example.");

a % b = 99 % 100 = 99

circle(200, 200, 50);

For a = 1000 and b = 100


a % b = 1000 % 100 = 0

setcolor(BLUE);
line(350, 250, 450, 50);

In our program we print pseudo random numbers in range


[0, 100]. So we calculate rand() % 100 which will return a

getch();
closegraph( );
return 0;
}
C program for palindrome

number in [0, 99] so we add 1 to get the desired range.


#include <stdio.h>
#include <stdlib.h>
int main() {

int c, n;

printf("Ten random numbers in [1,100]\n");

C programming code (Works in Turbo C only)


#include <stdio.h>
#include <conio.h>
#include <dos.h>

for (c = 1; c <= 10; c++) {


n = rand() % 100 + 1;
printf("%d\n", n);
}
return 0;
}

int main()
{
struct date d;
getdate(&d);

If you rerun this program you will get same set of


numbers. To get different numbers every time you can
use: srand(unisgned int seed) function, here seed is an
unsigned integer. So you will need a different value of
seed every time you run the program for that you can use

printf("Current system date is %d/%d/


%d",d.da_day,d.da_mon,d.da_year);
getch();
return 0;
}

current time which will always be different so you will

This code works in Turbo C only because it supports

get a different set of numbers. By default seed = 1 if you

dos.h header file.

do not use srand function.


This c program prints ip (internet protocol) address of
C programming code using random function(Turbo C
compiler only)
randomize function is used to initialize random number
generator. If you don't use it then you will get same
random numbers each time you run the program.

your computer, system function is used to execute the


command ipconfig which prints ip address, subnet mask
and default gateway. The code given below works for
Windows xp and Windows 7. If you are using turbo c
compiler then execute program from folder, it may not

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

work when you are working in compiler and press

int main()
{
int n, max, num, c;

C programming code
#include<stdlib.h>

printf("Enter the number of random numbers you


want\n");
scanf("%d", &n);

Ctrl+F9 to run your program.

int main()
{
system("C:\\Windows\\System32\\ipconfig");
return 0;

printf("Enter the maximum value of random


number\n");
scanf("%d", &max);

printf("%d random numbers from 0 to %d are :-\n", n,


max);

array elements. For example if a is an array of integers

randomize();
for (c = 1; c <= n; c++)
{
num = random(max);
printf("%d\n",num);
}
getch();
return 0;

C program to reverse an array: This program reverses the


with three elements such that
a[0] = 1
a[1] = 2
a[2] = 3
Then on reversing the array will be
a[0] = 3
a[1] = 2
a[0] = 1

Given below is the c code to reverse an array.

Output of program:

C programming code
#include <stdio.h>
int main()
{
int n, c, d, a[100], b[100];
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for (c = 0; c < n ; c++)
scanf("%d", &a[c]);
/*
* Copying elements into array b starting from end of
array a
*/
for (c = n - 1, d = 0; c >= 0; c--, d++)
b[d] = a[c];
/*
* Copying reversed array into original.
* Here we are modifying original array, this is
optional.
*/

Reverse array by swapping (without using


additional memory)
#include <stdio.h>
int main() {
int array[100], n, c, t, end;
scanf("%d", &n);
end = n - 1;
for (c = 0; c < n; c++) {
scanf("%d", &array[c]);
}

for (c = 0; c < n; c++)


a[c] = b[c];

for (c = 0; c < n/2; c++) {


t
= array[c];
array[c] = array[end];
array[end] = t;

printf("Reverse array is\n");


for (c = 0; c < n; c++)
printf("%d\n", a[c]);

end--;

return 0;

printf("Reversed array elements are:\n");


Download Reverse array program.
for (c = 0; c < n; c++) {
printf("%d\n", array[c]);
}
return 0;
}
C program to reverse an array using pointers
#include <stdio.h>
#include <stdlib.h>
void reverse_array(int*, int);
int main()

{
int n, c, *pointer;

and a[3] = 3. Array insertion does not mean increasing its


size i.e array will not be containing 11 elements.

scanf("%d",&n);
pointer = (int*)malloc(sizeof(int)*n);
if( pointer == NULL )
exit(EXIT_FAILURE);
for ( c = 0 ; c < n ; c++ )
scanf("%d",(pointer+c));

C programming code
#include <stdio.h>
int main()
{
int array[100], position, c, n, value;
printf("Enter number of elements in array\n");
scanf("%d", &n);

reverse_array(pointer, n);

printf("Enter %d elements\n", n);

printf("Original array on reversal is\n");

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

for ( c = 0 ; c < n ; c++ )


printf("%d\n",*(pointer+c));
free(pointer);
return 0;

printf("Enter the location where you wish to insert an


element\n");
scanf("%d", &position);

printf("Enter the value to insert\n");


scanf("%d", &value);

void reverse_array(int *pointer, int n)


{
int *s, c, d;

for (c = n - 1; c >= position - 1; c--)


array[c+1] = array[c];

s = (int*)malloc(sizeof(int)*n);

array[position-1] = value;

if( s == NULL )
exit(EXIT_FAILURE);

printf("Resultant array is\n");


for (c = 0; c <= n; c++)
printf("%d\n", array[c]);

for ( c = n - 1, d = 0 ; c >= 0 ; c--, d++ )


*(s+d) = *(pointer+c);

return 0;

for ( c = 0 ; c < n ; c++ )


*(pointer+c) = *(s+c);

free(s);

C program to merge two arrays into third array: Arrays

}
Array is passed to function and a new array is created and
contents of passed array (in reverse order) are copied into
it and finally contents of new array are copied into array
passed to function.
This code will insert an element into an array, For
example consider an array a[10] having three elements in
it initially and a[0] = 1, a[1] = 2 and a[2] = 3 and you
want to insert a number 45 at location 1 i.e. a[0] = 45, so
we have to move elements one step below so after
insertion a[1] = 1 which was a[0] initially, and a[2] = 2

are assumed to be sorted inascending order. You enter


two short sorted arrays and combine them to get a large
array.
C programming code to merge two sorted
arrays
#include <stdio.h>
void merge(int [], int, int [], int, int []);
int main() {
int a[100], b[100], m, n, c, sorted[200];
printf("Input number of elements in first array\n");
scanf("%d", &m);
printf("Input %d integers\n", m);

for (c = 0; c < m; c++) {


scanf("%d", &a[c]);
}

Output of program:

printf("Input number of elements in second array\n");


scanf("%d", &n);
printf("Input %d integers\n", n);
for (c = 0; c < n; c++) {
scanf("%d", &b[c]);
}
merge(a, m, b, n, sorted);
printf("Sorted array:\n");
for (c = 0; c < m + n; c++) {
printf("%d\n", sorted[c]);
}
return 0;
}
void merge(int a[], int m, int b[], int n, int sorted[]) {
int i, j, k;
j = k = 0;
for (i = 0; i < m + n;) {
if (j < m && k < n) {
if (a[j] < b[k]) {
sorted[i] = a[j];
j++;
}
else {
sorted[i] = b[k];
k++;
}
i++;
}
else if (j == m) {
for (; i < m + n;) {
sorted[i] = b[k];
k++;
i++;
}
}
else {
for (; i < m + n;) {
sorted[i] = a[j];
j++;
i++;
}
}
}

If the arrays are not sorted then you can sort them first
and then use the above merge function, another method is
to merge them and then sort the array. Sorting two smaller
arrays will take less time as compared to sorting a big
array. Merging two sorted array is used in merge sort
algorithm.
C program for bubble sort: c programming code for
bubble sort to sort numbers or arrange them in ascending
order. You can easily modify it to print numbers in
descending order.
Bubble sort algorithm in c
/* Bubble sort code */
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);

printf("Enter %d integers\n", n);

Download Merge arrays program.

for (c = 0; c < n; c++)


scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)

{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use
< */
{
swap
= array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);

for (c = 0; c < n; c++)


scanf("%ld", &array[c]);
bubble_sort(array, n);
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%ld\n", array[c]);
return 0;
}
void bubble_sort(long list[], long n)
{
long c, d, t;
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (list[d] > list[d+1])
{
/* Swapping */

return 0;
}
Download Bubble sort program.
Output of program:

t
= list[d];
list[d] = list[d+1];
list[d+1] = t;
}
}
}
}
You can also sort strings using Bubble sort, it is less
efficient as its average and worst case complexity is high,
there are many other fast sorting algorithms.
Insertion sort in c: c program for insertion sort to sort
numbers. This code implements insertion sort algorithm
to arrange numbers of an array in ascending order. With a
little modification it will arrange numbers in descending

Bubble sort in c language using function


#include <stdio.h>
void bubble_sort(long [], long);
int main()
{
long array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%ld", &n);
printf("Enter %ld integers\n", n);

order.
Insertion sort algorithm implementation in c
/* insertion sort ascending order */
#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);

printf("Enter %d integers\n", n);

#include <stdio.h>

for (c = 0; c < n; c++) {


scanf("%d", &array[c]);
}

int main()
{
int array[100], n, c, d, position, swap;

for (c = 1 ; c <= n - 1; c++) {


d = c;

printf("Enter number of elements\n");


scanf("%d", &n);

while ( d > 0 && array[d] < array[d-1]) {


t
= array[d];
array[d] = array[d-1];
array[d-1] = t;

printf("Enter %d integers\n", n);


for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);

d--;

for ( c = 0 ; c < ( n - 1 ) ; c++ )


{
position = c;

}
}
printf("Sorted list in ascending order:\n");

for ( d = c + 1 ; d < n ; d++ )


{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}

for (c = 0; c <= n - 1; c++) {


printf("%d\n", array[c]);
}
return 0;
}
Download Insertion sort program.
}
Output of program:

printf("Sorted list in ascending order:\n");


for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}
Download Selection sort program.

Selection sort in c: c program for selection sort to sort


numbers. This code implements selection sort algorithm
to arrange numbers of an array in ascending order. With a
little modification it will arrange numbers in descending
order.
Selection sort algorithm implementation in c

Output of program:

int m, n, c, d, first[10][10], second[10][10], sum[10]


[10];
printf("Enter the number of rows and columns of
matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
scanf("%d", &second[c][d]);
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d];
printf("Sum of entered matrices:-\n");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
printf("%d\t", sum[c][d]);
printf("\n");

This c program add two matrices i.e. compute the sum of

two matrices and then print it. Firstly user will be asked to
enter the order of matrix ( number of rows and columns )

return 0;
}

and then two matrices. For example if the user entered


order as 2, 2 i.e. two rows and two columns and matrices

Download Add Matrix program.

as
First Matrix :-

Output of program:

12
34
Second matrix :45
-1 5
then output of the program ( sum of First and Second
matrix ) will be
57
29
C programming code
#include <stdio.h>

C code to subtract matrices of any order. This program

int main()
{

finds difference between corresponding elements of two


matrices and then print the resultant matrix.

C programming code

Output of program:

#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10],
difference[10][10];
printf("Enter the number of rows and columns of
matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");

This c program prints transpose of a matrix. It is obtained

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
scanf("%d", &second[c][d]);

by interchanging rows and columns of a matrix. For

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
difference[c][d] = first[c][d] - second[c][d];

34

printf("difference of entered matrices:-\n");


for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
printf("%d\t",difference[c][d]);
printf("\n");
}
return 0;
}
Download Subtract matrices program.

example if a matrix is
12
56
then transpose of above matrix will be
135
246
When we transpose a matrix then the order of matrix
changes, but for a square matrix order remains same.
C programming code
#include <stdio.h>
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
printf("Enter the number of rows and columns of matrix
");
scanf("%d%d",&m,&n);
printf("Enter the elements of matrix \n");
for( c = 0 ; c < m ; c++ )
{
for( d = 0 ; d < n ; d++ )
{
scanf("%d",&matrix[c][d]);
}
}
for( c = 0 ; c < m ; c++ )
{
for( d = 0 ; d < n ; d++ )
{

transpose[d][c] = matrix[c][d];
}
}

printf("Enter the number of rows and columns of first


matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");

printf("Transpose of entered matrix :-\n");


for( c = 0 ; c < n ; c++ )
{
for( d = 0 ; d < m ; d++ )
{
printf("%d\t",transpose[c][d]);
}
printf("\n");
}
return 0;
}
Download Transpose Matrix program.

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
scanf("%d", &first[c][d]);
printf("Enter the number of rows and columns of second
matrix\n");
scanf("%d%d", &p, &q);
if ( n != p )
printf("Matrices with entered orders can't be multiplied
with each other.\n");
else
{
printf("Enter the elements of second matrix\n");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
scanf("%d", &second[c][d]);

Output of program:

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
Matrix multiplication in c language: c program to

printf("Product of entered matrices:-\n");

multiply matrices (two dimensional array), this program

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < q ; d++ )
printf("%d\t", multiply[c][d]);

multiplies two matrices which will be entered by the user.


Firstly user will enter the order of a matrix. If the entered
orders of two matrix is such that they can't be multiplied

printf("\n");

then an error message is displayed on the screen. You

have already studied the logic to multiply them in

Mathematics.

return 0;

Matrix multiplication in c language

#include <stdio.h>

Download Matrix multiplication program.

int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];

char array[100];

A 3 X 3 matrix multiply in c is shown as example below.

printf("Enter a string\n");
scanf("%s", array);
printf("You entered the string %s\n",array);
return 0;
}
Input string containing spaces
#include <stdio.h>
int main()
{
char a[80];
gets(a);
printf("%s\n", a);
return 0;
}
Matrices are frequently used while doing programming

Note that scanf can only input single word strings, to

and are used to represent graph data structure, in solving

receive strings containing spaces use gets function.

system of linear equations and many more. Lot of


research is being done on how to multiply matrices using

This program prints length of string, for example consider

minimum number of operations. You can also implement

the string "c programming" it's length is 13. Null

it using pointers.

character is not counted when calculating string length. To


find string length we use strlen function of string.h.

This program print a string. String can be printed by using


various functions such as printf, puts.
C programming code
#include <stdio.h>
int main()
{
char array[20] = "Hello World";

C program to find string length


#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int length;

printf("%s\n",array);

printf("Enter a string to calculate it's length\n");


gets(a);

return 0;

length = strlen(a);

printf("Length of entered string is = %d\n",length);


To input a string we use scanf function.
C programming code
#include <stdio.h>
int main()
{

return 0;
}
Download String length program.

Output of program:

C program to compare two strings using


strcmp
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
printf("Enter the first string\n");
gets(a);

You can also find string length using pointer or without


strlen function. Following program shows how to achieve

printf("Enter the second string\n");


gets(b);

this.
C program to find string length without strlen

if( strcmp(a,b) == 0 )
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");

C program to find length of a string using pointers.


#include <stdio.h>
int main()
{
char array[100], *pointer;
int length = 0;
printf("Enter a string\n");
gets(array);

return 0;
}
Download Compare Strings program.
Output of program:

pointer = array;
while(*(pointer+length))
length++;
printf("Length of entered string = %d\n",length);
return 0;
}
Function to find string length
int string_length(char *s)
{
int c = 0;
while(*(s+c))
c++;

C program to compare two strings without


using strcmp
Here we create our own function to compare strings.
int compare(char a[], char b[])
{
int c = 0;
while( a[c] == b[c] )
{
if( a[c] == '\0' || b[c] == '\0' )
break;
c++;
}
if( a[c] == '\0' && b[c] == '\0' )
return 0;
else
return -1;

return c;
}
This c program compares two strings
using strcmp, without strcmp and using pointers. For
comparing strings without using library function see
another code below.
}

C program to compare two strings using


pointers

char destination[50];

In this method we will make our own function to perform

printf("Source string: %s\n", source);


printf("Destination string: %s\n", destination);

strcpy(destination, source);

string comparison, we will use character pointers in our


function to manipulate string.

return 0;
}

#include<stdio.h>
int compare_string(char*, char*);
int main()
{
char first[100], second[100], result;

c program to copy a string using pointers


: here we copy string without using strcmp by creating our
own function which uses pointers.
#include<stdio.h>

printf("Enter first string\n");


gets(first);

void copy_string(char*, char*);

printf("Enter second string\n");


gets(second);

main()
{
char source[100], target[100];

result = compare_string(first, second);

printf("Enter source string\n");


gets(source);

if ( result == 0 )
printf("Both strings are same.\n");
else
printf("Entered strings are not equal.\n");

copy_string(target, source);
printf("Target string is \"%s\"\n", target);

return 0;

return 0;

int compare_string(char *first, char *second)


{
while(*first==*second)
{
if ( *first == '\0' || *second == '\0' )
break;

void copy_string(char *target, char *source)


{
while(*source)
{
*target = *source;
source++;
target++;
}
*target = '\0';
}

first++;
second++;
}
if( *first == '\0' && *second == '\0' )
return 0;
else
return -1;
}
This program copy string using library function strcpy, to
copy string without using strcpy see source code below in
which we have made our own function to copy string.

Anagram in c: c program to check whether two strings are


anagrams or not, string is assumed to consist of alphabets
only. Two words are said to be anagrams of each other if
the letters from one word can be rearranged to form the
other word. From the above definition it is clear that two
strings are anagrams if all characters in both strings occur

C program to copy a string


#include<stdio.h>
#include<string.h>

same number of times. For example "abc" and "cab" are

main()
{
char source[] = "C program";

how many times characters appear in the strings and then

anagram strings, here every character 'a', 'b' and 'c' occur
only one time in both strings. Our algorithm tries to find
comparing their corresponding counts.

C anagram programming code

Output of program:

#include <stdio.h>
int check_anagram(char [], char []);
int main()
{
char a[100], b[100];
int flag;
printf("Enter first string\n");
gets(a);
printf("Enter second string\n");
gets(b);
flag = check_anagram(a, b);

This program reverses a string entered by the user. For


example if a user enters a string "reverse me" then on
reversing the string will be "em esrever". We show you
four different methods to reverse string the first one uses
strrev library function of string.h header file, second

if (flag == 1)
printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
else
printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);

without using strrev and in third we make our own

return 0;

using first method then you must include string.h in your

function to reverse string using pointers, reverse string


using recursion and Reverse words in string. If you are
program.

int check_anagram(char a[], char b[])


{
int first[26] = {0}, second[26] = {0}, c = 0;
while (a[c] != '\0')
{
first[a[c]-'a']++;
c++;
}
c = 0;

C programming code
/* String reverse in c*/
#include <stdio.h>
#include <string.h>
int main()
{
char arr[100];

while (b[c] != '\0')


{
second[b[c]-'a']++;
c++;
}
for (c = 0; c < 26; c++)
{
if (first[c] != second[c])
return 0;
}
return 1;
}
Download Anagram program.

printf("Enter a string to reverse\n");


gets(arr);
strrev(arr);
printf("Reverse of entered string is \n%s\n",arr);
return 0;
}
Download Reverse string program.

Output of program:

main()
{
char string[100];
printf("Enter a string\n");
gets(string);
reverse(string);
printf("Reverse of entered string is \"%s\".\n", string);
return 0;

C program to reverse string without using


function

Below code does not uses strrev library function to

void reverse(char *string)


{
int length, c;
char *begin, *end, temp;

reverse a string. First we calculate the length of string


using strlen function and then assigns characters of input

length = string_length(string);
begin = string;
end = string;

string in reverse order to create a new string using a for


loop. You can also calculate length of string without using
strlen. We use comma operator in for loop to initialize

for (c = 0; c < length - 1; c++)


end++;

multiple variables and increment/decrement variables.

for (c = 0; c < length/2; c++)


{
temp = *end;
*end = *begin;
*begin = temp;

#include <stdio.h>
#include <string.h>
int main()
{
char s[100], r[100];
int n, c, d;
printf("Input a string\n");
gets(s);
n = strlen(s);
for (c = n - 1, d = 0; c >= 0; c--, d++)
r[d] = s[c];

begin++;
end--;
}
}
int string_length(char *pointer)
{
int c = 0;
while( *(pointer + c) != '\0' )
c++;

r[d] = '\0';
printf("%s\n", r);

return c;
}

return 0;
}

C program to reverse a string using recursion

C program to reverse a string using pointers

#include <stdio.h>
#include <string.h>

Now we will invert string using pointers or without using

void reverse(char*, int, int);

library function strrev.


#include<stdio.h>
int string_length(char*);
void reverse(char*);

int main()
{
char a[100];
gets(a);

reverse(a, 0, strlen(a)-1);

Download String Concatenation program.

printf("%s\n",a);
return 0;

Output of program:

}
void reverse(char *x, int begin, int end)
{
char c;
if (begin >= end)
return;
c
= *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
reverse(x, ++begin, --end);
}

Concatenate strings without strcat function


C program to concatenate strings without using library
function strcat of header file string.h.

In recursion method we swap characters at the begin and


at the end and then move towards the middle of the string.
This method is inefficient due to repeated function calls
but useful in practicing recursion.

#include <stdio.h>
int main()
{
char p[100], q[100];
int c, d;
printf("Input a string\n");
gets(p);

This program concatenates strings, for example if the first


string is "c " and second string is "program" then on

printf("Input a string to concatenate\n");


gets(q);

concatenating these two strings we get the string "c


program". To concatenate two strings we use strcat
function of string.h, to concatenate without using library

c = 0;

function see another code below which uses pointers.

while (p[c] != '\0') {


c++;
}

C programming code

d = 0;

#include <stdio.h>
#include <string.h>

while (q[d] != '\0') {


p[c] = q[d];
d++;
c++;
}

int main()
{
char a[100], b[100];
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b);
strcat(a,b);
printf("String obtained on concatenation is %s\n",a);

p[c] = '\0';
printf("String obtained on concatenation is \"%s\"\n",
p);
return 0;
}
String concatenation using pointers

return 0;
}

#include <stdio.h>

void concatenate_string(char*, char*);


printf("Enter a string to reverse\n");
gets(arr);

int main()
{
char original[100], add[100];

strrev(arr);

printf("Enter source string\n");


gets(original);

printf("Reverse of entered string is \n%s\n",arr);


return 0;

printf("Enter string to concatenate\n");


gets(add);

concatenate_string(original, add);

Download Reverse string program.

printf("String after concatenation is \"%s\"\n",


original);

Output of program:

return 0;
}
void concatenate_string(char *original, char *add)
{
while(*original)
original++;
while(*add)
{
*original = *add;
add++;
original++;
}
*original = '\0';
}

C program to reverse string without using


function
Below code does not uses strrev library function to
reverse a string. First we calculate the length of string
using strlen function and then assigns characters of input
string in reverse order to create a new string using a for

This program reverses a string entered by the user. For

loop. You can also calculate length of string without using

example if a user enters a string "reverse me" then on

strlen. We use comma operator in for loop to initialize

reversing the string will be "em esrever". We show you

multiple variables and increment/decrement variables.

four different methods to reverse string the first one uses


strrev library function of string.h header file, second

#include <stdio.h>
#include <string.h>

without using strrev and in third we make our own


function to reverse string using pointers, reverse string
using recursion and Reverse words in string. If you are
using first method then you must include string.h in your
program.
C programming code
/* String reverse in c*/
#include <stdio.h>
#include <string.h>
int main()
{
char arr[100];

int main()
{
char s[100], r[100];
int n, c, d;
printf("Input a string\n");
gets(s);
n = strlen(s);
for (c = n - 1, d = 0; c >= 0; c--, d++)
r[d] = s[c];
r[d] = '\0';
printf("%s\n", r);
return 0;

C program to reverse a string using recursion

C program to reverse a string using pointers

#include <stdio.h>
#include <string.h>

Now we will invert string using pointers or without using

void reverse(char*, int, int);

library function strrev.


#include<stdio.h>

int main()
{
char a[100];

int string_length(char*);
void reverse(char*);

gets(a);
reverse(a, 0, strlen(a)-1);

main()
{
char string[100];
printf("Enter a string\n");
gets(string);
reverse(string);
printf("Reverse of entered string is \"%s\".\n", string);

printf("%s\n",a);
return 0;
}
void reverse(char *x, int begin, int end)
{
char c;
if (begin >= end)
return;

return 0;
}

c
= *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;

void reverse(char *string)


{
int length, c;
char *begin, *end, temp;
length = string_length(string);
begin = string;
end = string;
for (c = 0; c < length - 1; c++)
end++;

at the end and then move towards the middle of the string.

for (c = 0; c < length/2; c++)


{
temp = *end;
*end = *begin;
*begin = temp;

but useful in practicing recursion.

begin++;
end--;
}
}
int string_length(char *pointer)
{
int c = 0;
while( *(pointer + c) != '\0' )
c++;
return c;
}

reverse(x, ++begin, --end);


}
In recursion method we swap characters at the begin and
This method is inefficient due to repeated function calls

This program delete an element from an array. Deleting


an element does not affect the size of array. It is also
checked whether deletion is possible or not, For example
if array is containing five elements and you want to delete
element at position six which is not possible.
C programming code
#include <stdio.h>
int main()
{
int array[100], position, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);

printf("Enter %d elements\n", n);


for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
printf("Enter the location where you wish to delete
element\n");
scanf("%d", &position);
if ( position >= n+1 )
printf("Deletion not possible.\n");
else
{
for ( c = position - 1 ; c < n - 1 ; c++ )
array[c] = array[c+1];
printf("Resultant array is\n");
for( c = 0 ; c < n - 1 ; c++ )
printf("%d\n", array[c]);
}

various options while executing shutdown.exe, you can


use -t option to specify number of seconds after which
shutdown occurs.
Syntax: shutdown -s -t x; here x is the number of seconds
after which shutdown will occur.
By default shutdown occur after 30 seconds. To shutdown
immediately you can write "shutdown -s -t 0". If you wish
to restart your computer then you can write "shutdown
-r".
If you are using Turbo C Compiler then execute your
program from command prompt or by opening the
executable file from the folder. Press F9 to build your
executable file from source program. When you run
program from within the compiler by pressing Ctrl+F9 it

return 0;
}
Download Delete element from array program.
Output of program:

may not work.


C programming code for Windows XP
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Do you want to shutdown your computer now
(y/n)\n");
scanf("%c", &ch);
if (ch == 'y' || ch == 'Y')
system("C:\\WINDOWS\\System32\\shutdown -s");
return 0;
}
C programming code for Windows 7
#include <stdio.h>
#include <stdlib.h>

C Program to shutdown your computer: This program


turn off i.e shutdown your computer system. Firstly it will
asks you to shutdown your computer if you press 'y' then

int main()
{
system("C:\\WINDOWS\\System32\\shutdown /s");
return 0;
}

your computer will shutdown in 30 seconds, system

To shutdown immediately use

function of "stdlib.h" is used to run an executable file

"C:\\WINDOWS\\System32\\ shutdown /s /t 0". To restart

shutdown.exe which is present in

use /r instead of /s.

C:\WINDOWS\system32 in Windows XP. You can use

C programming code for Ubuntu Linux

#include <stdio.h>
int main() {
system("shutdown -P now");
return 0;
}

We build binary numbers the same way we build numbers


in our traditional base 10 system. However, instead of a
one's column, a 10's column, a 100's column (and so on)
we have a one's column, a two's columns, a four's column,
an eight's column, and so on, as illustrated below.

You need to be logged in as root user for above program

Table 2.1. Binary

to execute otherwise you will get the message shutdown:


Need to be root, now specifies that you want to shutdown
immediately. '-P' option specifies you want to power off
your machine. You can specify minutes as:

2...

26

25

24

23

22

21

20

...

64

32

16

shutdown -P "number of minutes"


For more help or options type at terminal: man shutdown.

For example, to represent the number 203 in base 10, we


know we place a 3 in the 1's column, a 0 in
the10's column and a 2 in the 100's column. This is
expressed with exponents in the table below.
Table 2.2. 203 in base 10

Chapter 2. Binary and Number Representation


Table of Contents

102

101

100

Binary -- the basis of computing


o

Binary Theory

Hexadecimal

Practical Implications

Types and Number Representation


o

C Standards

Types

Number Representation

Binary -- the basis of computing


Binary Theory
Introduction
Binary is a number system which builds numbers from
elements called bits. Each bit can be represented by any
two mutually exclusive states. Generally, when we write it
down or code bits, we represent them with 1 and 0. We
also talk about them being true and false, and the
computer internally represents bits with high and low
voltages.

Or, in other words, 2 102 + 3 100 = 200 + 3 = 203. To


represent the same thing in binary, we would have the
following table.
Table 2.3. 203 in base 2
27

26

25

24

23

22

21

20

That equates to 27 + 26 + 23+21 + 20 = 128 + 64 + 8 + 2 + 1


= 203.
Conversion
The easiest way to convert between bases is to use a
computer, after all, that's what they're good at! However,
it is often useful to know how to do conversions by hand.
The easiest method to convert between bases is repeated
division. To convert, repeatedly divide the quotient by the
base, until the quotient is zero, making note of the
remainders at each step. Then, write the remainders in
reverse, starting at the bottom and appending to the right

each time. An example should illustrate; since we are


converting to binary we use a base of 2.

represents A, so when value 10 is sent to the video card it


displays a capital 'A' on the screen.

Table 2.4. Convert 203 to binary

To avoid this happening, the American Standard Code for


Information Interchange or ASCII was invented. This is
a 7-bit code, meaning there are 27 or 128 available codes.

Quotient

Remainder

20310 2 =

101

10110 2 =

50

5010 2 =

25

2510 2 =

12

1210 2 =

610 2 =

310 2 =

110 2 =

Reading from the bottom and appending to the right each


time gives 11001011, which we saw from the previous
example was 203.
Bits and Bytes
To represent all the letters of the alphabet we would need
at least enough different combinations to represent all the
lower case letters, the upper case letters, numbers and
punctuation, plus a few extras. Adding this up means we
need probably around 80 different combinations.
If we have two bits, we can represent four possible unique
combinations (00 01 10 11). If we have three bits, we can
represent 8 different combinations. As we saw above,
with n bits we can represent 2n unique combinations.
8 bits gives us 28 = 256 unique representations, more than
enough for our alphabet combinations. We call a group of
8 bits a byte. Guess how bit a C char variable is? One
byte.
ASCII
Given that a byte can represent any of the values 0
through 256, anyone could arbitrarily make up a mapping
between characters and numbers. For example, a video
card manufacturer could decide that the value 10

The range of codes is divided up into two major parts; the


non-printable and the printable. Printable characters are
things like characters (upper and lower case), numbers
and punctuation. Non-printable codes are for control, and
do things like make a carriage-return, ring the terminal
bell or the special NULLcode which represents nothing at
all.
127 unique characters is sufficient for American English,
but becomes very restrictive when one wants to represent
characters common in other languages, especially Asian
languages which can have many thousands of unique
characters.
To alleviate this, modern systems are moving away from
ASCII to Unicode, which can use up to 4 bytes to
represent a character, giving much more room!
Parity
ASCII, being only a 7-bit code, leaves one bit of the byte
spare. This can be used to implement paritywhich is a
simple form of error checking. Consider a computer using
punch-cards for input, where a hole represents 1 and no
hole represents 0. Any inadvertent covering of a hole will
cause an incorrect value to be read, causing undefined
behaviour.
Parity allows a simple check of the bits of a byte to ensure
they were read correctly. We can implement
either odd or even parity by using the extra bit as a parity
bit.
In odd parity, if the number of 1's in the 7 bits of
information is odd, the parity bit is set, otherwise it is not
set. Even parity is the opposite; if the number of 1's is
even the parity bit is set to 1.
In this way, the flipping of one bit will case a parity error,
which can be detected.
XXX more about error correcting
16, 32 and 64 bit computers
Numbers do not fit into bytes; hopefully your bank
balance in dollars will need more range than can fit into
one byte! Most modern architectures are 32

bit computers. This means they work with 4 bytes at a


time when processing and reading or writing to memory.
We refer to 4 bytes as a word; this is analogous to
language where letters (bits) make up words in a sentence,
except in computing every word has the same size! The
size of a C it variable is 32 bits. Newer architectures are
64 bits, which doubles the size the processor works with
(8 bytes).
Kilo, Mega and Giga Bytes
Computers deal with a lot of bytes; that's what makes
them so powerful!
We need a way to talk about large numbers of bytes, and a
natural way is to use the "International System of Units"
(SI) prefixes as used in most other scientific areas. So for
example, kilo refers to 103 or 1000 units, as in a kilogram
has 1000 grams.
1000 is a nice round number in base 10, but in binary it
is 1111101000 which is not a particularly "round" number.
However, 1024 (or 210) is (10000000000), and happens to
be quite close to the base ten meaning of kilo (1000 as
opposed to 1024).
Hence 1024 bytes became known as a kilobyte. The first
mass market computer was the Commodore 64, so named
because it had 64 kilobytes of storage.
Today, kilobytes of memory would be small for a wrist
watch, let alone a personal computer. The next SI unit is
"mega" for 106. As it happens, 220 is again close to the SI
base 10 definition; 1048576 as opposed to 1000000.
The units keep increasing by powers of 10; each time it
diverges further from the base SI meaning.
Table 2.5. Bytes
210

Kilobyte

220

Megabyte

230

Gigabyte

40

Terrabyte

250

Petabyte

260

Exabyte

Therefore a 32 bit computer can address up to four


gigabytes of memory; the extra two bits can represent
four groups of 230 bytes.. A 64 bit computer can address
up to 8 exabytes; you might be interested in working out
just how big a number this is! To get a feel for how bit
that number is, calculate how long it would take to count
to 264 if you incremented once per second.
Kilo, Mega and Giga Bits
Apart from the confusion related to the overloading of SI
units between binary and base 10, capacities will often be
quoted in terms of bits rather than bytes.
Generally this happens when talking about networking or
storage devices; you may have noticed that your ADSL
connection is described as something like 1500
kilobits/second. The calculation is simple; multiply by
1000 (for the kilo), divide by 8 to get bytes and then 1024
to get kilobytes (so 1500 kilobits/s=183 kilobytes per
second).
The SI standardisation body has recognised these dual
uses, and has specified unique prefixes for binary usage.
Under the standard 1024 bytes is a kibibyte, short for kilo
binary byte (shortened to KiB). The other prefixes have a
similar prefix (Mebibyte, for example). Tradition largely
prevents use of these terms, but you may seem them in
some literature.
Boolean Operations
George Boole was a mathematician who discovered a
whole area of mathematics called Boolean Algebra.
Whilst he made his discoveries in the mid 1800's, his
mathematics are the fundamentals of all computer
science. Boolean algebra is a wide ranging topic, we
present here only the bare minimum to get you started.
Boolean operations simply take a particular input and
produce a particular output following a rule. For example,
the simplest boolean operation, not simply inverts the
value of the input operand. Other operands usually take
two inputs, and produce a single output.
The fundamental Boolean operations used in computer
science are easy to remember and listed below. We
represent them below with truth tables; they simply show
all possible inputs and outputs. The termtrue simply
reflects 1 in binary.

Not
Usually represented by !, not simply inverts the value,
so 0 becomes 1 and 1 becomes 0
Table 2.6. Truth table for not
Input

Output

Table 2.9. Truth table for xor


Input 1

And
To remember how the and operation works think of it as
"if one input and the other are true, result is true
Table 2.7. Truth table for and
Input 1
0

Input 2
0

Input 2

Output

Output
0

How computers use boolean operations


Believe it or not, essentially everything your computer
does comes back to the above operations. For example,
the half adder is a type of circuit made up from boolean
operations that can add bits together (it is called a half
adder because it does not handle carry bits). Put more half
adders together, and you will start to build something that
can add together long binary numbers. Add some external
memory, and you have a computer.

Or
To remember how the or operation works think of it as "if
one input or the other input is true, the result is true
Table 2.8. Truth table for or
Input 1

Exclusive Or (xor)
Exclusive or, written as xor is a special case of or where
the output is true if one, and only one, of the inputs is true.
This operation can surprisingly do many interesting tricks,
but you will not see a lot of it in the kernel.

Input 2

Output

Electronically, the boolean operations are implemented


in gates made by transistors. This is why you might have
heard about transistor counts and things like Moores Law.
The more transistors, the more gates, the more things you
can add together. To create the modern computer, there
are an awful lot of gates, and an awful lot of transistors.
Some of the latest Itanium processors have around 460
million transistors.

Working with binary in C


In C we have a direct interface to all of the above
operations. The following table describes the operators

Table 2.10. Boolean operations in C

Operation

Usage in C

Hexadecimal

Binary

Decimal

not

0000

and

&

0001

or

0010

xor

0011

0100

0101

0110

0111

1000

1001

1010

10

1011

11

1100

12

1101

13

1110

14

1111

15

We use these operations on variables to modify the bits


within the variable. Before we see examples of this, first
we must divert to describe hexadecimal notation.
Hexadecimal
Hexadecimal refers to a base 16 number system. We use
this in computer science for only one reason, it makes it
easy for humans to think about binary numbers.
Computers only ever deal in binary and hexadecimal is
simply a shortcut for us humans trying to work with the
computer.
So why base 16? Well, the most natural choice is base 10,
since we are used to thinking in base 10 from our every
day number system. But base 10 does not work well with
binary -- to represent 10 different elements in binary, we
need four bits. Four bits, however, gives us sixteen
possible combinations. So we can either take the very
tricky road of trying to convert between base 10 and
binary, or take the easy road and make up a base 16
number system -- hexadecimal!
Hexadecimal uses the standard base 10 numerals, but
adds A B C D E F which refer to 10 11 12 13 14 15(n.b.
we start from zero).
Traditionally, any time you see a number prefixed
by 0x this will denote a hexadecimal number.
As mentioned, to represent 16 different patterns in binary,
we would need exactly four bits. Therefore, each
hexadecimal numeral represents exactly four bits. You
should consider it an exercise to learn the following table
off by heart.
Table 2.11. Hexadecimal, Binary and Decimal

Of course there is no reason not to continue the pattern


(say, assign G to the value 16), but 16 values is an
excellent trade off between the vagaries of human
memory and the number of bits used by a computer
(occasionally you will also see base 8 used, for example
for file permissions under UNIX). We simply represent
larger numbers of bits with more numerals. For example,
a sixteen bit variable can be represented by 0xAB12, and
to find it in binary simply take each individual numeral,
convert it as per the table and join them all together
(so 0xAB12 ends up as the 16-bit binary
number 1010101100010010). We can use the reverse to
convert from binary back to hexadecimal.

We can also use the same repeated division scheme to


change the base of a number. For example, to find 203 in
hexadecimal
Table 2.12. Convert 203 to hexadecimal
Quotient

Remainder

20310 16 =

12

11 (0xB)

1210 16 =

12 (0xC)

Hence 203 in hexadecimal is 0xCB.


Practical Implications
Use of binary in code
Whilst binary is the underlying language of every
computer, it is entirely practical to program a computer in
high level languages without knowing the first thing about
it. However, for the low level code we are interested in a
few fundamental binary principles are used repeatedly.
Masking and Flags
Masking
In low level code, it is often important to keep your
structures and variables as space efficient as possible. In
some cases, this can involve effectively packing two
(generally related) variables into one.
Remember each bit represents two states, so if we know a
variable only has, say, 16 possible states it can be
represented by 4 bits (i.e. 24=16 unique values). But the
smallest type we can declare in C is 8 bits (achar), so we
can either waste four bits, or find some way to use those
left over bits.
We can easily do this by the process of masking.
Remembering the rules of the logical operations, it should
become clear how the values are extracted.
The process is illustrated in the figure below. We are
interested in the lower four bits, so set our mask to have
these bits set to 1. Since the logical and operation will
only set the bit if both bits are 1, those bits of the mask set
to 0 effectively hide the bits we are not interested in.
Figure 2.1. Masking

To get the top (blue) four bits, we would invert the mask.
You will note this gives a result of 0x90 when really we
want a value of 0x09. To get the bits into the right
position we use the right shift operation.
Setting the bits requires the logical or operation. However,
rather than using 1's as the mask, we use 0's. You should
draw a diagram similar to the above figure and work
through setting bits with the logical oroperation.
Flags
Often a program will have a large number of variables
that only exist as flags to some condition. For example, a
state machine is an algorithm that transitions through a
number of different states but may only be in one at a
time. Say it has 8 different states; we could easily declare
8 different variables, one for each state. But in many cases
it is better to declare one 8 bit variable and assign each bit
to flag flag a particular state.
Flags are a special case of masking, but each bit
represents a particular boolean state (on or off). An n bit
variable can hold n different flags. See the code example
below for a typical example of using flags -- you will see
variations on this basic code very often.
Example 2.1. Using flags
1
#include <stdio.h>

// define all 8 possible flags for an 8 bit variable


5 //

name hex

binary

#define FLAG1 0x01 // 00000001

#define FLAG2 0x02 // 00000010

// this will pass as FLAG1 is set

#define FLAG3 0x04 // 00000100

if (flags & (FLAG1|FLAG4))

#define FLAG4 0x08 // 00001000

printf("FLAG1 or FLAG4
set!\n");

10 // ... and so on
35
#define FLAG8 0x80 // 10000000
return 0;
}
int main(int argc, char *argv[])
{
15

char flags = 0; //an 8 bit variable


Hexadecimal Number System

// set flags with a logical or


flags = flags | FLAG1; //set flag 1
flags = flags | FLAG3; //set flag 3

The hexadecimal (base 16) number system operates the


same way as the decimal (base 10) number system, except
it is based on sixteen instead of ten. The operation of the
decimal system is familiar.
The 4-digit base-10 number 5826 appears below,
indicating how the value of the number is derived from
the values of its 4 digits.

20
// check flags with a logical and. If the
flag is set (1)
// then the logical and will return 1,
causing the if
// condition to be true.
if (flags & FLAG1)
25

printf("FLAG1 set!\n");

// this of course will be untrue.


if (flags & FLAG8)
printf("FLAG8 set!\n");
30
// check multiple flags by using a logical
or

Everybody knows that 5826 means five-thousand eighthundred twenty-six. But only because they have been
taught that 1, 10, 100, and 1000 are part of the
calculation even though they are never written. All that is
actually written is a total of twenty-one (5 and 8 and 2 and
6). Only the interpretation that people supply, which is
purely mental and unwritten, informs what is written with
its intended value.
Hexadecimal operates the same way. Each digit is
"weighted" by a "multiplier," with the results all added

together. The multipliers in both systems are the powers


of the system base (10 or 16). The powers of 10 are 1, 10,
100, 1000, etc. while those of 16 are 1, 16, 256, 4096, etc.
So the same digits "5826" used in base 16 represent a
value calculated as follows:

10

11

12

13

14

15

Here's the derivation of the value of another 4-digit


hexadecimal number, but this one uses some of the highorder digits A-F:

Though the digits are the same (5826) the values come
out quite different, because the base and its "multiplier
values" are different.
You will see hexadecimal numbers some of whose digits
are letters instead of numbers. That's because the number
of digits needed by any number system is the number's
base. So base base 2 needs 2 digits, base 10 needs 10, and
base 16 needs 16. Base 2 has 0 and 1. Base 10 has 0
through 9. Base 16 borrows 0 though 9 but needs another
6. For those, we could invent some symbols. However, for
convenience we employ the first 6 letters of the alphabet
(A through F) instead. When we run out of digits at 9, we
use A as the next digit. So A represents the value 10. B
comes next, and represents 11. The hexadecimal digits
and thevalue they stand for are:
Hexadeci Valu
mal digit e
0

The highest you can count with a given number of digits


(in any number system) is the number in which every
digit contains the maximum value in the number system
(1 in base 2, or 9 in base 10, or F in base 16). So the
largest number you can represent with 4 digits in base 16
is:

Counting any higher than that would require that you


utilize more digits. The very next number is 10000 in

hexadecimal, or 65536 in decimal. It is a well-known


value in computer science and is called "64K."

Das könnte Ihnen auch gefallen