সোমবার, ১৮ অক্টোবর, ২০১০

37. Structures

The structure mechanism allows us to aggregate variables of different types
struct definitions are usually placed outside of functions so that they are in scope throughout the file, as in the following example:

The “.” in a.num is the “structure member operator”, which connects the structure name and the member name.
A “member” is a variable in a structure.
Assignment (=) works just as you would expect, as if there were a separate assignment for each structure member.

Structures Simple Example

struct card_struct {
int number;
char suit;
}; /* note the semicolon after the definition! */
void some_function() {
struct card_struct a, b;
a.number = 3;
a.suit = ’D’;
b = a;
}

Structure member as Parameter

void sum(double p1_x,double p1_y,double p2_x,double p2_y ) {
struct point psum;
psum.x = p1_x + p2_x;
psum.y = p1_y + p2_y;
printf(“%lf_%lf\n”, psum.x, psum.y); 10_5
}
void main()
 {
struct point a, b, c;
a.x = 3.5; a.y = 4.5; b.x = 6.5; b.y = 0.5;
printf(“%lf_%lf_%lf_%lf\n”, a.x, a.y, b.x, b.y);
sum( a.x, a.y, b.x, b.y); 3.5_4.5_6.5_0.5
}

Structure as Parameter

Structures work seamlessly with functions.
A structure is a type, so it can be the type of a function parameter (as here), or a return type:
point sum( struct point p1, struct point p2 ) {
struct point psum;
psum.x = p1.x + p2.x;
psum.y = p1.y + p2.y;
return psum;
}
void main() { 3.5_4.5_6.5_0.5_10_5
struct point a, b, c;
a.x = 3.5; a.y = 4.5; b.x = 6.5; b.y = 0.5;
c = sum( a, b);
printf(“%lf_%lf_%lf_%lf_%lf_%lf\n”, a.x, a.y, b.x, b.y, c.x, c.y);
}

Post by j.siam,
Ref-: Md Munirul Haque

36. Strings


When dealing with strings in C, you should always think of the underlying array of characters.
Also: always think in terms of the activation records! You must explicitly allocate all the space for every string you use.


String Example


void main()
{
char s[] = "Hi!"; // initialization with string constant
char s2[] = { 'H' , 'i' , '!' , '\0' };
// initialization with char constant
int i;
for( i = 0; s[i] != 0; i++ )
printf( "%c_%c_", s[i], s2[i] );




}


Output: H_H_i_i_!_!_



String input


Alternative way of taking string input


char str[80];
scanf(“%s”, str);
scanf(“%s”, &str[0]);
gets(str);
for(i=0; i<10;i++)
scanf(“%c”, &str[i]);

