10/05/2016

C program



About C language
C is a general-purpose, high-level language.It was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs.

 The first publicly available description of C is produced by Brian Kernighan and Dennis Ritchie which is recently known as the K&R standard.
Characteristics of C
  • It is a highly structured language.
  • It uses features of high lavel laguage.
  • It can handle bit-level operation.
  • C is a machine independent language.
  • It supports dynamic memory management (using pointer).
Keywords
Keywords(reserved words),are the special words reserved by C.The number of keywords supported by C varies depending on the version of C.Generally 32 keywords are supported by C which are as follows:

auto             else             long            switch
break           else if         char            const
extern          float            for               goto
if                  default       double         do
continue     Return       register        int
signed        sizeof         static           Short
unsigned    struct         typedef       then
union          volatile       while           void
C Programs
A C program can vary from 3 lines to thausands-millions of lines It should be written into one or more text files.C programming extension is ".c".For example, hello.c. We can use "vi", "vim" or any other text editor to write C program into a file.

FORMATE
#include<stdio.h>
#include<conio.h>
void main()
{
--------
--------
----------
getch()
     }
data types
int    float    double    char
Size of data types
Following program shows the memory size of data types:
#include<stdio.h>
#include<limits.h>
int main()
{
   printf("Storage size for int : %d \n", sizeof(int));
    printf("Storage size for float : %d \n", sizeof(float));
    printf("Storage size for char : %d \n", sizeof(char));
    printf("Storage size for double : %d \n", sizeof(double));
   return 0;
    }
Output:
Storage size for int : 4
Storage size for float : 4 
Storage size for char : 1
Storage size for double : 8

C plus plus programming

SOMETHING ABOUT C++

DATA TYPES:-
char
int
float
double
void
bool
DATA TYPE MODIFIERS:-
signed
unsigned
long
short
Identifiers
hello_world
_abc
DEFINE
Reserved Words(Keywords)

  • Variable Declaration Words:-

char
double 
float

  • Statements Words:-

break
else
if 
case

  • Storage Allocation Identifier

const
volatile
static
void

Basic structure of C++ program

 The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program which simply prints "myeasycprogram" to your computer screen. Although it is very simple, it contains all the fundamental components of C++ programs :

// my first program in C++
#include <iostream>

int main()
{
  std::cout << "myeasycprogram";
}

Output:
myeasycprogram


Description of this program line by line:

 Line1:// my first program in C++
