বৃহস্পতিবার, ৯ ডিসেম্বর, ২০১০

Reverse an integer by using Recursion

#include<stdio.h>
#include<conio.h>
int re (int,int,int*,int);
void main()
{
clrscr();
int i,j=0,n[5],k=0,m;
printf("Enter a number: ");
scanf("%d",&i);
m=re(i,j,n,k);
for(j=0;j<m;j++)
printf("%d",n[j]);
getch();
}
re(int i,int j,int *n,int k)
{
if(i==0) return k;
j=i%10;
n[k]=j;
i=i/10;
re(i,j,n,k+1);
program written by arnob;
48. Writer a C program which store students name, id and gpa. and make a serach option that when we enter a name for search, if the name is there then show that students name,id and gpa. If the name is not there then show NOT FOUND!.



#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
char name[40];
char id[20];
char gpa[5];
}stu[100];
void main()
{
clrscr();
int i=0,j,n;
char name[40];
printf("How many students informatio: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the name: ");
scanf("%s",stu[i].name);
printf("\nEnter the id: ");
scanf("%s",stu[i].id);
printf("\nEnter the gpa: ");
scanf("%s",stu[i].gpa);
clrscr();
}
printf("\nEnter the search name: ");
scanf("%s",name);
for(i=0;i<n;i++)
{
clrscr();
j=strcmp(name,stu[i].name);
if(j==0)
{
printf("\nName :");
puts(stu[i].name);
printf("\nId :");
puts(stu[i].id);
printf("\nGPA :");
puts(stu[i].gpa);
break;
}
}
if(j!=0)
printf("Not found !");
getch();
}

program written by arnob;

শুক্রবার, ৩ ডিসেম্বর, ২০১০

47. Find the hight and second hight number by using RECURSION

/* Find the hight number by using recursion */

#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int n,a[100],i,j;
printf("How many nmber you want to input: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d number",i+1);
scanf("%d",&a[i]);
}
int hight(int,int,int,int*);
j=hight(n,0,0,a);
printf("The hight number is %d",j);
return 0;
}

int hight(int n,int i,int m,int *a)
{
if(i>n) return m;
if(m<a[i])
m=a[i];
hight(n,i+1,m,a);
}


/* Find the second hight number by using recursion */

#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int n,a[100],i;
printf("How many nmber you want to input: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d number",i+1);
scanf("%d",&a[i]);
}
int hight(int,int,int,int,int*);
hight(n,0,0,0,a);
printf("The second hight number is %d",a[1]);
return 0;
}

int hight(int n,int i,int j,int k,int *a)
{
if(i>n-1) return 0;

for(j=i+1;j<n;j++)
if(a[i]<a[j])
{
k=a[i];
a[i]=a[j];
a[j]=k;
}
hight(n,i+1,j,k,a);
}


written by anrob.

46. Find the even number from a array by using RECURSION

Question: Get input a array frmon user and find the hight number. You can only use one array and can not use any globel variable.

Ans: If you can use more then one array then you can easyle find the hight number by only using for loop. But you can not use more then one array. So you can solve this problem by using recursion.

/*program for find the even number */

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

int main()
{
clrscr();
int a[100];n,i;
printf("How many number you want to input: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d number: ");
scanf("%d",&a[i]);
}
void chk_evn(int,int,int*,int*)
chk_evn(0,0,&n,a);
for(i=0;i<n;i++)
printf("%d",a[i]);
return 0;
}

void chk_evn (int i,int j,int *n,int *a)
{
if(i==n){*n=j;return n;}
if(a[i]%2==0)
a[j++]=a[i];
chk_evn(i+1;j,n,a);
}

program written by arnob

বৃহস্পতিবার, ১১ নভেম্বর, ২০১০

45. Passing 2-D Array to a Function by using pointer

There are two ways in which er can pass a 2-D array to a function by using pointer. These are illustrated in the following program.

/*Two ways of accessing a 2-D array*/
#include<alloc.h>
void main()
{
int a [3][4]={
               1,2,3,4,
               5,6,7,8,
               9,0,1,6
             };
clrscr();
display(a,3,4);
show(a,3,4);
}

display(int *q,int row, int col)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%d",*(q+i*col+j));
printf("\n");
}
printf("\n");
}

