ftell Function in C | Get current position using FTELL Function | using ftell() function in c

ftell Function in C | Get current position using FTELL Function | using ftell() function in c language|Return value of ftell



Gives the current position in the file, i.e. Returns the current value of the position indicator of the stream.

On success, the current value of the position indicator is returned.
If an error occurs, -1L is returned, and the global variable errno is set to a positive value. This value can be interpreted by perror.





#include 

int main ()
{
  FILE * pFile;
  long size;

  pFile = fopen ("popsys.txt","rb");
  if (pFile==NULL) perror ("Sorry Error opening file");
  else
  {
    fseek (pFile, 0, SEEK_END);
    size=ftell (pFile);
    fclose (pFile);
    printf ("Yes!! Size of myfile.txt: %ld bytes.\n",size);
  }
  return 0;
}

Related Links :

Position the file pointer in C | Moving File Pointer in C To Specific Location | fseek() Function Use Details | rewind() Function in C | Parameters of rewind, fseek function in C

Position the file pointer in C | Moving File Pointer in C To Specific Location | fseek() Function Use Details | rewind() Function in C | Parameters of rewind, fseek function in C 

 

Well Friends, Lets check out the File Pointers & its related Functions like FSEEK, SEEK_CUR, REWIND etc. One of the attributes of an open file is its file position that keeps track of where in the file the next character is to be read or written. In the GNU system, and all POSIX.1 systems, the file position is simply an integer representing the number of bytes from the beginning of the file.

The file position is normally set to the beginning of the file when it is opened, and each time a character is read or written, the file position is incremented. In other words, access to the file is normally sequential. Ordinary files permit read or write operations at any position within the file. Some other kinds of files may also permit this. Files which do permit this are sometimes referred to as random-access files. You can change the file position using the fseek function on a stream or the lseek function on a file descriptor. If you try to change the file position on a file that doesn't support random access, you get the ESPIPE error. Streams and descriptors that are opened for append access are treated specially for output: output to such files is always appended sequentially to the end of the file, regardless of the file position. However, the file position is still used to control where in the file reading is done. If you think about it, you'll realize that several programs can read a given file at the same time. In order for each program to be able to read the file at its own pace, each program must have its own file pointer, which is not affected by anything the other programs do.


int fseek(FILE *stream, long offset, int whence);
void rewind(FILE *stream);
 
 
 
When doing reads and writes to a file, the OS keeps track of where you are in the file using a counter generically known as the file pointer. You can reposition the file pointer to a different point in the file using the fseek() call. Think of it as a way to randomly access you file.
The first argument is the file in question, obviously. offset argument is the position that you want to seek to, and whence is what that offset is relative to.
Of course, you probably like to think of the offset as being from the beginning of the file. I mean, "Seek to position 3490, that should be 3490 bytes from the beginning of the file." Well, it can be, but it doesn't have to be. Imagine the power you're wielding here. Try to command your enthusiasm.
You can set the value of whence to one of three things:
SEEK_SET
offset is relative to the beginning of the file. This is probably what you had in mind anyway, and is the most commonly used value for whence.
SEEK_CUR
offset is relative to the current file pointer position. So, in effect, you can say, "Move to my current position plus 30 bytes," or, "move to my current position minus 20 bytes."
SEEK_END
offset is relative to the end of the file. Just like SEEK_SET except from the other end of the file. Be sure to use negative values for offset if you want to back up from the end of the file, instead of going past the end into oblivion.
Speaking of seeking off the end of the file, can you do it? Sure thing. In fact, you can seek way off the end and then write a character; the file will be expanded to a size big enough to hold a bunch of zeros way out to that character.
Now that the complicated function is out of the way, what's this rewind() that I briefly mentioned? It repositions the file pointer at the beginning of the file:

fseek(fp, 0, SEEK_SET); // same as rewind() 
rewind(fp); // same as fseek(fp, 0, SEEK_SET)
 
 
What it fseek Function Returns??
  
Well fseek(), on success zero is returned; -1 is returned on failure. 

Related Links :

Difference between Macros and Functions in C | Comparing macros & function in C | C language macro, User Defined Functions, PDF, Macros in C | Working of Function and macro in C Programming

Difference between Macros and Functions in C | Comparing macros & function in C | C language macro, User Defined Functions, PDF, Macros in C | Working of Function and macro in C Programming 

 


Macros
Functions
Macro calls are replaced with macro expansions (meaning).

In function call, the control is passed to a function definition along with arguments, and definition is processed and value may be returned to call
Macros run programs faster but increase the program size.
Functions make program size smaller and compact.
If macro is called 100 numbers of times, the size of the program will increase.
If function is called 100 numbers of times, the program size will not increase.
It is better to use Macros, when the definition is very small in size.
It is better to use functions, when the definition is bigger in size.


Related Links :

Null Pointer Assignment in C | Null Pointer concept in c

Null Pointer Assignment in C | Null Pointer concept in c


It does make sense to assign an integer value to a pointer variable. An exception is an assignment of 0, which is sometimes used to indicate some special condition(Null pointer).

A macro is used to represent a null pointer. That macro goes under the name NULL. Thus, setting the value of a pointer using the NULL, as with an assignment statement such as ptr = NULL, tells that the pointer has become a null pointer. Similarly, as one can test the condition for an integer value as zero or not, like if (i == 0), as well we can test the condition for a null pointer using if (ptr == NULL) or you can even set a pointer to NULL to indicate that it’s no longer in use.


# include
# define NULL 0
main()
{
int *pi = NULL;
printf(“The value of pi is %u”, pi);
}
 
 

Related Links :

What's the difference between const MAXSIZE = 100; and #define MAXSIZE 100

What's the difference between
    const MAXSIZE = 100;
and
    #define MAXSIZE 100


A preprocessor #define gives you a true compile-time constant. In C, const gives you a run-time object which you're not supposed to try to modify; ``const'' really means ``readonly''.

Related Links :

Pointers and Pointees in C | Difference between Pointers and Pointees in C | C language Pointers and Pointees concept

Pointers and Pointees in C | Difference between Pointers and Pointees in C | C language Pointers and Pointees concept



Pointers and Pointees