String handling functions These are from string.h library. (You have to #include to use these functions).
int strlen( char *s ); Returns the length of the string s.
strlen(“hello”) will return the value 5
char *strcat( char *s1, char *s2 ); Takes two strings as arguments, concatenates them, and puts the result in s1.
The programmer must ensure that s1 points to enough space to hold the result. The string s1 is returned.
strcat(“hello”, “_world”) will return string “hello_world”



char *strcpy( char *s1, char *s2 );
The string s2 is copied into s1.
Whatever exists in s1 is overwritten. It is assumed that s1 has enough space to hold the result. The value of s1 is returned.
strcpy(s1, s2) will return s1 with the new value copied from s2


(Remember, using = to assign one string to another only copies pointers, it doesn’t actually give a new copy of the string. And it won’t work at all if the left hand side is a string array.)


int strcmp( char *s1, char *s2 ); Integer is returned that is less than, equal to, or greater than zero, depending on whether s1 is lexicographically less than, equal to, or greater than s2 (respectively).


strcmp(“he”, “hi”) will return less than 0
strcmp(“12”, “12”) will return 0
strcmp(“they”, “the”) will return greater than 0

Post by j.siam,
Ref-: Md Munirul Haque

35. Introduction to Pointer and Arrays

Pointer and arrays:
1. Array elements are always stored in contiguous memory location.
2. A pointer when incremental always pointer to an immediately next location of its type.
Suppose we have an array,
int mamun[ ]={3,4,5,6};
Suppose the elements are located in memory as
Elements:               3        4           5           6
Memory location: 1000   1002      1004      1005
Here is program that prints out the memory location in which the elements of this array are stored.

main( )
{
   int mamun[ ]={3,4,5,6};
   int i=0,*p;
   p=mamun;   /*Because the array name is a base address of first elemnt of the array. We cam also write it p=mamunb[0]*/
     while (i<=4)
 {
    printf(" \n Address = %u",&mamun[i]);
    printf("\n Element = %d", *p);
    i++;
    p++;
 }
}
output:
address             elements
1000                  3
1002                  4
1004                  5
1006                  6

in this program, to begin with  we have collected the base address of the array(address of 0th  element) in the variable p using the statement,
p=mamun; /*assigns address 1000to p*/.
When we are inside the loop for the first time p contains the address 1000,and the value at this address is 24.
These continue till the last element of the array has bee n printed.

A word of caution! D o not attempt the following operations on pointer ... they would never work out.
1. Addition of two pointers.
2. Multiplying a pointer with a number.
3. Dividing a pointer with a number. 

written by mamun

34. Pointer and Functions

Passing addresses to Functions:

Look at this porgram

#include<stdio.h>
void arnob(int,int)
main( )
{
int a=10,b=20;
arnob(&a,&b);
printf("\na=%d",a);
printf("\nb=%d",b);
}

arnob(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}

The output of the above program would be:
a=20
b=10

  When we send the address of  a and b it come in the function arnob. But we know that the normal variable can not store the address of a variable. So if we want to store the address of a and b we mast declere the pointer type variable. Because we know that only pointer type variable can store the address of a variable. So in the function arnob we declear two pointer x and y to store the address of a and b. And we also declear a normal variable t. Now we put the value of *x in t. Also we know that *x mean 'value at address x' that means  a. And we know a=10. So t=*x mean that t=a i mean t=10. Now *x=*y mean that a=b. So tha valu of a is now 20. *y=t, we know that the valu of t=10. So *y=t mean b=10. Look at this porgram we work in tha fanction arnob. But the value of a and b change in the main function.

post by Arnob

33. Pointer Expressions

Let us now see what are pointers and how they can be used in various expressions. If i=5 then expression &i returns the adderss of i. If we so desire, this address can be collected in avariable by saying,

j=&i;

But remember that j is not an ordinary variable like any other integer variable. It is a variable, which contains the address of another variable. Since j is a variable the compiler ust probide it space in memory. Once again, the following memory map would illustrate the contents of and j.

As you can see, i's value is 5 and j's value is i's address.

But wait, we can't use j in program without declaring it. And since j is a variable, which contains the address of i, it is declared as,

int *j;

This declaration tells the conpiler that j will be used to store the address of an integer value - in other words j points to an integer. How do we justify the usage of  * (pointer).

int *j;

Let us go by the meaning of *. It stand for 'value at address'. Thus, int *j would mean, the value at the address contained in j is an int.

Look at the following declarations,

int *alpha;
char *ch;
float *s;

Here, alpha, ch and s are declared as pointer variables, i.e. variables capable of holding addresses. Remember that, addresses are always going to be whole numbers, therefore pointers always contain whole numbers. The declaration float *s does not mean that s is going to contain a floating-point value. What it means is, s is going to contain the address of a floating-point value. Similarly, char *ch means that ch is going to contain the address of a char value.

Pointer we know is a variable, which contains address of another variable. Now this variable itself could be another pointer. Thus, we now have a pointer, which contains another pointer's address. The following example should make this point clear.

#include<stdio.h>
main( )
{
int i=5;
int *j;
int **k;

j=&i;
k=&j;
printf(" \n Address of i = %u",&i);
printf(" \n Address of i = %u",j);
printf(" \n Address of i = %u",*k);
printf(" \n Address of j = %u",&j);
printf(" \n Address of j = %u",k);
printf(" \n Address of k = %u",&k);

printf("\n\n Value of j = %u",j);
printf("\n Value of k = %u",k);
printf("\n Value of i = %d",i);
printf("\n Value of i = %d",*(&i));
printf("\n Value of i = %d",*j);
printf("\n Value of i = %d",**k);
getch();
}

The output of the above program would be:

Address of i = 6589
Address of i = 6589
Address of i = 6589
Address of j = 3275
Address of j = 3275
Address of k = 7234

Value of j = 6589
Value of k = 3275
Value of i = 5
Value of i = 5
Value of i = 5
Value of i = 5

The following memory map would help you in tracing out how the program prints the above output.
Observe how the variables i, j and k have been declared,

int i;
int *j;
int **k;

Here, i is an ordinary int, j is a pointer to an int, whereas k is a pointer to a pointer. In principle, there could be a pointer to a pointer to a pointer, or a pointer to a pointer to a pointer/ There is no limit on how far can we go on extending this definition.

Taken from 'Understanding Pointers In C'
post by Arnob

32.The & and * Operators in POINTER

Consider the declaration,

int i=5;

This declaration tells the C compier to

  • Reserve space in memory to hold the integer value.
  • Associate the name i with this memory location.
  • Store the value 3 at this location.
We may represent i's location in the memory by the following memory map:

we see that the computer has selected memory location 6589 as the place to store the value 5. This location number 6589 is not a number to be relied upon, becuse some othertime the computer may choose a different location for storring the value 5. The important point is, i's address in memory is a number.

We can print this adderss through the following program:

#include<stdio.h>
main( )
{
int i=5;
printf("\n Address of i=%u", &i);
printf("\n Value of i=%u", i);
getch();
}

The output of the above program would be:

Address of i=6589
Value of i=5

Now look at the first printf( ) statement carefully. The '&' operator used in this statement is C's 'address of' operator. The expression &i returns the address of the variable i, which in this case happens to be 6589.

The other pointer operator available in Cis '*', called 'value at address' operator. It returns the value stored at a porticular address. The 'value at address' operator is also called an 'indirection' operator.

post by Arnob.
taken from 'Understanding pointers In C' 

রবিবার, ১৭ অক্টোবর, ২০১০

31. Introduction to Pointers

Introduction to Pointers
 Pointer is new type of variable that holds the memory address of another variable.
If a variable p contains the address of another variable q, then p is said to point to q.

To declare a pointer variable: add a asterisk to the type you want to point to.
int *a;
Declares a variable a of type int *, which can be used to hold the address of (or a “pointer to”) an integer.

Two unary operators (“inverses”):
& operator - “address of” operator.
Returns the address of the variable it precedes.
int *p = &q;
* operator - “dereference” or “value of” operator.
Accesses the variable that the pointer points to.
Returns the value stored at the address that the pointer points to.
int r = *p;
Pointers: Example 1


void main() {
int x = 1, y = 2, z = 3;
int *ip;
ip = &x;
z = *ip;
printf("%d", z); // prints value to x
printf("%d", *ip); // prints value to x
}




The * operator dereferences the pointer to get at the variable we’re pointing to.
In short: don’t confuse the * (dereference/value of) operator with the * in the declaration of a pointer variable (or with multiplication)!
int *p; // pointer declaration
*p = 100; // dereferencing

Another Example

int x = 1, y = 2;
int *ip;
char c;
char *cp;
ip = &x; /* ip now points to x */
printf( "%d\n", *ip ); /* prints 1 */
printf( "%d\n", *ip + 2 );
/* prints 3 */

y = *ip; /* y is now 1 */
*ip = 0; /* x is now 0 */
printf( "%d\n", x ); /* prints 0 */
//cp= &x; /* doesn’t work; types don’t match */
/*cp is not pointing anywhere */
*cp = ’z’;

cp = &c;
*cp = 'z';
printf( "%c\n", c ); /* prints z */

Pointer Arithmetic

Pointer addition: pointer plus int
if a pointer p points to an element of an array, then p + i is a pointer (of the same type) pointing to the ith element after the element pointed to by p.
Pointer subtraction: pointer minus pointer
If p and q point to elements of the same array, then q - p gives the number of elements between p and q.

Pointer comparison: pointer relation pointer
Permissible relations: ==, !=, <, <=, >, >=
If p and q point to elements of the same array, then p < q is true if p points to an earlier member of the array than q does. Note: CAN’T add two pointers, or perform any sort of multiplication, etc. A pointer is a physical memory location, represented by an integer, but you should never think of them as integers. (Try it!). Pointer arithmetic works at the level of “the next element in the array”, NOT at “the next physical memory address”.
Don’t Get Confused!

 Post by j.siam,
 Ref-: Md Munirul Haque






বৃহস্পতিবার, ১৪ অক্টোবর, ২০১০

30. Recursion

Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms of a previous result. Many iterative problems can be written in this form.

If you want to solve a problem recursively, two conditions must be satisfied. First, the problem must be written in a recursive form, and second one is , the problem statement must include a stopping condition. Suppose, for example, we wish to calculate the facttorial of a positive interger quantity. We would normally express this problem as n! = 1 * 2 * 3 * 4 *........... * n, where n is the specified positive integer. However, we can also express his problem in another way, by writting n! = n * (n-1)! This is a recursive statement of the problem, in which the desired action is expressed in terms of a previous result. Also, er know that 1!=1 by definition. This last expression provides a stopping condition for the recurion.

Example:
Look at this code :
unsigned int factorial(unsigned int a)
{
   if (a == 1)
   return 1;
   else
    {
      a *= factorial(a-1);
      return a;
   }
}


let a =4. Now when a=4 the if condition is false
so 4*=factorial(3);
but factorial( ) is a function so it call again. And again check the if condition where a=3 because the function call when a=3. But if condition is not true
so 3*=factoral(2); again call the function factoral where a=2. And again it check if conditon but it not true.
so 2* = factoral (1);  Now call the factoral and check the if conditon and if is true so it return 1. Now this is a importent point that every time when call the function factorial (), the return a ; is not work. Now it work. At last when the function call at the value of 1, the function return 1. so function (1)=1. Now put the value of facturl(1) in the point [a*=factorial(1)] and we get 2*1=2. the output is look like this:

let a=4
4 != 1 so the if portion is skipped for now.

4*=factorial(3)

3 != 1

3*=factoral(2)

2 != 1

2*=factoral(1)

1==1 so 1 is returned

2*1=2 so 2 is returned

2*3=6 so 6 is returned

6*4=24 so 24 is returned

The function doesn't get to the 'return a' until the factoral(a-1) returns a number which doesn't happen until a==1.

Recursive functions should be avoided at all costs because they get very unweildy very quickly. Large numbers would consume a lot of memory to do something as simple as a factorial.


post by arnob.

29. How to print prime number.

Print Prime Numbers(using for loop):

#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
clrscr();
int i,j,n;
printf("Enter a value : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
 {
 for(j=2;j<=sqrt(i);j++)
   {
   if(i%j==0)
     break;
     if(j>sqrt(i))
     printf("%d  ",i);
   }
 }
getch();
}
post by Arnob.

মঙ্গলবার, ১২ অক্টোবর, ২০১০

28. Program to generate Fibonacci Series

The Fibonacci series :

0, 1, 1, 2, 3, 5, 8, 13, 21, …..


Fibonacci series begins with the terms 0 and 1 and has the property that each succeeding term is the sum of the two preceding terms. Now, I want to write a C program for print the fibonacci series.


#include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
   int OldNum, NewNum, FibNum, MaxNum;
   printf("Generate Fibonacci Numbers till what number? ");
   scanf("%d", &MaxNum);
   OldNum=0;
   NewNum=1;
   FibNum = OldNum + NewNum;
   printf("%d, %d, %d, ", OldNum, NewNum, FibNum);
   for(;;)
   {
      OldNum = NewNum;
      NewNum = FibNum;
      FibNum = OldNum + NewNum;
      if(FibNum > MaxNum)
      {
         printf("");
         exit(1);
      }
      printf("%d, ", FibNum);
   }
}
post by arnob.

