Jumat, 04 Desember 2015

When is the right time to use

1. Struct
In C#, a structure is a value type data type. we use Struct when we want to make a single variable hold related data of various data types. The struct keyword is used for creating a structure. Structures are used to represent a record. Suppose you want to keep track of your books in a library


2. Pointer/reference
A pointer is a variable whose value is the address of another variable, we use Pointer when we want to direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address


3. Function
Functions will generally require a prototype. we use Function when we want compiler  function will return, what the function will be called, as well as what arguments the function can be passed. Function can be used in the same manner as a variable would be. For example, a variable can be set equal to a function that returns a value between zero and four.

4. Array
Array will specifies the type of the elements and the number of elements required by an array as follows .You use an array when you need to reference a list of objects or values. You use a while loop when you need to repeat a block of code based on a condition. Example when you have 1000 numbers, if you don't use arrays. you will find it's hard to sort these numbers...

=Write an example that uses combination all of items above.=

1. Pointer to Array of Structure stores the Base address of the Structure array.
void main()
{
struct Cricket *ptr = match;   // By default match[0]
for(i=0;i<4;i++)
    {
    printf("\nMatch : %d",i+1);[
    printf("\n%s Vs %s",ptr->team1,ptr->team2);
    printf("\nPlace : %s",ptr->ground);

    if(match[i].result == 1)
        printf("nWinner : %s",ptr->team1);
    else
        printf("nWinner : %s",ptr->team1);
    printf("\n");

    // Move Pointer to next structure element
    ptr++;
    }
}


2. Example of Pointer And Functions
Program to swap two number using call by reference.

 /* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *a,int *b);
int main(){
  int num1=5,num2=10;
  swap(&num1,&num2);  /* address of num1 and num2 is passed to swap function */
  printf("Number1 = %d\n",num1);
  printf("Number2 = %d",num2);
  return 0;
}
void swap(int *a,int *b){ /* pointer a and b points to address of num1 and num2 respectively */
  int temp;
  temp=*a;
  *a=*b;
  *b=temp;
}


Tidak ada komentar:

Posting Komentar