A pointer stores a reference to something. Unfortunately there is no fixed term for the thing that the pointer points to, and across different computer languages there is a wide variety of things that pointers point to. We use the term pointee for the thing that the pointer points to, and we stick to the basic properties of the pointer/pointee relationship which are true in all languages. The term "reference" means pretty much the same thing as "pointer" -- "reference" implies a more high-level discussion, while "pointer" implies the traditional compiled language implementation of pointers as addresses. For the basic pointer/pointee rules covered here, the terms are effectively equivalent.

Related Links :

Multilevel pointers in c programming | Pointers of Pointers | Pointers in Pointers in C |

Multilevel pointers in c programming | Pointers of Pointers | Pointers in Pointers in C 


A pointer is pointer to another pointer which can be pointer to others pointers and so on is know as multilevel pointers. We can have any level of pointers.



#include
int main(){
int s=2,*r=&s,**q=&r,***p=&q;
printf("%d",p[0][0][0]);


return 0;
}

Output: 2

Explanation:

As we know p[i] =*(p+i)
So,
P[0][0][0]=*(p[0][0]+0)=**p[0]=***p
Another rule is: *&i=i
So,
***p=*** (&q) =**q=** (&r) =*r=*(&s) =s=2



Related Links :

Multidimensional Arrays Table of 1 to 34 Numbers

Multidimensional Arrays Table of 1 to 34 Numbers | Print Numbers in matrix format | Tabular Printing of numbers in C



#include 

const int num_rows = 7;
const int num_columns = 5;

int
main()
{
  int box[num_rows][num_columns];
  int row, column;

  for(row = 0; row < num_rows; row++)
    for(column = 0; column < num_columns; column++)
      box[row][column] = column + (row * num_columns);

  for(row = 0; row < num_rows; row++)
    {
      for(column = 0; column < num_columns; column++)
        {
          printf("%4d", box[row][column]);
        }
      printf("\n");
    }
  return 0;
}

Related Links :

Preprocessor in C | How C Preprocessor Works | Preprocessor Concept in C | Examples on Preprocessor in C | Preprocessor Compiling Steps

Preprocessor in C | How C Preprocessor Works | Preprocessor  Concept in C | Examples on Preprocessor in C | Preprocessor Compiling Steps 



The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In simplistic terms, a C Preprocessor is just a text substitution tool. We'll refer to the C Preprocessor as the CPP.
All preprocessor lines begin with #
  • The unconditional directives are:
    • #include - Inserts a particular header from another file
    • #define - Defines a preprocessor macro
    • #undef - Undefines a preprocessor macro
  • The conditional directives are:
    • #ifdef - If this macro is defined
    • #ifndef - If this macro is not defined
    • #if - Test if a compile time condition is true
    • #else - The alternative for #if
    • #elif - #else an #if in one statement
    • #endif - End preprocessor conditional
  • Other directives include:
    • # - Stringization, replaces a macro parameter with a string constant
    • ## - Token merge, creates a single token from two adjacent ones

Pre-Processors Examples:

Analyze following examples to understand various directives.
  #define MAX_ARRAY_LENGTH 20
Tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability.
  #include 
  #include "myheader.h"
Tells the CPP to get stdio.h from System Libraries and add the text to this file. The next line tells CPP to get myheader.h from the local directory and add the text to the file.
  #undef  FILE_SIZE
  #define FILE_SIZE 42
Tells the CPP to undefine FILE_SIZE and define it for 42.
  #ifndef MESSAGE
  #define MESSAGE "You wish!"
  #endif
Tells the CPP to define MESSAGE only if MESSAGE isn't defined already.
  #ifdef DEBUG
    /* Your debugging statements here */
  #endif
Tells the CPP to do the following statements if DEBUG is defined. This is useful if you pass the -DDEBUG flag to gcc. This will define DEBUG, so you can turn debugging on and off on the fly!