সোমবার, ১১ অক্টোবর, ২০১০

27. Create a number pyramid.

 I have written this article to demonstrate how you can print a number pyramids using for loop and if condition. Building a pyramid in c programming is quite easy, but you must have the understanding of how for loop works.

#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int i,j,n,k;
printf("Enter a value : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
 {
  for(j=1;j<=n-i;j++)
   printf(" ");
  {
   for(j=1;j<=i;j++)
   printf("%d",j);
   j=1;
   for(j=i;i>=j;j--)
   if(j==0)
   break;
   else
   {
   k=j-1;
   if(k==0)
   break;
   else
   printf("%d",k);
   }
   printf("\n");
   }
   }
 getch();
}

post by Arnob

26. How to creat a pyramid in C


Hello friends, today I want to write about Pyramid. How can you create a pyramid in C. It is very easy to make a pyramid in C. For create a pyramid in C, you must have the understanding of how for loop works.
                                                             when input is 4.

 If you want to create this type of pyramid you can follow the program.


#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int i,j,n,k;
printf("Enter a value : ");
scanf("%d",&n);
  for(i=1;i<=n;i++)
  {
    for(j=1;j<=n-i;j++)
     printf(" ");
    {
      for(j=1;j<=i;j++)
      printf("*");
       j=1;
      for(j=i;i>=j;j--)
      if(j==0)
      break;
      else
      {
        k=j-1;
        if(k==0)
        break;
        else
        printf("*");
        }
      printf("\n");
      }
    }