show(int (*q)[4],int row, int clo)
{
int i,j;
int *p;

for(i=0;i<row;i++)
{
p=q+i;
for(j=0;j<col;j++)
printf("%d",*(p+j));
printf("\n");
}
printf("\n");
}

And here is the output...

1234
5678
9016

1234
5678
9016

In the display() finction we have collected the base address of the 2-D array being passed to it in an ordinary int pointer. Thenthrough the two for loops using the ex[ression *(q+i*col+j) we have reached the appropriate element in the array. Suppose i is equal to 2 and j is equal to 3, then we wish to reach the element give this element or not. The exprewssion *(q+i*col+j) becomes *(4001+2*4+3). This turns out to be *(4001+11). Since 4001 is address of an integer, *(4001+11) turns out to be *(4023). Value at this address is +. This is indeed same as a[2][3]. A more general formula for accessing each array element would be:

*(base address + row *no of columns +column no)

In the show( ) function we have defined q to be a pointer to an array of 4 integers through the declaration
int (*q)[4];

To begin with, q hods the base address of the xeroth 1-D array, i.e 4001. This address is then assigned to p, an int pointer, and then using this pointer all elements of the xeroth 1-D array are accessed. Next thime through the loop when i takes a value 1, the expression q+i fetches the address of the first 1-D arry. This is because, q is a pointer to zeroth 1-D array and adding 1 to it would given us the address of the next 1-D array. This address is once again assigned to p, and using it all elements of the next 1-D arraY are accessed. 

Arnob

বুধবার, ১০ নভেম্বর, ২০১০

44. Array of pointer

The way there can be an array of ints or an array of floats, similarly there can be an array of pointers. Since a pointer vcariable always contains an address, an array of pointers would be nothing but a collection of addresses. The addresses present in the array of pointers can be addresses of isolated variables or addresses of array elements or any other addresses. All rules that apply to an ordinary array apply in toto to the array of pointers as well. I think a program would clarify the concept.

/*Array of pointer*/
#include<stdio.h>
void main( )
{
int *arr[4]; /* array of integer pointers */
int i=31,j=5,k=19,l=17,m;

arra[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
for (m=0;m>3;m++)
printf("\n%u",*(arr[m]));
}

And here is the putput...
31
5
19
71

Here is another program...

#include <stdio.h>
#include <conio.h>
main() {
  clrscr();
  int *array[3];
  int x = 10, y = 20, z = 30;
  int i;
  array[0= &x;
  array[1= &y;
  array[2= &z;
  for (i=0; i< 3; i++) {
    printf("The value of %d= %d ,address is %u\t \n", i, *(array[i]),
        array[i]);
  }
  getch();
  return 0;
}

output......


Taken from "Understanding Pointers IN C"

সোমবার, ৮ নভেম্বর, ২০১০

43. Pointer to an array

The way we can have a pointer to an integer or a pointer to a float, can we also have a pointer to an array? The answer is yes. The Declaration of a pointer to an integer is int *p; but the declaration of a pointer to an array is int (*q)[4]; That means q is a pointer to an array of 4 integer. Pointer to an array, use in two dimensional arrays. When we increase a pointer to an integer it points the next element, but when we increase the pointer to an array it skip those element which you give in the bracket. In this declaration int (*q)[4]; it skip 4 element. Let us use this pointer to an array in a program. Here it is…

/*Program for pointer to an array*/

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

void main( )
{
int a[][4]= {
              5,7,5,9
              4,6,3,1
              2,9,0,6
            };
int *p;
int (*q)[4];

p=(int*)a;
q=a

printf(“\n %u %u”,p,q);
p++;
q++;
printf(“\n %u %u”,p,q);
getch();\
};

And here is the output…

65500 65500
65502 65508

To begin with both p and q contain the same address 65500. However, p is an integer pointer, whereas q is a pointer to an array of 4 integers. Hence on incrementing p it points to the next integer, whereas, q starts pointing to the next 1-D array of 4 integers. Pointer to an array is vary useful while passing a 2-D array to a function, as we would see in the next section.

Written by Arnob
Ref: “Understanding Pointers In C”

রবিবার, ৭ নভেম্বর, ২০১০

42. Dynamic Memory Allocation

In this tutorial you will learn about C Programming - Dynamic Memory Allocation. Suppose we have a program which can store 100 student’s marks. If you need to store 75 students’ marks in this program you can, but some memory are not uses. But if you need store 110 students’ marks in this program you can not do it. You need increase array size. So it is big problem when any body use this program because he or she can not increase the array size. If we have a way that when the program runs in that time we give the array size, then that problem can not come. Yes we have a way that when we run the program we give the student number then the program make array size in its own. The way is dynamic memory allocation. In this system we can use two functions they are malloc and calloc. They both do the same work. They are often known as “Dynamic memory allocation functions”. Let us now see a program, which uses the concept of dynamic memory allocation.

/*Program for dynamic memory allocation */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n,avg,I,*p,sum=0;

printf(“\n Enter the number of student: ”);
scanf(“%d”,&n);

p=(int*) malloc (n*2)
if(p==NULL)
{
printf(“\n Memory allocation unsuccessful”);
exit();
}
for(i=0;i<n;i++)
scanf(“%d”,(p+i));

for(i=0;i<n;i++)
sum=sum+*(p+i);

avg=sum /n;
printf(“Average marks=%d”,avg);
getch();
}
Note: here (n*2) means that the number of (student * 2). We want to convert the student number in byte. The number of student is integer so we multiply with 2(integer =2 byte). If it is float then we multiply with 4(float=4 byte).

Here, we have first asked for the number of students whose marks are to be entered and then allocated only as much memory as is really required to store these marks. Not a byte more, not a byte less. The allocation job is done using the standard library function malloc( ). malloc( ) returns a NULL if memory allocation is unsuccessful. If successful it returns the address of the memory chunk that is allocated. We have collected this address in an integer pointer p since malloc( ) returns a void pointer we have telecasted it into an integer pointer. IN the first for loop using simple pointer arithmetic we have stored the marks entered from keyboard into the memory that has been allocated. In the second for loop we have accessed the same values to find the average marks.

The calloc( ) functions works exactly similar to malloc( ) except for the fact that is needs tow arguments. For example,
Int *p
P=(int*) calloc (10,2);

Here 10 mean the number of student. And 2 indicates that we wish to allocate memory for storing integers.


Written by Arnob.
Reference: “Understanding Pointers In C”

41. Files in C

The library stdio.h defines a structure called FILE.
You don’t need to know any of the details of how a FILE works, you just need to know how to point to them.
A pointer to a file is called a “file handle”.

Writing to a File

void main()
 {
FILE *fp; /* pointer to a file */
/* open WRITEME.txt for reading */
fp = fopen("WRITEME.txt", “w");
/* do stuff with the file */
fprintf(fp,"This goes in the file");
/* close the file -- it’s a good habit */
fclose(fp);
}

fopen

The function fopen accepts a string corresponding to the name of the filename, and another string the says whether we want to open the file to
read ("r"),
Write ("w"), or
append ("a").
If there is any error, fopen returns the pointer value NULL.

Input and Output in File

Up to now, we’ve been using printf to print messages (to “standard output”), and scanf to receive input from the keyboard (from “standard input”).
These can be generalized to the functions fprintf and fscanf, which write to and read from a particular file.

Given a file pointer fp, the statement:
fprintf(fp,"This goes in the file");
writes to the file handled by fp.
The statement: fscanf(fp,"%d",&intvar); reads an integer from the file.

Read and Writing Way

There are more rudimentary ways to read from files and write to files.
Suppose that fp is a file pointer.

The function getc(fp) returns a single character read from the file.
putc(c,fp);
writes the character c to the file.

Finishing of File

feof() returns non-zero if fp reaches end-of-file, otherwise zero.

FILE *fp;
while(!feof(fp))
ch = getc(ch);

Post by J.siam
Ref Herbert Schildt

40. ASCII Characters & Characters Constants

ASCII Characters


ASCII stands for American Standard Code for Information Interchange.
A character is 8 bits long.
The characters are represented by an 8 bit integer.
For example, the character code for ‘A’ is 65 and the character code for ‘a’ is 97.

Character Constants

All characters are represented as integers (usually signed), and can be treated as integers.
Escape codes correspond to characters, for use in single-quotes:
Examples: \n (newline), \\ (backslash), \" (double quote)
Example use: char a = ’\n’;
Variables of type char can be thought of as either a character of an integer.
printf( "%c", ’a’ ); /* a is printed */
printf( "%d", ’a’ ); /* 97 is printed */
printf( "%c", 97 ); /* a is printed */
printf( "%d", 97 ); /* 97 is printed */


Lower-case letters, upper-case letters, digits “consecutive”
’a’ == 97, ’b’ == 98, . . ., ’z’ == 122
’A’ == 65, ’B’ == 66, . . ., ’Z’ == 90
’0’ == 48, ’1’ == 49, . . ., ’9’ == 57
• Some more examples of the integer values corresponding to character constants:
’ ’ == 32, ’*’ == 42, ’\n’ == 10, ’\\’ == 92, . . .


Characters


#include<stdio.h>
void main() {
char i;
printf( "Here’s the alphabet, in lower-case:\n" );
for( i = 'a'; i <='z'; i++ ) { printf( "%c", i ); } printf( "\n\nHere’s the alphabet, in upper-case:\n" ); for( i = 'A'; i <= 'Z'; i++ ) { printf( "%c", i );
}
}

 Post by J.siam
 Ref Herbert Schildt

39. Pointers and Arrays 2

Suppose that a is an int array of size 10.
If pa is a pointer to an integer, i.e.,
int *pa;
then the assignment
pa = &a[0];
sets pa to point to element zero of a.
When does x = *pa; make sense – what does the type of x have to be? What does it do?

If pa points to an element of an array, then (by definition) pa + 1 points to the next element.
In general, pa + i points to the ith element after the element pointed to by pa.
Example.
int a[4] = { 0, 1, 2, 3 };
int *p;
p = &a[0];
printf( "%d\n", *(p + 2)); // prints 2
scanf( "%d", p + 3 ); // take input in a[3]
printf( "You typed: %d\n", a[3] );

More on pointers and arrays

In fact, the name of an array is a synonym for the address of the initial element.
As an example, when we have the declarations int a[10]; int *pa;
&a[0] is the same as a, and thus-
pa = &a[0];
is the same as
pa = a;.

For any expression b of type int *, b[i] can always be written as *(b + i), and vice-versa.

For example, given the above declarations:
a[i] and *(a + i) are equivalent
pa[i] and *(pa + i) are equivalent

Even more on pointers and arrays

Note that an array name (like a assuming the above declarations) is not a variable, so statements like
a = pa; and a++; are illegal. (You also don’t want to form the expression &a.)

Practice: Pointers and Arrays

void main() {
int a[4] = { 0, 1, 2, 3 };
int *pa;
pa = a + 1;
printf( "%d\n", *pa ); // prints 1
printf( "%d\n", pa[2] ); // prints 3
pa++;
printf( "%d\n", pa[0] ); // prints 2
scanf( "%d", pa + 1 ); // input at a[3]
printf( "You typed: %d\n", a[3] ); // prints 3
}

Post by J.siam
Ref Herbert Schildt

38.Array Of Strings

Strings: they’re just arrays!
Strings are one-dimensional arrays of chars.
By convention, a string in C is terminated by the null character, ’\0’, or 0. (We have ’\0’ == 0.)
String constants (such as those passed to the function printf) are enclosed in double quotes.
When allocating char arrays that will hold strings, make sure you allocate enough space!

Array Of Strings

Declaration:
char arr[8][81];
// allocates 8 string space each with 80 character length

Input
scanf(“%s”, arr[2]);
scanf(“%s”, &arr[2][0]);
gets(arr[2]);
gets(&arr[2][0]);


void main()
{
char arr[8][81];
scanf( "%s", arr[1] );
printf( "Length of your string: " );
printf( "%d\n", strlen(arr[1] ));

printf( "You typed the string: %s\n", arr[1] );
printf( "The first character you typed was: " );
printf( "%c\n", arr[1][0] );
}


Two-dimensional array of chars acts as array of strings (of size 8): arr[0], ..., arr[7]
scanf( "%s", ... ); used to read strings.
To refer to a specific character of one of the strings arr[i], tack on another index:
arr[1][0] for instance refers to the first (zero-indexed) character of the string arr[1].

String matching

void main()
{
char s1[20], s2 [20];
strcpy( s2, "Hello" );
strcpy(s1, s2);

for(i=0; i if( s1[i] != s2[i] ) {
printf(“Not equal”);
break;
printf(“String s1 and s2 is equal at character index %d”, i);
}
}

Post by J.siam
Ref Herbert Schildt

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

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