Stringize (#):

The stringize or number-sign operator ('#'), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro that has a specified argument or parameter list.
When the stringize operator immediately precedes the name of one of the macro parameters, the parameter passed to the macro is enclosed within quotation marks and is treated as a string literal. For example:
#include 

#define   message_for(a, b)  \
          printf(#a " and " #b ": We love you!\n")

int main(void)
{
   message_for(Carole, Debra);
   return 0;
}
This will produce following result using stringization macro message_for
Carole and Debra: We love you!

Token Pasting (##):

The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token.
If the name of a macro parameter used in the macro definition is immediately preceded or followed by the token-pasting operator, the macro parameter and the token-pasting operator are replaced by the value of the passed parameter.Text that is adjacent to the token-pasting operator that is not the name of a macro parameter is not affected. For example:
#define tokenpaster(n) printf ("token" #n " = %d", token##n)

tokenpaster(34);
This example results in the following actual output from the preprocessor:
printf ("token34 = %d", token34);
This example shows the concatenation of token##n into token34. Both the stringize and the token-pasting operators are used in this example.

Parameterized Macros:

One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number:
int square(int x) {
    return x * x;
  }
We can instead rewrite this using a macro:
#define square(x) ((x) * (x))
Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between and macro name and open parenthesis. For example:
#define MAX(x,y) ((x) > (y) ? (x) : (y))

Macro Caveats:

  • Macro definitions are not stored in the object file. They are only active for the duration of a single source file starting when they are defined and ending when they are undefined (using #undef), redefined, or when the end of the source file is found.
  • Macro definitions you wish to use in multiple source files may be defined in an include file which may be included in each source file where the macros are required.
  • When a macro with arguments is invoked, the macro processor substitutes the arguments into the macro body and then processes the results again for additional macro calls. This makes it possible, but confusing, to piece together a macro call from the macro body and from the macro arguments.
  • Most experienced C programmers enclose macro arguments in parentheses when they are used in the macro body. This technique prevents undesired grouping of compound expressions used as arguments and helps avoid operator precedence rules overriding the intended meaning of a macro.
  • While a macro may contain references to other macros, references to itself are not expanded. Self-referencing macros are a special feature of ANSI Standard C in that the self-reference is not interpreted as a macro call. This special rule also applies to indirectly self-referencing macros (or macros that reference themselves through another macro).

Related Links :

Bitwise operators supported by C language

Bitwise operators supported by C language



There are following Bitwise operators supported by C language
OperatorDescriptionExample
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in eather operand. (A | B) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. (~A ) will give -60 which is 1100 0011
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will

Related Links :

Shutdown Windows XP PC From C | C language Code to Shutdown Windows XP Computer

Shutdown Windows XP PC From C | C language Code to Shutdown Windows XP Computer





#include 
#include 
 
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;
}


Related Links :

C program to shutdown Windows 7 PC | Shutdown windows 7 computer from C Language

C program to shutdown Windows 7 PC | Shutdown windows 7 computer from C Language




#include 
#include 
 
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;
}


Related Links :

C program to shutdown Ubuntu Linux Computer | turn off Ubuntu Linux PC From C Language

C program to shutdown Ubuntu Linux Computer | turn off Ubuntu Linux PC From C Language







#include 
 
int main() {
  system("shutdown -P now");
  return 0;
} 



Related Links :

c program for character pattern | Printing Character pattern in C | Patterns of Chars in C | Pyramid of characters in C

c program for character pattern | Printing Character pattern in C | Patterns of Chars in C | Pyramid of characters in C





#include
 
main()
{
      char ch = 'A';
      int n, c, k, space = 0;
 
      scanf("%d", &n);
 
      for ( k = n ; k >= 1 ; k-- )
      {
          for ( c = 1 ; c <= space ; c++)
              printf(" ");
 
          space++;
 
          for ( c = 1 ; c <= k ; c++ )
          {
             printf("%c ", ch); 
             ch++;
          }
 
          printf("\n");
          ch = 'A';
      }
 
      return 0;
}


Related Links :

C Program to print pattern of stars and numbers | Printing pattern of Stars and Number Combination | pyramid in stars and numbers in C

C Program to print pattern of stars and numbers | Printing pattern of Stars and Number Combination | pyramid in stars and numbers in C





#include
 
main()
{
    int n, c, k, space, count = 1;
 
    printf("Enter number of rows\n");
    scanf("%d",&n);
 
    space = n;
 
    for ( c = 1 ; c <= n ; c++)
    {
        for( k = 1 ; k < space ; k++)
           printf(" ");
 
        for ( k = 1 ; k <= c ; k++)
        {
            printf("*");
 
            if ( c > 1 && count < c)
            {
                 printf("A");    
                 count++; 
            }      
        }    
 
        printf("\n");
        space--;
        count = 1;
    }
    return 0;
}


Related Links :

c code to print pattern

c code to print pattern of Star | C Program to Print pyramid of stars in C | Pyramid of stars in C | Printing pyramid of asterisk in C



#include
 
main()
{
    int n, c, k = 2, j;
 
    printf("Enter number of rows\n");
    scanf("%d",&n);
 
    for ( j = 1 ; j <= n ; j++ )
    {
        for ( c = 1 ; c <= 2*n-k ; c++)
           printf(" ");
 
        k = k + 2;
 
        for ( c = 1 ; c <= j ; c++)
           printf("*   ");
 
        printf("\n");
    } 
 
    getch();
    return 0;
}





OUTPUT : 

      *
    *   *
  *   *   *
*   *   *   *



Related Links :

Palindrome number program c

Palindrome number program c | C Program to check Palindrome Number in C | Algorithm for Palindrome Number 

 


#include
 
main()
{
   int n, reverse = 0, temp;
 
   printf("Enter a number to check if it is a palindrome or not\n");
   scanf("%d",&n);
 
   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;
}



Palindrome number algorithm 1. Get the number from user. 2. Reverse it. 3. Compare it with the number entered by the user. 4. If both are same then print palindrome number 5. Else print not a palindrome number.

Related Links :

c program to reverse a number | Reversing Number in C | C Assignment to reverse number

c program to reverse a number | Reversing Number in C | C Assignment to reverse number



#include 
 
main()
{
   int n, reverse = 0;
 
   printf("Enter a number to reverse\n");
   scanf("%d",&n);
 
   while (n != 0)
   {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n = n/10;
   }
 
   printf("Reverse of entered number is = %d\n", reverse);
 
   return 0;
}



Related Links :

c program to swap two numbers | Swaping 2 numbers in C | C assignments to swap two numbers | Number swapping in C

c program to swap two numbers | Swapping 2 numbers in C | C assignments to swap two numbers | Number swapping in C





#include 
 
int main()
{
   int x, y, temp;
 
   printf("Enter the value of x and y\n");
   scanf("%d%d", &x, &y);
 
   printf("Before Swapping\nx = %d\ny = %d\n",x,y);
 
   temp = x;
   x = y;
   y = temp;
 
   printf("After Swapping\nx = %d\ny = %d\n",x,y);
 
   return 0;
}


Related Links :

c program to add n numbers | Addition of n Numbers in C

c program to add n numbers | Addition of n Numbers in C | C assignments to add N numbers in C



#include 
 
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);
 
   for (c = 1; c <= n; c++)
   {
      scanf("%d",&value);
      sum = sum + value;
   }
 
   printf("Sum of entered integers = %d\n",sum);
 
   return 0;
}



Related Links :

c program to find ncr and npr | nCr Calculation in C | C Assignments to solve NCR and NPR | Equation Solving in C language

c program to find ncr and npr | nCr Calculation in C | C Assignments to solve NCR and NPR | Equation Solving in C language




#include
 
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
 
main()
{
   int n, r;
   long ncr, npr;
 
   printf("Enter the value of n and r\n");
   scanf("%d%d",&n,&r);
 
   ncr = find_ncr(n, r);
   npr = find_npr(n, r);
 
   printf("%dC%d = %ld\n", n, r, ncr);
   printf("%dP%d = %ld\n", n, r, npr);
 
   return 0;
}
 
long find_ncr(int n, int r)
{
   long result;
 
   result = factorial(n)/(factorial(r)*factorial(n-r));
 
   return result;
}
 
long find_npr(int n, int r)
{
   long result;
 
   result = factorial(n)/factorial(n-r);
 
   return result;
} 
 
long factorial(int n)
{
   int c;
   long result = 1;
 
   for( c = 1 ; c <= n ; c++ )
      result = result*c;
 
   return ( result );
}

Related Links :

c program to swap two numbers using bitwise operators | Swap 2 numbers using Bitwise operator | Bit wise Operator Swap two numbers

c program to swap two numbers using bitwise operators | Swap 2 numbers using Bitwise operator | Bit wise Operator Swap two numbers



#include 
int main() 
{
int i = 65;
int k = 120;
printf("\n value of i=%d k=%d before swapping", i, k);
i = i ^ k;
k = i ^ k;
i = i ^ k;
printf("\n value of i=%d k=%d after swapping", i, k);
return 0;
}



Related Links :

PUSHBOX Game in C | C Language Games | Fun in C Gaming