getch();
}
post by Arnob

বৃহস্পতিবার, ৭ অক্টোবর, ২০১০

25. DO.....WHILE LOOP

Do....while loop is similar to the while loop. While loop checks the condition first then the statements are executed but the do…..while loop checks the conditions after the statement are executed. This means that do…while loop executes the statements at least once, while the while loop might not execute the statements at all based on its condition.

The expression must have arithmetic or pointer type. Execution proceeds as follows:
1.   The statement body is executed.
2.   Next, expression is evaluated. If expression is false, the do-while statement terminates and control passes to the next statement in the program. If expression is true , the process is repeated, beginning with step 1.

Example of the do-while statement:
do
{
    y = f( x );
    x--;
} while ( x > 0 );

In this program, the two statements y = f( x ); and x--; are executed, regardless of the initial value of x. Then check the condition (x>0). If the condition is true then the statement body is executed again and x > 0 is reevaluated. The statement body is executed repeatedly as long as the condition is true. When the condition is false then do…..while loop is stop.
 post by Arnob

বুধবার, ৬ অক্টোবর, ২০১০

24. Some program using Switch statement.

/* program 1 */


/*  Student result grad using switch statement. */


#include<stdio.h>
#include<conio.h>
void main()
{
int marks, index;
char str;
printf("Enter the marks: ");
scanf("%d",&marks);
index=marks/10;
switch(index)
{
case 10:
case 9:
          strcpy (grade,"A+");
          break();
case 8:
          strcpy (grade,"A");
          break();
case 7:
          strcpy (grade,"B");
          break();
case 6:
           strcpy (grade,"C");
           break();
case 5:
           strcpy (grade,"D");
            break();
case 4:
          strcpy (grade,"E");
          break();
          default:
          strcpy (grade,"F");
          break();
}
printf("%s \n",grade);
getch();
}