Lines beginning with two slash signs (//) are comments by the programmer and have no effect on the behavior of the program. Programmers use them to include short explanations or observations concerning the code or program. 

 Line2:#include <iostream>
Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor. They are special lines interpreted before the compilation of the program itself begins. In this case, the directive #include <iostream>, instructs the preprocessor to include a section of standard C++ code, known as header iostream, that allows to perform standard input and output operations, such as writing the output of this program to the screen.

Line3:A blank line.
Blank lines have no effect on a program. They simply improve readability.

Line 4: int main ()
This line initiates the declaration of a function. Essentially, a function is a group of code statements which are given a name: in this case, this gives the name "main" to the group of code statements that follow. 

The function named main is a special function in all C++ programs; it is the function called when the program is run. The execution of all C++ programs begins with the main function regardless of where the function is actually located within the code.

Lines 5 and 7: { and }
The open brace ({) at line 5 indicates the beginning of main's function definition, and the closing brace (}) at line 7, indicates its end. Everything between these braces is the function's body that defines what happens when main is called. All functions use braces to indicate the beginning and end of their definitions.

Line 6: std::cout << "myeasycprogram";
This line is a C++ statement. A statement is an expression that can actually produce some effect. It is the meat of a program, specifying its actual behavior. Statements are executed in the same order that they appear within a function's body.

Now we can also write the program as follows:

#include<iostream>
using namespace std;

int main()
{
cout<<"myeasycprogram";
}

Output:
myeasycprogram


C++ basic












Topics and Examples

 C PROGRAM

 C basic

• if else

• for loop

• while loop

• do-while loop

• switch case

• arrays


•  pointer

• file in C

Matrix


• question bank


C++ PROGRAM












NUMERICAL METHOD AND COMPUTATIONAL TECHNIQUE


*Calculator
*Prime number
*Calculate number of vowels
*Factorial of a number
*Armstrong number
*Fibonacci series
*Harmonic series
*Even numbers series
*Piramid structure
*Floyd's triangle
*Temparature conversion

*Make a analog clock
*Draw ranbow




PRIVACY AND POLICY OF MY BLOG
This blog does not share personal information with third parties nor do i store any information about your visit to this blog.

I am not responsible for republished content from this blog on other blogs or websites without my permission.

This privacy policy is subject to change without notice and was last updated on Month, Day, Year. If you have any questions feel free to comment.


Please post comment.Also you can post programming related problems.





File in C

What is file?

A file is a collection of data.The data includes text,symbols and numbers.

C support the file handling  mechanism.

Opening a file

You can use the fopen( ) function to create a new file or to open an existing file. Following is the syntax for opening a file:

FILE  *fptr;
FILE = fopen("file_name", "opening mode" );

Following are the different opening mode of a file:

Mode   Description
r    Opens an existing text file
            for reading purpose.
w    Opens a text file for writing
            purpose.
a    Opens a text file for appending
            purpose.
r+    Opens a text file for reading
            and writing both(must exit)
w+    Opens a text file for reading
            and writing both.
a+    Appends a text file for reading
            and writing both.

If you want to handle binary files then you will use below mentioned access modes instead of the above mentioned:
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing a File

To close a file, use the fclose( ) function. The general syntax for closing a file is as follows:

  fclose( fptr)

Writing a File

Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );
You can use the following functions to write a null-terminated string to a stream:
int fputs( const char *s, FILE *fp );


1.Following program includes open read and close file operation:

#include<stdio.h>
#include<conio.h>
void main()
{
FILE  *fptr;
char array[100];
fptr = fopen("program.txt", "r");
fgets(array,sizeof(array),fptr);
fclose(fptr);
printf("%s",array);
getch();
}

2.This program includes how to create a file and write some data into the file.

#include <stdio.h>
#include<conio.h>
int main()
{
 FILE *fp;
 file = fopen("file.txt","w");
 /*Create a file and add text*/
 fprintf(fp,"%s","This is an example line:");
 fclose(fp);
 return 0;
}

3.Following program shows the use of fputs() function:
#include <stdio.h>
#include<conio.h>
int main()
{
   FILE *fp;

   fp = fopen("test.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
return 0;
}


4.Following C program shows how to copy a file.

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

int main()
{
  char ch, source_file[20], target_file[20];
  FILE *source, *target;

  printf("Enter name of file to copy\n");
  gets(source_file);

  source = fopen(source_file, "r");

/* if file not found then exit*/
  if( source == NULL )
  {
  printf("Press any key to exit...\n");
  exit(EXIT_FAILURE);
  }

  printf("Enter name of target file\n");
  gets(target_file);

  target = fopen(target_file, "w");

/*opening file in write mode*/
/* if file not found then exit*/
  if( target == NULL )
  {
  fclose(source);
  printf("Press any key to exit...\n");
  exit(EXIT_FAILURE);
  }

  while( ( ch = fgetc(source) ) != EOF )
  fputc(ch, target);
/* appending each character from file1 to target file*/

  printf("File copied successfully.");

/*closing both files*/
  fclose(source);
  fclose(target);

  return 0;
}

Output:
Enter name of file to copy
add.c
Enter name of target file
subtraction.c
File copied successfully.


5.A C program to merge two files.

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

int main()
{
  FILE *fs1, *fs2, *ft;

  char ch, file1[50], file2[50], file3[50];

  printf("Enter name of first file:\n");
  gets(file1);

  printf("Enter name of second file:\n");
  gets(file2);

  printf("Enter name of file which will store contents of two files:\n");
  gets(file3);

  fs1 = fopen(file1,"r");
  fs2 = fopen(file2,"r");

/*if file not found then exit*/
  if( fs1 == NULL || fs2 == NULL )
{
  perror("Error ");
  printf("Press any key to exit...\n");
  getch();
  exit(EXIT_FAILURE);
}

ft = fopen(file3,"w");
/* Opening file in write mode*/

/*if file not found then exit*/
if( ft == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}

while( ( ch = fgetc(fs1) ) != EOF )
fputc(ch,ft);
/* appending cotents of file1 to resultant file*/

while( ( ch = fgetc(fs2) ) != EOF )
fputc(ch,ft);
/* appending cotents of file2 to resultant file*/

printf("Two files were merged into %s file successfully.\n",file3);

fclose(fs1);
fclose(fs2);
fclose(ft);

return 0;
}

Output:
Enter name of first file
add.c
Enter name of second file
mul.c
Enter name of file which will store contents of two file
addmul.c
Two files were merged into addmul.c file successfully.



6.A C program to print the source code of program.

#include<stdio.h>
int main()
{
FILE *fp;
char ch;

fp = fopen(__FILE__, "r");

do {
ch = getc(fp);
putchar(ch);
} while (ch != EOF);

fclose(fp);
return 0;
}

Output is same as the source code.


7.A C program shows how to delete a file.

#include<stdio.h>

main()
{
  int status;
  char file_name[25];

  printf("Enter the name of file you wish to delete\n");
  gets(file_name);

  status = remove(file_name);
/*remove() will delete specified file and returns 0 if file deleted*/

  if( status == 0 )
  printf("%s file deleted successfully.\n",file_name);
  else
  {
  printf("Unable to delete the file\n");
  perror("Error");
  }

  return 0;
}

_________________________




Operators in C

Operators in C
One of the most important features of C is that it has a very rich set of built in operators including arithmetic, relational, logical, and bitwise operators.
Arithmetic operators
Arithmetic operators are used for mathematical calculations like addition (+), subtraction(-), multiplication (*), division (/), and modulus (remainder) (%).
Example :

#include<stdio.h>
int main()
{
    int num1,num2;
    int add,sub,mul,div,mod;

    printf("\nEnter First Number :");
    scanf("%d",&num1);

    printf("\nEnter Second Number :");
    scanf("%d",&num2);

    add = num1 + num2;  //(+) operator
    printf("\nAddition is : %d",add);

    subs = num1 - num2;  //(-) operator
    printf("\nSubtraction is : %d",subs);

    mul = num1 * num2;  //(*)operator
    printf("\nMultiplication is : %d",mul);

    div = num1 / num2;  //(÷) operator
    printf("\nDivision is : %d",div);

    mod = num2 % num1;  //(%) operator
    printf("\nModulus is : %d",mod);

    return(0);
}

Output

    Enter First Number : 10
    Enter Second Number : 2
    Addition is : 12
    Subtraction is : 8
    Multiplication is : 20
    Division is : 5
    Modulus is : 2
Assignment operator
Assignment operator is used to assign value to an variable.
Example : a = b. Assigns values from right side operands to left side operand.
Assignment operator is binary operator which operates on two operands (variable).
Example :

#include<stdio.h>
#include<conio.h>
int main()
{
    int a;
    // variable a is assigned integer value 55
    a = 55;

    return (0);

}
Shorthand assignment operators
In addition, C has a set of shorthand assignment operators of the form.
var oper = exp;
Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator oper = is known as shorthand assignment operator
For Example
x + = 10 is same as x = x + 10
Similarly for  -=, *=,  /=, %=, etc.

These shorthand operators improve the speed of execution as they require the expression, the variable x in the above example, to be evaluated once rather than twice.
Relational operators
Relational operators are used to compare the value of two variables.
Operators                Operator Use
    ==  check value of 2 variable                            are equa
    !=       check value of 2 variable
              are equal or not
    >       check is value is greater than
    >=  check is value is greater                             than or equal to
    <      check value is less than
    <=     check value is less than
              or equal to
Example :


#include <stdio.h>

int main()
{
    int x = 21;
    int y= 10;
    int z ;
       if( x == y ) //use of  == operator
    {
        printf("x is equal to y\n" );
    }
    else
    {
        printf("x is not equal to y\n" );
    }
     if ( x < y )  // use of < operator
    {
        printf("x is less than y\n" );
    }
    else
    {
        printf("x is not less than y\n" );
    }
      if ( x > y ) // use of > operator
    {
        printf("x is greater than y\n" );
    }
    else
    {
        printf("x is not greater than y\n" );
    }

    // Lets change value of x and y
    x = 5;
    y = 20;
    if (x <= y ) // use of <= operator
    {
    printf("x is either less than or equal to y\n" );
    }

if ( x >= y)  // use of >= operator
    {
        printf("x is either greater than  or equal to y\n" );
    }

    return 0;
}

Output :

    x is not equal to y
    x is not less than y
    x is greater than y
    x is either less than or equal to y
    x is either greater than  or equal to y
Logical operators
Logical operators are used to perform logical operations on the given two variables.
Logical operators :

Operator Usage
&& expr1 && expr2
|| expr1 || expr2
! !expr1
Logical operator chart :
OperatorCondition1Condition2Result
&&                 True True True
                        True False False
                       False True False
                       False False False
||                 True True True
                        True False True
                       False True True
                       False False False
!                True  -         False
                       False -         True

Example:
  • (a == 5) && (b < 5) = false
    /*
        here, first expression a == 5 is true
              second expression b < 5 is false
        so, final result of && operator is false
        (True && False = False)
    */

(a == 4) && (b < 15) = false
(a == 5) && (b < 15) = true
(a == 4) && (b < 5) = false

(a == 5) || (b < 5) = true
(a == 4) || (b < 15) = true
(a == 4) || (b < 5) = false

!(a == 5) = false
!(a == 4) = true
Increment operator
Increment operator (++) increases the value of its operand by 1
Decrament perator
Decrement operator (--) decreases the value of its operand by 1
Example :


Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of bits from right to left. Bitwise operators are not applied to float or double.
Operator Description
      & Bitwise AND
      | Bitwise OR
      ^ Bitwise XOR
     << Left shift
      >> Right shift

Explanation :
& (Bitwise AND) - The Bitwise AND will take pair of bits from each position, and if only both the bit is 1, the result on that position will be 1. Bitwise AND is used to Turn-Off bits.
    int a = 10;
    int b = 12;
    int c = a & b;
Calculation :
            bit
a =    1010
b =  & 1100
       ----------
c =    1000
       ----------
value of c = 8;
| (Bitwise OR) - The Bitwise OR, will take pair of bits from each position, and if any one of the bit is 1, the result on that position will be 1 else 0.
    int a = 10;
    int b = 12;
    int c = a | b;

Calculation :
            bit
 a =    1010
 b =  | 1100
       ----------
c =    1110
       ----------
value of c = 14;
^ (Bitwise XOR) - The Bitwise XOR will take pair of bits from each position, and if both the bits are different, the result on that position will be 1. If both bits are same, then the result on that position is 0.


    int a = 10;
    int b = 12;
    int c = a ^ b;

Calculation :
            bit
a =    1010
b =  ^ 1100
       ----------
c =    0110
       ----------
value of c = 6;
<< (Left shift) - Left shift operator will shift the bits towards left for the given number of times.


    int a = 6;
    int b = a << 2;

Calculation :
    a = 6
    Position 7 6 5 4 3 2 1
    6 in bit 0 0 0 0 1 1 0
    Shifting 2 bit to left
    Position 7 6 5 4 3 2 1
    Result   0 0 1 1 0 0 0
     value of b = 24;
>> (Right shift) - Right shift operator will shift the bits towards right for the given number of times.


    int a = 6;
    int b = a >> 2;

Calculation :
    a = 6
    Position 7 6 5 4 3 2 1
    6 in bit 0 0 0 0 1 1 0
    Shifting 2 bit to right
    Position 7 6 5 4 3 2 1
    Result   0 0 0 0 0 0 1
     value of b = 1;
Ternary operator
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
Syntax :


    (condition) ? expression1 : expression2
If condition is true expression1 is evaluated else expression2 is evaluated. Expression1/Expression2 can also be further conditional expression.

Example :


#include <stdio.h>

int main()
{
    int a = 5;
    char c;

    //Example 1
    // condition ? expression1 : expression2
    c = (a < 10) ? 'S' : 'L';
    printf("C = %c",c);

    //Example 2
    // condition ? ( condition ? expression1 : expression2 ) : expression2
    c = (a < 10) ? ((a < 5) ? 's' : 'l') : ('L');
    printf("\nC = %c",c);

    return 0;
}

Output :

    C = S
    C = l
Explanation :

//Example 1
    c = (a < 10) ? 'S' : 'L';
This means, if (a < 10), then c = S else c = L

//Example 2
    c = (a < 10) ? ((a < 5) ? 's' : 'l') : ('L');
This means, if (a < 10), then check one more conditions if(a < 5), then c = s else l, else c = L.
The comma operator
The comma operator has left-to-right associativity. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before the right operand is evaluated.
The comma operator is mainly useful for obfuscation.
The comma operator allows grouping expression where one is expected.
Commas can be used as separators in some contexts, such as function argument lists.
Example :

#include <stdio.h>
int main ()
{
    int i = 10, b = 20, c= 30;

    // here, we are using comma as separator
    i = b, c;

    printf("%i\n", i);

    // bracket makes its one expression.
    // all expression in brackets will evaluate but
    // i will be assigned with right expression (left-to-right associativity)
    i = (b, c);
    printf("%i\n", i);

    return 0;
}
Output :

    20
    30
Cast operator
Cast operator can be used to explicitly convert the value of an expression to a different data type
Two Types of Cast

Implicit Cast
Explicit cast
Implicit Cast -
Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler.

Explicit Cast -
Explicit type conversion is a type conversion which is explicitly defined within a program (instead of being done by a compiler for implicit type conversion).

Lower DataType to Higher DataType are converted implicitly
Higher DataType to Lower DataType are converted explicitly
Example :

#include <stdio.h>

int main()
{
    int i   = 10;
    float f = 3.147;

    printf("The integer is: %d\n", i);
    printf("The float is:   %f\n", f);

    //implicit conversion
    f = i;
    printf("Implicit conversion int to float :   %f\n", f);

    //explicit conversion
    i = (int) f;
    printf("Explicit conversion float to int :   %d\n", i);

    return 0;
}
Output :

 The integer is: 10
 The float is:   3.147000
 Implicit conversion int to float :   10.000000
 Explicit conversion float to int :   10
sizeof
C provides a compiler-time unary operator called sizeof that can be used to compute the size of any object.
The expression such as:
sizeof object
sizeof(type name)
Example :

#include<stdio.h>

int main()
{

    printf("size of int in byte :  %d\n", sizeof(int));
    printf("size of char in byte %d\n", sizeof(char));
    printf("size of float in byte %d", sizeof(float));

    return 0;
}
Output :

 size of int in byte :  4
 size of char in byte 1
 size of float in byte 4
C has a special shorthand that simplifies coding of certain type of assignment.
For Example

a = a + 2;
can be written as :

a += 2;
Shorthand works for akk binary operators in C.
Syntax :

  variable operator = variable / constant / expression
Operators are listed below :

Operators Example Meaning
+= a+=2 a=a+2
-= a-=2    a=a-2
*= a*=2 a=a*2
/= a/=2 a=a/2
%= a%=2 a=a%2
&&= a&&=2 a=a&&2
||= a||=2 a=a||2

Opetator                               Associativity

() [] . -> expr++ expr--left-to-right
* & + - ! ~ ++expr --expr (typecast) sizeofright-to-left
* / %left-to-right
+ -left-to-right
>> <<left-to-right
< > <= >=left-to-right
== !=left-to-right
&left-to-right
^left-to-right
|left-to-right
&&left-to-right
||left-to-right
?:right-to-left
= += -= *= /= %= >>= <<= &= ^= |=right-to-left
,left-to-right<
Order of Operation : Parenthesis
Exponents
Multiplication
Division
Addition
Subtraction

Draw ranbow using C graphics

Draw Rainbow using C Graphics.

#include<stdio.h>
#include<graphics.h>
#include<dos.h>
void main(){
int i , gd = DETECT , gm;
initgraph(&gd , &gm ,"c:\\tc\\bgi");

for(i = 0 ; i < 350 ; i++)
{
if(i % 25 == 0)
setcolor(rand() % 16);
arc(350 , 400 , 0 , 180 , i) ;
delay(10);
}
getch(); 

closegraph();
}

Output:



Pointer in C

Pointer
A pointer is a variable whose value is the address of another variable.
General syntax:
data-type  *pointer_name
Example:
char  *a;
int  *p;

1.Following example shows the memory address of variables:

#include <stdio.h>
#include<conio.h>
int main ()
{
   int  variable1;
   char variable2;

   printf("Address of variable1: %x\n", &variable1  );
   printf("Address of variable2: %x\n", &variable2  );

   return 0;
}

2.Following example makes use of pointer:

#include<stdio.h>
#include<conio.h>
int main()
    {
    int var;
    int *ptr1;
    int **ptr2;
    var = 3000;
 /* take the address of var */
    ptr1 = &var;
    /* take the address of ptr1 using address of operator &*/
    ptr2 = &ptr1;
/* take the value using ptr2 */
    printf("Value of var = %d\n", var);
 
    printf("Value available at *ptr1 = %d\n", *ptr1);

    printf("Value available at **ptr2 = %d\n", **ptr2);

    return 0;
}


3.Following example shows the use of pointer as a holder of the memory address of other varible:

#include <stdio.h>
 int main ()
{
/* actual variable declaration */
 int  var = 1;
 /* pointer variable declaration */
 int  *ptr;
   ptr = &var;  /* store address of var in pointer variable*/

   printf("Address of var variable: %x\n", &var  );

   /* address stored in pointer variable */
   printf("Address stored in ptr variable: %x\n", ptr );

   /* access the value using the pointer */
   printf("Value of *ptr variable: %d\n", *ptr );

   return 0;
}

Output:
Address of var variable: 28ff18
Address stored in ptr variable: 28ff18
Value of *ptr variable:1

NULL pointer
The NULL pointer is a constant which value is zero.It is defined in several standard libraries.
4.Following example shows the NULL pointer:

#include <stdio.h>
#include<conio.h>
int main ()
{
   int  *ptr = NULL;
   printf("The value of ptr is : %x\n", ptr  );
   return 0;
}

Output:
The value of ptr is 0

5.Following example shows the use of pointer for swaping of two integers:

#include<stdio.h>
#include<conio.h>
 void swap( int *, int * ) ;
 void main( )
 {
 int a, b ;
 printf( "Enter two numbers" ) ;
 scanf( " %d %d ", &a, &b ) ;
 printf( "a = %d ;  b = %d \n", a, b ) ;

 swap( &a, &b ) ;

 printf( "a = %d ;  b = %d \n", a, b ) ;
 }

 void swap ( int  *ptr1, int  *ptr2 )
 {
 int temp ;

 temp = *ptr2 ;
 *ptr2 = *ptr1 ;
 *ptr1 = temp ;
 }

Output:
Enter two numbers34 56
a=34;  b=56
a=56;  b=34

6.Following example shows the use of increment of pointer.

#include<stdio.h>
#include<conio.h>
const int MAX = 3;
 int main() {

    int var[] = { 10, 100, 200 };
    int i, *ptr;

    /* let us have array address in pointer */
    ptr = var;

    for (i = 0; i < MAX; i++) {

        printf("Address of var[%d] = %x\n", i, ptr);
        printf("Value of var[%d] = %d\n", i, *ptr);
 /* move to the next location */
        ptr++;
     }
  return 0;
}

Output:
Address of var[0] = 68fefc
Value of var[0] = 10
Address of var[1] = 68ff00
Value of var[1] = 100
Address of var[2] = 68ff04
Value of var[2] = 200



7.A C program to find the length of string using Pointer.

#include<stdio.h> 
#include<conio.h>
int string_ln(char*);
void main()
{
char str[20];
int length;

printf("\nEnter any string : ");
gets(str);

length = string_ln(str);
printf("The length of the given string %s is : %d", str, length);
}

int string_ln(char*p) /*p=&str[0]*/
{
int count = 0;
while (*p != '\0') {
count++;
p++;
}
return count;
}

Output:
Enter any string : Welcome
The length of the given string Welcome is : 7


8.A C program which accepts an array of integers and reverse print that array by using pointer.

#include <stdio.h>
#define MAX 30

void main() 
{
int size, i, arr[MAX];
int *ptr;

ptr = &arr[0];

printf("Enter the size of array : ");
scanf("%d", &size);

printf("\nEnter %d integers into array:\n", size);
for(i=0;i<size;i++) {
scanf("%d", ptr);
ptr++;
}

ptr=&arr[size - 1];

printf("\nElements of array in reverse order are :\n");
for(i=size-1;i>=0;i--) {
printf("%d   ",*ptr);
ptr--;
}
}

Output:
Enter the size of array : 4

Enter 4 integers into array:
3 6 2 8

Elements of array in reverse order are :
8   2   6   3


9.A C program to sum the elements of array using pointer.

#include<stdio.h> 
#include<conio.h>
void main()
{
int n,numArray[100];
int i, sum = 0;
int *ptr;
printf("Enter the number of elements of an array:");
scanf("%d",&n);
printf("\nEnter %d elements
:\n",n);
for(i=0;i<n;i++)
scanf("%d", &numArray[i]);
ptr = numArray; /*a=&a[0] */

for(i=0;i<n;i++) {
sum = sum + *ptr;
ptr++;
}
printf("\nThe sum of array elements : %d", sum);
getch();
}

Output:
Enter the number of elements of an array:4

Enter 4 elements :
4 3 8 9

The sum of array elements : 24