PUSHBOX Game in C | C Language Games | Fun in C Gaming


#include
#include
#include
#include
void display(char a[11][9]);
int pos(char a[11][9]);
void swap(char *a,char *b);
int final(char a[11][9]);
void main()
{

char a[11][9],ch;
for(i=0;i<11;i++)
for(j=0;j<9;j++)
a[i][j]='a';
}
{
a[i][8]='H';
for(i=0;i<9;i++)
a[0][i]='H';
}
{
{
a[i][j]='H';
}
a[1][7]='X';
a[9][7]='X';
a[4][5]='U';
a[6][5]='U';
a[1][2]='H';
a[1][6]='H';
a[7][2]='H';
a[7][6]='H';

/* You can change the designing part to customize your own puzzle  */
abc:;
final1=final(a);
if(final1==0)
clrscr();
printf("\\n\\n********Congrats Puzzle Solved********");
printf("\\n\\n********www.glearn.net / www.lernc.blogspot.com********");
clrscr();
upos=pos(a);
no=ch;

{
{

{
a[2][1]='O';
goto abc;
else if(a[2][7]=='U'&&a[3][7]=='O')
a[1][7]='a';
a[3][7]='a';
}
goto abc;

goto abc;

{
swap(&a[upos/9][upos%9],&a[(upos/9)-1][upos%9]);
else if(a[(upos/9)-1][upos%9]!='X')
}
}
{
{

{
a[8][1]='O';
}

{
a[8][7]='O';
}

goto abc;

goto abc;

{
swap(&a[upos/9][upos%9],&a[upos/9+1][upos%9]);
else if(a[(upos/9)+1][upos%9]!='X')
}

}
{
{

{
a[1][6]='O';
}

{
a[9][6]='O';
}

goto abc;

goto abc;

{
swap(&a[upos/9][upos%9],&a[upos/9][upos%9+1]);
else if(a[(upos/9)][upos%9+1]!='X')
}
}
{
{

{
a[1][2]='O';
}

{
a[9][2]='O';
}

goto abc;

goto abc;

{
swap(&a[upos/9][upos%9],&a[upos/9][upos%9-1]);
else if(a[(upos/9)][upos%9-1]!='X')
}
}

{
}
       else if(no==114)
                {
                       goto ab;
                 }
goto abc;
}

getch();      /* clean up */
closegraph();

}

void display(char a[11][9])
{

int poly[8];
{
{
{
poly[1]=poly[3]=y1;
poly[7]=poly[5]=y2;
setfillstyle(SOLID_FILL,RED);
}
{
poly[1]=poly[3]=y1+3;
poly[7]=poly[5]=y2-3;
setfillstyle(SOLID_FILL,YELLOW);
}
{
poly[1]=poly[3]=y1+3;
poly[7]=poly[5]=y2-3;
setfillstyle(SOLID_FILL,BLACK);
}
{
poly[1]=poly[3]=y1+3;
poly[7]=poly[5]=y2-3;
setfillstyle(SOLID_FILL,CYAN);
}
{
poly[1]=poly[3]=y1;
poly[7]=poly[5]=y2;
setfillstyle(SOLID_FILL,GREEN);
}
x2=x2+20;
x1=100;
y1=y1+20;
}
}

int pos(char a[11][9])
{
for(i=1;i<11;i++)
for(j=1;j<9;j++)
if(a[i][j]=='O')
pos=9*i+j;
}
}
}

void swap(char *a,char *b)
{
temp=*a;
*b=temp;
}

int final(char a[11][9])
{
{
{
{
return(final);
}
return(final);
}



Related Links :

Pointers in C | Concept of Pointers in C | Working of Pointers in C

Pointers in C | Concept of Pointers in C | Working of Pointers in C | C Pointers representation of Concept 

Pointer is a variable that represents the location of a data item, such as variable or an array element. Within the computer’s memory, every stored data item occupies one or more contiguous memory cells. The number of memory cells required to store a data item depends on the type of the data item. For example, a single character will typically be stored in one byte of memory; an integer usually requires two contiguous bytes, a floating-point number usually requires four contiguous bytes, and a double precision usually requires eight contiguous bytes.

                          Suppose v is a variable that represents some particular data item. The compiler will automatically assign memory cells to this data item. The data item can then be accessed if we know the address of the first memory cell. The address of v’s memory location can be determined by the expression &v, where & is the unary operator, called the address operator, that evaluates the address of its operand.

                          Now let us assign the address of v to another variable pv. Thus pv = &v;
This new variable is called pointer to v. since it “points to” the location where v is stored in address, not its value. Thus pv is referred to as a pointer variable. The relationship between pv and v is illustrated in the following figure.

Address of V-----------> Value of V

                          The data item represented by v. (i.e. the data item stored in v’s memory cells) can be accessed by the expression *pv where * is a unary operator called the indication operator, that operates only on a pointer variable. Therefore, *pv and v both represent the same data item.

                          The address operator (&) and indirection operator(*) are unary operators and they are the members of the same precedence group as the other unary operators. The address operator (&) must act upon operands that associated with unique address, such as ordinary variable or single array element. Thus the address operators cannot act upon arithmetic expressions. The indirection operator can only act upon operands that are pointers (e.g., pointer variables).

Pointer declaration:

                            Pointer variables, like all other variables, must be declared before, they may be used in C program. When a pointer variable is declared, the variable name must be preceded by an asterisk(*). This identifies the fact that the variable is a pointer. The data type that appears in the declaration refers to the object of the pointer. i.e. the data item that is stored in the address represented by the pointer, rather than the pointer itself. Thus a pointer declaration may be written in general terms as :

Data-type *ptr;

Where ptr is the name of the pointer variable, and data-type refers to the data type of the pointer object.

For example, a C program contains the following declarations.
int i,*ptri;
float f,*ptrf;

                            The first line declares i to be an integer type variable and ptri to be a pointer variable whose object is an integer quantity. The second line declares f to be a floating-point type variable and ptrf to be a pointer variable whose object is a floating point quantity.

                            Within a variable declaration, a pointer variable can be initialized by assigning in the address of another variable, remember that the variable whose address is assigned to the pointer variable must have been declared earlier in the program, for example,

int i;
int *ptri=&i;

                            The first line declares i to be integer type variable and the second line declares ptri to be a pointer variable whose object is an integer point quantity. In addition, the address of i is initially assigned to ptri.

Related Links :

Standard C Library Functions in c programming language

Standard C Library Functions in c programming language | Important Library Functions in C | List of C Library Functions in c programming language


Features Found in the Libraries

# Function Name Type Library to which it belongs Syntax Description Example
1 abs(i) int stdlib.h int abs(int i); Returns the absolute value of i x = abs(-7) // x es 7
2 acos(d) double math.h double acos(double d); Returns the arc cosine of d angle = acos (0.5) / / returned is phi angle / 3
3 asin(d) double math.h double asin(double d); Returns the arc sine of d angle = asin (0.707) / / about phi / 4
4 atan(d) double math.h double atan(double d);
long double tanl(long double d);
Returns the arc tangent of d. Calculates the arc tangent of x. Requires library called complex.h angle atan (1.0) / / angle is phi / 4
5 atan(d1, d2) double math.h double atan(double d1, double d2); Returns the arc tangent of d1/d2 angle = atan (y, x)
6 atof(s) double stdlib.h double atof(const char *cadena) Convert string s to a double precision number. Requires llamda math.h library double x,
char * cad_dbl = "200.85" ...
x = atof (cad_dbl) / / convert the string "200.85" a real value
7 atoi(s) int stdlib.h int atoi(const char *cadena) Convert string s to an integer. The string must have the following format: [blank] [sign] [ddd] (still mandatory decimal digits). nt i, char * cad_ent = "123" ... i = atoi (cad_ent) / / converts the string "123" to integer 123
8 atol(s) long stdlib.h long atol(const char *cadena); Convert string s to a long integer. The string must have the following format: [blank] [sign] [ddd] (still mandatory decimal digits). long int i; char cad_ent = "9876543", ... i = atol (cad_ent) / / convert the string "9876543" to long integer
9 calloc(n, s) void(puntero) malloc.h y stdlib.h
o bien
alloc.h y
stdlib.h
void *calloc(size_t n, size_t s); Allocate memory for a formation of n elements, each of s bytes. Returns a pointer to the beginning of the reserved space. If enough space exists for the new block or we is 0, calloc returns null. long * buffer
buffer = (long *) calloc (40, sizeof (long));
10 ceil(d) double math.h double ceil(double d); Returns a value rounded up to the next higher integer rounding = ceil (5.1) / / rounding is 6
11 cos(d) double math.h double cos(double d);
complex cos(complex d);
Returns the cosine of d coseno_x = cos (1.6543)
12 cosh(d) double math.h double cos(double d);
complex cos(complex d);
Returns the hyperbolic cosine of d d = 1.00; printf ("d =% f \ n \ n, d);
13 difftime(11, 12) double time.h double difftime(time_t hora2, time_t hora1) Returns the time difference 11 (TIME2) - 12 (hour1), where 11 and 12 represent the time elapsed after a time base (see function time) time_t start, end; clrscrl (); start = time (NULL); delay (5000) end = time (NULL) print ("Difference in seconds:% f \ n", difftime (start, end));
14 exit(u) void stdlib.h void exit(int estado) Close all files and buffers and the program ends. The value of u is assigned by the function to indicate the completion status. exit(0);
15 exp(d) double math.h double exp(double d);
complex exp(complex d)
Raise e to the power d ( e = 2.7182818 ... is the base of natural logarithms system (neperian)) d = 100.00, y = exp (d) printf ("The exponential x =% f. \ n \ n", y);
16 fabs(d) double math.h double fabs(double d); Returns the absolute value of d y = fabs (-7.25) / / and is worth 7.25
17 fclose(f) int stdio.h int fclose(FILE *f); Close the file f. Returns 0 if the file was closed successfully. int fclose (FILE "file");
18 feof(f) int stdio.h int feof(FILE *f); Determines whether an end of file found. if so, returns a nonzero value, otherwise returns 0 feof (chips);
19 fgetc(f) int stdio.h int fgetc(FILE f); Read character from file f c + fgetc (fp)
20 fegts(s, i, f) char(puntero) stdio.h char *fgets(char s, int s, FILE *f); Reads a string s with characters i, f File fgets (caddemo, 80, fp);
21 floor(d) double math.h double floor(double d); Returns a value rounded down to nearest integer less x = floor (6.25) / / x is 6
22 fmod(d1, d2) double math.h double fmod(double d1, double d2); Returns the remainder of d1/d2 (with the same sign as d1) rest = fmod (5.0,2.0) / / rest equal to 1.0
23 fopen(s1, s2) file(puntero) stdio.h FILE *fopen(const char *s1, const char *s2) Opens a file named s1, s2 type. Returns a pointer to the file. *
Way Action
"R" Open for reading
"W" Opens an empty file for writing
"A" Opens for writing at end of file
"R+" Open for reading / writing
"W+" Opens an empty file for read / write
"A+" Open for reading and add
"Rb" Open a binary file for reading.
"Wb" Open a binary file for writing
"Ab" Open a binary file to add
"Rb+" Open a binary file for read / write.
"Wb+" Open a binary file for read / write
"Ab+" Open or create binary file for read / write
if ((corriente2 = fopen ("data", "W +"))== NULL printf ("File not opened ... \ n");
24 fprintf(f, ...) int stdio.h int fprintf(FILE *f, const char *formato [,arg,...]); Escribe datos en el archivo f (el resto de los argumentos fprintf(f1, "El resultado es %f\n",result);
25 fputc(c, f) int stdio.h int fputc(int c, FILE *f); Escribe un caracter en el archivo f fputc(*(p++), stdout);
26 fputs(s, f) int stdio.h int fputs(const char *cad, FILE *f) Escribe una cadena de caracteres en el archivo f fputs("esto es una prueba", f1);
27 fread(s, i1, i2, f) int stdio.h size_t fread(void *b, size_t t, size_t n, FILE *f); Lee i2 elementos, cada uno de tamano i1 bytes, desde el archivo f hasta la cadena s fread(buf, strlen(msg)+1, 1, flujo);
28 free(p) void malloc.h o stdlib.h void free(void *dir_memoria); Libera un bloque de memoria reservada cuyo principio esta indicado por p. char *cad;
// asignar memoria a la cadena
cad=(char *)malloc(50);
...
free(cad); // liberar memoria
29 fscanf(f, ...) int math.h int fscanf(FILE *f, const char *formato, [, direccion,... ]); Lee datos del archivo f ( el resto de los argumentos fscanf(flujo, %s%f, cad, &f);
30 fseek(f, l, i) int stdio.h int fseek(FILE *f, long desplaza, int origen); Mueve el puntero al archivo f una distancia de 1 bytes desde la posicion i (i puede representar el principio del archivo, la posicion actual del puntero o el fin del archivo.
Notas
Origen Significado
SEEK_SET Principio de archivo
SEEK_CUR Posicion actual puntero
SEEK_END Final del archivo
fseek(f1,OL,SEEK_SET); // ir al principio
31 ftell(f) long int stdio.h long int ftell(FILE *f); Devuelve la posicion actual del puntero dentro del archivo f ftell(fichen)
32 fwrite(s, i1, i2, f) int stdio.h size_t fwrite(const void *p, size_t i1, size_t i2, FILE *f); Escribe i2 elementos, cada uno de tamano 1 bytes, desde la cadena s hasta el archivo f num=fwrite(lista,sizeof(char),25,flujo);
33 getc(f) int stdio.h int getc(FILE *f); Lee un caracter del archivo f while(c=getc(fx) !=EOF {
print ("%c",c);
}
34 getchar( ) int stdio.h int getchar(void); Lee un caracter desde el dispostivo de entrada estandar int c;
while((*c=getchar()) != '\n')
print ("%c",c);
35 gets(s) char(puntero) stdio.h char *gets(char *cad); Lee una cadena de caracteres desde el dispositivo de entrada estandar gets(nombre);
36 isalnum(c) int ctype.h int isalnum(int c); Determina si el argumento es alfanumerico. Devuelve un valor disitinto de cero si es cierto; en otro caso devuelve 0 carac=getch();
if (isalnum(carac))
print("%c letra|digito \n",carac);
else
printf("%c no letra|digito \n", carac);
37 isalpha(c) int ctype.h int isalpha(int c); Determina si el argumento es alfabetico. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0. int c;
if (isalpha(c)) printf("%c es letra\n",c);
38 isascii(c) int ctype.h int isascii(int c); Determina si el argumento es un caracter ASCII. Devuelve un valor disitinto de cero si es cierto; en otro caso devuelve 0 int c;
if (isascii(c)) printf('%c es un ascii\n",c)
39 iscntrl(c) int ctype.h int isacntrl(int c); Determina si el argumento es un caracter ASCII de control. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0 if(iscntrl(c)) printf"%c es un caracter de control\n",c);
40 isdigit(c) int ctype.h int isdigit(int c); Determina si el numero es un digito decimal. Devuelve un valor disitinto de cero si es cierto; en otro caso devuelve 0 if(isdigit(c)) printf"%c es un digito\n",c);
41 isgraph(c) int ctype.h int isgraph(int c); Determina si el argumento es un caracter ASCII grafico (hex 0x21 -0x7e; octal 041 -176). Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0 if(isgraph(c)) printf"%c es un caracter imprimible(no espacio)\n",c);
42 islower(c) int ctype.h int islower(int c); Determina si el argumento es ua minuscula. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0 if(islower(c)) printf"%c es una letra minuscula\n",c);
43 isodigit(c) int ctype.h int isodigit(int c); Determina si el argumento es un digito octal. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0 if(isodigit(c)) printf"%c es un digito octal\n",c);
44 isprint(c) int ctype.h int isprintint c); Determina si el el argumento es un caracter ASCII imprimible (hex 0x20 -0x7e; octal 040 -176). Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0 if(isprint(c)) printf("\n"c imprimible\n",c);
45 ispunct(c) int ctype.h int ispunct(int c); Determina si el argumento es un caracter de puntuacion. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0 if(ispunct(c)) printf"%c es un caracter de puntuacion\n",c);
46 isspace(c) int ctype.h int isspace(int c); Determina si el argumento es un espacio en blanco. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0 if(isspace(c)) printf"%c es un espacio\n",c);
47 isupper(c) int ctype.h int isupper(int c); Determina si el argumento es una mayuscula. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0 if(isupper(c)) printf"%c es una mayuscula\n",c);
48 isxdigit(c) int ctype.h int isxdigit(int c); Determina si el argumento es un digito hexadecimal. Devuelve un valor distinto de cero si es cierto; en otro caso devuelve 0 ifisxdigit(c)) print"%c es un digito hexadecimal\n",c)
49 labs(l) long int math.h long int labs(long int l); Devuelve el calor absoluto de 1 long lx=-51654,ly;
ly=labs(lx);
50 log(d) double math.h double log(double d); Devuelve el logaritmo natural de d hdouble x,y;
x=10;
y=log(x);
51 log10(d) double math.h double log10(double d); Devuelve el logaritmno (en base 10) de d hdouble x,y;
x=10;
y=log10(x);
52 malloc(u) void(puntero) stdlib.h void *malloc(size_t u); Reserva u bytes de memoria. devuelve un puntero al principio del espacio reservado cadena=malloc(MAX_CHR);
53 pow(d1, d2) double math.h double pow(double d1, double d2); Devuelve d1 elevado a la potencia d2 double x=2.0, y=4.0, z;
z=pow(x,y); //z sera 1.60
54 printf(...) int stdio.h int printf(const char *formato[,argumento,...]); Escribe datos en dispositivo de salida estandar.
Codigo Formato
%c Caracter
%d Entero Decimal
%e Real (double o float), notacion cientifica.
%f Coma flotante
%s Cadena de caracteres
%x Hexadecimal sin signo
print("producto %d y %d es %d\n",x,y,x*y);
55 putc(c, f) int stdio.h int putc(int c, FILE *f); Escribe un caracter en el archivo f putc('*',demo);
56 putchar(c) int stdio.h int putchar(int c); Escribe un caracter en el dispositivo de salida estandar putchar('B');
57 puts(s) int stdio.h int puts(const char *cad) Escribe una cadena de caracteres en el dispositivo de salida estandar puts("Desea continuar (s/n);
58 rand( ) int stdlib.h int rand(void); Devuelve un entero positivo aleatorio // visualizar 10 numeros aleatorios for (i=0;i<10;i++)
printf("%6d\",rand());
59 rewind(f) void stdio.h void rewind(FILE *f); Mueve el puntero al principio del archivo f rewind(fx);
60 scanf(...) int stdio.h int scanf(const char *formato {,direccion,...]); Lee datos en dispositivo de entrada estandar
Codigo Formato
%c Caracter
%d Enetero Decimal
%x Hexadecimal
%i Entero Decimal
%f Numero Real
%o Octal
%p Puntero
%s Cadena
scanf('%d %f %c %s, &i, &fp, &c, s);
61 sin(d) double math.h double sin(double d); Devuelve el seno de d double x, y;
x=0.52;
printf('x =%f radianes\n",x);
y=cos(x);
printf("el coseno de x =%f\n",y);
62 sinh(d) double math.h double sinh(double d); Devuelve el seno hiperbolico de d y=sinh(x);
63 sqrt(d) double math.h double sqrt(double d); Devuelve la raiz cuadrada de d printf("%lf",sqrt(25.0); //se visualiza 5
64 srand(u) void stdlib.h void srand(unsigned u); Inicializa el generador de numeros aleatorios srand(semilla);
65 strcmp(s1, s2) int string.h int strcmp(const char*s1, const char *s2); Compara dos cadenas de caracteres lexicograficamente. Devuelve un valor negativo si s1 < s2; 0 si s1 y s2 son identicas; y un valor positivo si s1 > s2 i=strcmp("MNP", "mnp"); // resultado < 0
i=strcmp("abc", "abc"); // resultado = 0
i=strcmp("xy", "abc"); // resultado > 0 char s1[80]="Mayo";
char s2[80]="Octubre";
int j;
j=strcmp(s1,s2);
66 strcmpi(s1, s2) int string.h int strcmpi(const char*s1, const char *s2); Compara dos cadenas de caracteres lexicograficamente, sin diferenciar mayusculas de minusculas. Devuelve un valor negativo si s1 < s2; 0 si s1 y s2 son identicas; y un valor positivo si s1 > s2 v=strcmpi(s1,s2);
67 strcpy(s1, s2) char string.h char *strcpy(char s1, const char s2); Copia la cadena de caracteres s2 en la cadena s1
char *s1="Pepe Luis";
char b[12];
strcpy(s2,s1);
cout <
68 strlen(s) int string.h size_t strlen(const char *s); Devuelve el numero de caracteres de una cadena
longitud=strlen(nombre);
char s[81]="Cadena demo';
printf("La longitud de s es: %d\n" strlen(s));
69 strset(c, s) char(puntero) string.h char *strset(char *cad, int c); Pone todos los caracteres de s a c (excluyendo el caracter nulo del final \0) char *cad="----";
strset (cad,'x'); // cad es ahora xxxx
70 system(s) int string.h system(comd); Pasa la orden al sistema operativo. Devuelve cero si la orden se ejecuta correctamente; en otro caso devuelve un valor distinto de cero, tipicamente -1. system(dir);
71 tan(d) double math.h double tan(double d); Devuelve la tangente de d y=tan(x);
72 tanh(d) double math.h double tanh(double d); Devuelve la tangente hiperbolica de d a=tanh(x);
73 time(p) long int time.h time_t time(time_t *h); Devuelve el numero de segundos transcurridos despues de un tiempo base designado time(&hora);
74 toascii int ctype.h int toascii(int c); Convierte el valor del argumento a ASCII c=toascii(entero);
75 tolower int ctype.h o stdlib.h int tolower(int c); Convierte una letra a minuscula c=tolower('s'); //c se convierte en 's'
76 toupper int ctype.h o stdlib.h int toupper(int c); Convierte una letra a mayuscula c=toupper('s'); //c se convierte en 'S'



Related Links :

Dynamic memory allocation| Calloc, Malloc in C Language | DMA, Calloc, Malloc, reallocin C Language

Dynamic memory allocation| Calloc, Malloc in C Language | DMA, Calloc, Malloc, reallocin C Language



we do not release the user to create different variables according to their interest. It's a bit difficult to explain well, so give an example: imagine you want to do a text encoder, you do not know how much space you will need in memory until the user gets the text, which can be a word or an entire book. The solution is to put a rookie char [10000], but even so we can be short, and if you have to decode a word, it goes up too much space. We need to change the variables and create them according to what happens, right? That is what this lesson.

                 ie, Dynamic memory allocation is the practice of assigning memory locations to variables during execution of the program by explicit request of the programmer. Dynamic allocation is a unique feature to C (amongst high level languages). It enables us to create data types and structures of any size and length to suit our programs need within the program.

                 For example, to use arrays, dynamic memory allocation and use, eliminating the need to determine the size of the array at declaration time. What do I say it is that extra space does not have to. Areas that could use up to 1000 minutes, but you know, actually do not know how much is used, the worst case, might well end up without one. In such cases, to specify precisely the number of elements in the declaration is a very difficult time. If too much waste of memory, and the less accessible outside of the array, may result in an error.

                 Dynamically allocated memory is freed when finished should not be used without. When released, this area no longer use that system to manage memory (OS) and I'll tell it to. When you exit the program without a release, essentially freed automatically. But I say with certainty, it should be freed by calling a dedicated function explicitly.

                 Finally, the dynamically allocated memory area, the area is secured in a location different from the usual definition of a variable. There is also the name depending on the role of memory space and just go. Used in the dynamic memory allocation area is called the heap. In contrast, the variables are usually allocated to the location of the stack. Variables are allocated on the heap, even if it was secured out of the scope, continues to exist. For example, in function, if you create a dynamic variable, but missing out the function and will continue to exist on the heap.

                  The functions malloc (), realloc (), calloc () and free (), the Library functions stdlib.h, malloc.h or are responsible for this task. All data are stored in the free store (heap), which is limited to 64k a stack in the beginning, this varies from machine. All variables were declared so far on the stack, now you tell me where to go, in an indirect way.

Related Links :

Converting Degree to Radian

C Program to Converting Degree to Radian | Degree to Radian conversion in C | Degree to Radian Changing in C language | Program to Degree to Radian conversion C


#include
#include
#include
#include

int main()
{
float a, b, c, d;
char s; 

printf("Enter Degrees: ");
scanf("%f", &a);
printf("Enter Minutes: ");
scanf("%f", &b);

c=((b/60)+a)*(3.1416/180);

printf("\nThe radians is %.0f", c);

printf("\n\nPress y to continue and x to exit: ");
scanf("%s", &s);
if(s=='y') {
system("cls");
return main();
getch();
}
if(s=='x')
{
return 0;
}}


Related Links :

C Program to print number of days in given Month

C Program to print number of days in given Month  | Number of days in given month | Switch case Months Days Calculator | decision control basic example Calendar in C

#include
#include

main()
{
int mon;

printf("Enter number ( 1 - 12 ): ");
scanf("%d",&mon);

switch(mon)
{
case 1:
printf("January has 31 days");
break;
case 2:
printf("February has 28 days");
break;  
case 3:
printf("March has 31 days");
break;  
case 4:
printf("April has 30 days");
break;  
case 5:
printf("May has 31 days");
break;  
case 6:
printf("June has 30 days");
break;  
case 7:
printf("July has 31 days");
break;
case 8:
printf("August has 31 days");
break;   
case 9:
printf("September has 30 days");
break;  
case 10:
printf("October has 31 days");
break;  
case 11:
printf("November has 30 days");
break;  
case 12:
printf("December has 31 days");
break;  
                 default:
printf("INVALID INPUT! ");
}
getch();
}





Related Links :

C Program to find area of circle, triangle and square

C Program to find area of circle, triangle and square  | Area of circle in C | Area of triangle in C


#include
#include
#include
main()
{
int n1;
int sum;
int a,b,c;
char y,s;

printf("Enter Operation To be Used: \n");
printf("(1=circle   2=Triangle   3=Square): ");
scanf("%d",&n1);



float pi;

switch(n1)
{
case 1:

float rad;
printf("\n\nArea Of a Circle!");
printf("\nEnter radius: ");
scanf("%f",&rad);

float areac;
areac = (3.14) * (rad * rad);

printf("The Area of a circle is %.2f",areac);
break;  




case 2:          

int base,he,areat;

printf("\n\nArea Of a Triangle!");
printf("\nEnter base: ");
scanf("%d",&base);
printf("Enter height: ");
scanf("%d",&he);

areat = (base * he)/(2);

printf("The Area of a triangle is %d",areat);
break;




case 3:     
int side,areas;
printf("\n\nArea Of a Square!");
printf("\nEnter side: ");
scanf("%d",&side);


areas = side * side;

printf("The Area of a Square is %d",areas);
break;
}        
if(n1>=4)
{
printf("\nInvalid Input!");

}      

printf("\n\nPress Y to repeat and N to end:\n");
scanf("%s",&s);
if(s=='y'){
system ("cls");
return main();        
getch();
}

if (s=='y')
{
return 0;
}}




Related Links :

C Program to Converting Fraction to Decimal

C Program to Converting Fraction to Decimal | Fraction to Decimal Conversion in C | C Assignment to convert given Fraction to Decimal



#include
#include

main()
{
float n1,n2;
char letter;
float convert;
printf("Enter Fractions: ");
scanf("%d%c%d",&n1,&letter,&n2);
convert = n1/n2;
printf("\nThe value into decimal is %.1f",convert);
getch();
}



Related Links :

TO CHECK WHETHER THE GIVEN STRING IS PALINDROME

TO CHECK WHETHER THE GIVEN STRING IS PALINDROME | Program to check Palindrome Sentence | String is Palindrome or Not | C Language Program to find Palindrome String




#include
#include
int stpal(char str[50]);
void main()
{
       char str[50];
       int pal;
       clrscr();
       printf("\n\n\t ENTER A STRING...: ");
       gets(str);
       pal = stpal(str);
       if(pal)
              printf("\n\t THE ENTERED STRING IS A PALINDROME");
       else
              printf("\n\t THE ENTERED STRING IS NOT A PALINDROME");
       getch();
}
int stpal(char str[50])
{
       int i = 0, len = 0, pal = 1;
       while(str[len]!='\0')
             len++;
       len--;
       for(i=0; i< len/2; i++)
       {
             if(str[i] == str[len-i])
                    pal = 1;
             else
             {
                    pal = 0;
                    break;
             }
       }
       return pal;
}


Related Links :

C Program TO REVERSE THE GIVEN STRING

C Program TO REVERSE THE GIVEN STRING | reverse the string in C | Reverse Sentence in C Language




#include
#include
void strev(char str1[50], char str2[50]);
void main()
{
          char str1[50], str2[50];
          clrscr();
          printf("\n\n\t ENTER A STRING...: ");
          gets(str1);
          strev(str1,str2);
          printf("\n\t THE REVERSED STRING IS...: ");
          puts(str2);
          getch();
}
void strev(char str1[50], char str2[50])
{
          int i = 0, len = 0, r = 0;
          while(str1[len]!='\0')
                 len++;
          for(i=len-1; i>=0; i--)
          {
                 str2[r] = str1[i];
                 r++;
          }
          str2[r] = '\0';
}


Related Links :

C Program to reverse a given number | Reverse the given Number in C

C Program to reverse a given number | Reverse the given Number in C





#include
#include
void main()
{
     long int num, rev = 0, dig;
     clrscr();
     printf("\n\n\t ENTER A NUMBER...: ");
     scanf("%ld", &num);
     while(num>0)
     {
          dig = num % 10;
          rev = rev * 10 + dig;
          num = num / 10;
     }
     printf("\n\t REVERSED NUMBER IS...: %ld", rev);
     getch();
}

Related Links :


If you face any Problem in viewing code such as Incomplete "For Loops" or "Incorrect greater than or smaller" than equal to signs then please collect from My Web Site CLICK HERE


More Useful Topics...

 

History Of C..

In the beginning was Charles Babbage and his Analytical Engine, a machine
he built in 1822 that could be programmed to carry out different computations.
Move forward more than 100 years, where the U.S. government in
1942 used concepts from Babbage’s engine to create the ENIAC, the first
modern computer.
Meanwhile, over at the AT&T Bell Labs, in 1972 Dennis Ritchie was working
with two languages: B (for Bell) and BCPL (Basic Combined Programming
Language). Inspired by Pascal, Mr. Ritchie developed the C programming
language.

My 1st Program...


#include
#include
void main ()
{
clrscr ();
printf ("\n\n\n\n");
printf ("\t\t\t*******Pankaj *******\n");
printf ("\t\t\t********************************\n");
printf ("\t\t\t\"Life is Good...\"\n");
printf ("\t\t\t********************************");
getch ();
}

Next Step...


#include
#include

void main ()
{
clrscr ();
printf ("\n\n\n\n\n\n\n\n");
printf ("\t\t\t --------------------------- \n\n");

printf ("\t\t\t | IGCT, Info Computers, INDIA | \n\n");
printf ("\t\t\t --------------------------- ");

getch ();

}

Hits!!!