/* program 2 */
/* Menu drive program */


#include<stdio.h>
#include<conio.h>
void main()
{
printf ("Travel Guide \n\n");
printf("A air Timings \n");
printf("T Train Timings \n");
printf("B Bus Timings \n");
printf("X To skip \n");
printf("Enter your choice : ");
character=getchar();
switch(character)
{
case 'A':
             air display ();
             break();
case'B':
            bus display();
            break();
case 'T':
             train display();
             break();
Default:
           printf("NO choice");
}
getch();
}

post by arnob

মঙ্গলবার, ৫ অক্টোবর, ২০১০

23. While statement

While is one kind of loop. The process to write down while statement is

While (condition)
{
Statement;
Increment or decrement;
}

Condition means a right expression and we normally use relational expression. While statement first of all check the condition if the condition is true then the program execute the while statement but if the condition false the wile statement can not execute.
Look at this program,

#include<stdito.h>
void main ()
{
int i=1;
while(i<=5)        
{
Printf(“i”);           /* statement */
i++;                      /* increment */
}
getch();
}

Output: 1 2 3 4 5

Explain: First of all I is initialize in i=1; . Then check the condition while (i<=5) so the condition is true because i=1. Then print the value of i by using printf statement (printf(“i”); ). Then the value of i is increment in (i++). Again check the while condition  and printf the value of i and increment i. whine i=6 the while condition is false so the loop is stop.

Written by arnob.

22. Infinite loop

If you want to create an infinite loop you can use for and while loop easily. For create an infinite loop by using for loop, you can not give any initialization, increment and condition into for loop. For example:

for ( ; ; )
{
Printf (“finite loop”);
}

When you run this program you can not exit this for loop normally. For exit this program uses ctrl+Break.

For create an infinite loop by using while loop you can use this formula,

While(1)
{
Printf(“finite loop”);
}

When you run this program you can not exit this for loop normally. For exit this program uses ctrl+Break.

Written by arnob.


  

21. Switch Statement

Taken from Mamun.
Switch statement as like as else if statement. When we create a program than need a lot of statement but when we need one of them statement then we use switch statement.
Structure of switch statement:
Switch (expression)
{
case constant_1:
statement_1;
break;
Case constant_2:
statement_2;
break;
............
default:
default_statement_x;
break;
}

switch statement have 4 keyword
1. switch
2. case.
3. break.
4. default.
Now i discuss about 4 keyword
Switch: Let be known the compiler by the switch that switch statement are working in that program. Most probably we compare it with if statement. As like as it statement written condition expression in '(  )' . Condition expressions are not

switch (expression)
           {
            ..................
            }
written relational or logical expression. It is only normal variable in conditional expression. Case statements are depending on conditional expression.

Case: Case depends on switch condition. Using constant value before case. That is depend on coalition expression. Using the colon (:) after case constant. Which case constant are equal the conditional expression then case statement will word.

Break: Those simple or compound statements are using with case that is used the break after simple or compound statement. When compiler fined the break statement than switch statement is closed.

Default: default as like as else statement. When conditional expression value is not equal with case constant than attach statement is defaults are compiled in the program.

Note that using the colon (:) after default keyword.
default:
statement ();
break;
Note:
1. Constant of two or more case are not same in switch statement.
2. You may used maximum 256 cases in switch statement according to ANSI value.
3. Replace the case constant you can be used char or int. If you use char than you write char in the single quotation (' ')
case 'a':