Selasa, 08 Desember 2015

The Right Time to Use Struct, Pointer/References, Array, Function and The Combination Example in c programming

The Right Time to Use Struct, Pointer/References, Array, Function and The Combination Example

When is the Right Time to Use Struct?
struct in c also called as structures. usually, struct provide a way of storing many different values with the same group or name. we used struct when we have a lot of data that need to be group for instance. we also used struct when we want to create a new data or information.


Example of Struct?
for example, i want to create a new information about three students. the information contains their name, age and grade. in this case i will use looping to named student 1, student 2, student 3.

#include <stdio.h>

struct student {
char name[50];   // declare name using array
int age;
int grade;
};

int main ()
{
struct student info[3];   //declare 3 students [3]
int i;

for(i=1;i<=3;i++) {    // this is for the looping, student 1, student 2, student 3
printf("Enter name for student %d : ",i);
scanf("%s",info[i].name);   // called struct using "." (dot)
printf("Enter age for sudent %d : ",i);
scanf("%d",&info[i].age);
printf("Enter grade for student %d : ",i);
scanf("%d",&info[i].grade);
}
return 0;


}



When is the Right Time to use Pointer/References?
pointer is a data type that store the address of another variable. but you must declare a pointer before you using it to store any variable address. we used pointer when we want to change the value or address of a variable that already declared. we used references if we want to give another name of variable. references also known as alias.


Example of pointer/references?
for example: i want to create a variable named "c" and i will give it another name (alias/references) called "si". so when i called the address of "si", it was the same with i called the address of "c".

#include <stdio.h>

int main () {
int c = 15;
int &si = c;
si = 20;

printf("%d\n",c);   // it's ok if you change "c" in the printf into "si" because it's actually the same
}


When is the Right Time to Use Function?
we use function when we have the same code/command in our source code. so it will make it short. and if you want to change to the command you just need to do it in function.


Example of function?
for example: i want to make the same command for 2 pairs of variables. the first one is to declare the function. called "a" and "b". the second one is the actual variable declaration, called "i" and "j". the same command is sum or addition.

#include <stdio.h>

int jumlah(int a, int b)       // these are parameters
{
int result;
result = a + b;
return result;
}                                   // if you use function use int, you must return something.

int main ()
{
int i = 5;
int j = 15;
int sum;

sum = jumlah(i,j);
printf ("%d\n",sum);
return 0;
}


When is the right time to use array?
the right time to used array is when we have a lot of data. and we can simplify it into one variable.


Example of array?
for example : i want to make some elements of array by the input by user (eg. 5 element). and then he must write the 5 values for those 5 elements. (eg. 1,2,3,4,5). then the output will be element 1 = 1, element 2 = 2. something like that.

#include <stdio.h>

main()
{
    int array[100], n, c;

    printf("Enter the number of elements in array\n");
    scanf("%d", &n);

    printf("Enter %d elements\n", n);

    for ( c = 0 ; c < n ; c++ )
        scanf("%d", &array[c]);

    printf("Array elements entered by you are:\n");

    for ( c = 0 ; c < n ; c++ )
        printf("array[%d] = %d\n", c, array[c]);

    return 0;
}


The combination of all above in one source code?
#include <stdio.h>
#include <string.h>

// declare a struct
struct person
{
int age;
char name [50]; // this is array in name
};

//declare a function
void combination(struct person *prsn);

int main ()
{
struct person prsn;

prsn.age = 15;
strcpy(prsn.name, "Miracle");

combination(&prsn);
return 0;
}

//function called
void combination(struct person *prsn) { //pointer to struct
printf("Person Name: %s \n",prsn->name);
printf("Person Age: %d \n",prsn->age);

}

Kamis, 03 Desember 2015

stdarg

C Library <stdarg.h>

<stdarg.h>
This header defines macros to access the individual arguments of a list of unnamed arguments whose number and types are not known to the called function.

A function may accept a varying number of additional arguments without corresponding parameter declarations by including a comma and three dots (,...) after its regular named parameters:
return_type function_name (parameter_declarations,...);
 
To access these additional arguments the macros va_start, va_arg and va_end, declared in this header, can be used:
  • First, va_start initializes the list of variable arguments as a va_list.
  • Subsequent executions of va_arg yield the values of the additional arguments in the same order as passed to the function.
  • Finally, va_end shall be executed before the function returns.


Library Variable
  • va_list
  1. This is a type suitable for holding information needed by the three macros va_start(), va_arg() and va_end().
  2. Before a function that has initialized a va_list object with va_start returns, the va_end macro shall be invoked.
  3. The specifics of this type depend on the particular library implementation. Objects of this type shall only be used as argument for the va_start, va_arg and va_end, and va_copy macros, or functions that use them, like the variable argument functions in <cstdio.h>


Library Macros
  • va_start
  1. The C library macro void va_start(va_list ap, last_arg) initializes apvariable to be used with the va_arg and va_end macros.
  2. The last_arg is the last known fixed argument being passed to the function i.e. the argument before the ellipsis/(,...).
  3. This macro must be called before using va_arg and va_end.
  4. Declaration: void va_start(va_list ap, last_arg);
  5. parameter -> ap - This is the object of va_list and it will hold the information needed to retrieve the additional arguments with va_arg.
  6. last_arg − This is the last known fixed argument being passed to the function.

  • va_arg
  1. The C library macro type va_arg(va_list ap, type) retrieves the next argument in the parameter list of the function with type.
  2. This does not determine whether the retrieved argument is the last argument passed to the function.
  3. Declaration: type va_arg(va_list ap, type)
  4. parameter -> ap - This is the object of type va_list with information about the additional arguments and their retrieval state. This object should be initialized by an initial call to va_start before the first call to va_arg.
  5. parameter -> type - This is a type name. This type name is used as the type of the expression, this macro expands to.
  6. This macro returns the next additional argument as an expression of type type.

  • va_end
  1. The C library macro void va_end(va_list ap) allows a function with variable arguments which used the va_start macro to return.
  2. If va_end is not called before returning from the function, the result is undefined.
  3. Declaration: void va_end (va_list ap)
  4. parameter -> ap - This is the va_list object previously initialized by va_start in the same function.
  5. This macro does not return any value.


Example 1:
#include <stdarg.h>
#include <stdio.h>

int sum(int, ...);
int main()
{
   printf("Sum of 15 and 56 = %d\n",  sum(2, 15, 56) );
   return 0;
}
int sum(int num_args, ...)
{
   int val = 0;
   va_list ap;
   int i;

   va_start(ap, num_args);
   for(i = 0; i < num_args; i++) 
   {
      val += va_arg(ap, int);
   }
   va_end(ap);
   return val;
}


Example 2:
#include <stdarg.h>
#include <stdio.h>

int mul(int, ...);
int main()
{
   printf("15 * 12 = %d\n",  mul(2, 15, 12) );
   return 0;
}
int mul(int num_args, ...)
{
   int val = 1;
   va_list ap;
   int i;

   va_start(ap, num_args);
   for(i = 0; i < num_args; i++) 
   {
      val *= va_arg(ap, int);
   }
   va_end(ap);
   return val;
}

Rabu, 02 Desember 2015

C File

C File

What is File?
file is an object on a computer that stores data, information, settings, command that are used with computer program.

in windows, files are indentified either by the file extension. for example ".exe" for executeable file, ".dll" file for DLL file and many others.
files also have an illegal files character, they are \ / ? * : " > < |

there are 2 kinds of files in general:
1.Text File
text file is a computer file that only contains text and has no special formatting. in windows, usually text file has ".txt" extension. examples: plain text, source code, html file, etc.

2.Binary File
any file that contains formatted text, non-text characters. examples: program file, image file, etc.


Redirection?
One way to get input into a program or display an output from a program we use standard input output. and it's means that if we want to read in data we use scanf() and to write out data we use printf().

but when we want to redirect and take input from a file. we can use input redirection.
     % a.out < inputfile (the "<" mark for input a file)
and when we want to display the output, we can use output redirection.
     % a.out >output file (the ">" mark for output a file)


Opening a File
to open a file, you can use fopen() function. you also can use fopen() function to create a new file.
ussually, the structure how to open a file is by this following
FILE *fileopen("url of file or filename.txt", "mode");

and these are the mode usually used to open a file:
  • "r" (read) = to open a text file, the file must exist.
  • "w" (write) = to create a new file, to open a file for writing because the file doesn't exist. if the name already exist, it will be discarded and will be an empty file.
  • "a" (append) = open a file for appending mode, if the file doesn't exist, a new file will be create. this is for output at the end of the line, expanding it.
  • "r+" (read/update) = open a file for update (both input and output). the file must exist.
  • "w+" (write/update) = to create a new file and open it for update(both input and output). if the name already exist, it will be discarded and will be an empty file.
  • "a+" (append/update) = open a file for reading and writing (input and output). the reading will start from begining but writing can only be appended.

With the mode specifiers above the file is open as a text file. In order to open a file as a binary file, a "b" character has to be included in the mode string. This additional "b" character can either be appended at the end of the string (thus making the following compound modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+").

The new C standard (C2011, which is not part of C++) adds a new standard subspecifier ("x"), that can be appended to any "w" specifier (to form "wx""wbx""w+x" or "w+bx"/"wb+x"). This subspecifier forces the function to fail if the file exists, instead of overwriting it.


fopen() example:
#include <stdio.h>
int main () {
FILE *pfile;
pfile = fopen ("anyfile.txt", "w");
if (pfile!=NULL) {
     fputs ("fopen() example", pfile);
     fclose (pfile);
     }
     return 0;
}


Writing a File
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error.
#include <stdio.h>
int main () {
FILE *pfile;
char c;
pfile = fopen ("alphabet.txt", "w");
if (pfile!=NULL) {
for (c='A';c<='Z';c++)
     fputc( c, pfile);
     fclose (pfile);
     }
     return 0;
}

The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory on your machine
#include <stdio.h>
int main () {
   FILE *pfile;
   char sentence [256];

   printf("Enter sentence to append: ");
   fgets(sentence,256,stdin);
   pfile = fopen ("text1", "a");
   fputs (sentence,pfile);
   fclose (pfile);
   return 0;
}

Reading a File
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream −
char *fgets(char *buf, int n, FILE *fp);

The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a nullcharacter to terminate the string.
#include <stdio.h>
main() {
   FILE *fp;
   char buff[255];

   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1 : %s\n", buff );

   fgets(buff, 255, (FILE*)fp);
   printf("2: %s\n", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);
}


Closing a File
To close a file, use the fclose( ) function. The prototype of this function is "int fclose (FILE *fp)". The fclose(-) function returns zero on success, or EOF if there is an error in closing the file.

This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
#include <stdio.h>
int main () {
FILE *pfile;
   pfile = fopen ("testfile.txt", "wt");
   fprintf (pfile, "fclose example");
   fclose (pfile);
}

Selasa, 24 November 2015

Struct in C

Struct in C

Struct?
struct is structures, provide a way of storing many different values with the same group or name. we used struct when we have a lot of data that need to be group for instance. struct contains information about the data.

Defining Struct?
to define structure, you must used struct statement. the syntax for struct is:
struct student {
char name [100];
int age;
int height;
int weight;
};

Accessing Struct members?
you can access any member of the structures, and commonly we used access operator (.). to make it clear, you can see the full example how to use struct:
#include <stdio.h>
struct students {
char name[100];
int age;
int weight;
int height;
};

int main () {
struct students student1;            //declare student1 of the student
struct students student2;            //declare student2 of the student

//access the information about student1
strcpy(student1.name, "Serafin William");
student1.age = 18;
student1.weight = 52;
student1.height = 170;

//access the information about student2
strcpy(student2.name, "Winner2nd");
student2.age = 17;
student2.weight = 56;
student2.height = 170;

//print the information about student 1
printf("Student 1 name: %s\n",student1.name);
printf("Student 1 age: %d\n",student1.age);
printf("Student 1 name: %d kg\n",student1.weight);
printf("Student 1 name: %d cm\n",student1.height);

//print the information about student2
printf("Student 2 name: %s\n",student2.name);
printf("Student 2 age: %d\n",student2.age);
printf("Student 2 name: %d kg\n",student2.weight);
printf("Student 2 name: %d cm\n",student2.height);

return 0;
}

Another example, How to use in function?
#include <stdio.h>
struct Books {
char  title[50];
char  author[50];
char  subject[100];
int   book_id;
};

/* function declaration */
void printBook( struct Books book );

int main( ) {
struct Books Book1;        /* Declare Book1 of type Book */
struct Books Book2;        /* Declare Book2 of type Book */
 
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali"); 
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
 
/* print Book1 info */
printBook( Book1 );

/* Print Book2 info */
printBook( Book2 );

return 0;
}

void printBook( struct Books book ) {
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}

How to use structure in pointer?
#include <stdio.h>
struct Books {
char  title[50];
char  author[50];
char  subject[100];
int   book_id;
};

/* function declaration */
void printBook( struct Books *book );

int main( ) {
struct Books Book1;        /* Declare Book1 of type Book */
struct Books Book2;        /* Declare Book2 of type Book */
 
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali"); 
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
 
/* print Book1 info by passing address of Book1 */
printBook( &Book1 );

/* print Book2 info by passing address of Book2 */
printBook( &Book2 );

return 0;
}

void printBook( struct Books *book ) {
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}

References?
#include <stdio.h>
struct someStruct {
unsigned int total;
};
    
int test(struct someStruct* state) {
state->total = 4;
}
    
int main () {
struct someStruct s;
s.total = 5;
test(&s);
printf("s.total = %d\n", s.total);
}

Senin, 23 November 2015

Pointers and reference in C

Pointers and Reference in C

     Definition of Pointers:
  • is a data type that store the addres of another variable. but you must declare a pointer before you using it to store any variable address.
  • you can declare a pointer using asterisk (*). example: int *a. the asterisk function is used to designate a variable as a pointer.
     Step to use Pointers?
  • create and define a pointer variable. (ex. int *x;).
  • create another variable that you want to store to pointer. (ex. int y = 10;).
  • access the value at the address in the pointer variable. (ex. x = &y).
  • that means that now variable x contains the address of variable y.
     to use pointers in another way?
  • define a variable that contains the address. (ex. int x = 10;)
  • and then create a pointer variable but point them into the variable that contains the address.  (ex. int *y = &x;)
    The example of to use pointers?

     #include <stdio.h>
     int main ()
     {
     int  x = 10;                         // create a variable
     int *y;                                // pointer variable declaration
     y = &x;                              // store address of x into y

     printf("address of x variable: %x\n",x);
     printf("address store of x into y pointer variable: %x\n",y);

     //access the value of the store address into y using pointer.
     printf("the value of y: %d\n",*y);
     
     return 0;
     }

     passing by pointers and the relation with function?
     #include <stdio.h>

     //function declaration
     int passing(int *x) {
     *x = 10;
     }

     int main ()
     {
     int y = 1;                             // x points to y
     passing(&y);                      // pass address of y to x
     printf("&d\n",y);                // now it will print 10 instead of 1
     return 0;
     }

     The relation of pointer with array?
     #include <stdio.h>
     int main ()
     {
     char c[4];
     int i;
     for (i=0;i<4;i++) {
     printf("Address of c[%d]=%x\n",i,&c[i]);
     }
     return 0;
     }

     How to pass pointer in array?
     int arr[5] = {1,2,3,4,5};
     int *x;
     x = &arr[1];                           // now it will point to arr[1]
     *x = 6;                                   //now arr[1] = 2 become x[1] = 6... {1,6,3,4,5}
     x+= 1;                                   //now move x to next address. start from arr[1].
     x[0] = 12;                              //now the result is {1,6,12,4,5}
     x[1] = 13;                              //now the result is {1,6,12,13,5}
     now you can access the data. (ex.you want to access 13, so you can call "arr[3]")

     References?
     references or alias is to make another name of a variable. example :
     int x = 10;
     int &y = x;                              // now x and y is the same variable
     y = 5;                                      //y=5 and the value of x also will be changed. x=5.

Selasa, 27 Oktober 2015

Looping in C programming language

Looping in C

in loop, statement will be executed sequentially. there are some syntax in loop. they are :
  1. for loop
    is a repetation control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
    example :
    #include <stdio.h>
    int main ()
    {
    int a;
    for (a=0; a<=10; a++) {
    printf ("%d ", a);
    }
    return 0;
    }

    the result will be "0 1 2 3 4 5 6 7 8 9 10"
  2. While loop
    while loop statement in c repeatdly executes a target statement as long as a given condition is teur.
    example :
    #include <stdio.h>
    int main ()
    {
    int a = 20;
    while (a<30)
    {
    printf ("%d ",a); a++;
    }
    return 0;
    }

    the output will be "20 21 22 23 24 25 26 27 28 29".
  3. Do while loop
    do while will check its condition at the bottom of the loop. but for and while will check the loop condition at the top of the loop.
    example :
    #include <stdio.h>
    int main ()
    {
    int a = 0;
    do
    {
    printf ("%d ",a); a++;
    }
    while (a<10);
    return 0;
    }

    the output will be "0 1 2 3 4 5 6 7 8 9".

Senin, 26 Oktober 2015

Decision Making / Branching in C

Decision / Branch in C

     Decision making is important concepts in c programming language. usually , program should be able to make logical or true/false decision based on the condition. the purpose of decision making/branch is to solve particular problems.
     Branching is the term given to the code executed in sequence as a result of change in the program flow. branching is the process of choosing the right branch for execution, depending on the result of the "statement condition".
     there are some syntax of decision making/branch. they are :
  1. If-else statement
    if the condition is true, the program will be executed. but if the condition expression is false, it will executed other statement.
    example :
    #include <stdio.h>
    int main ()
    int a = 5;
    if (a<10) {  // this will be check the statement condition
    printf ("this is true\n"); // if the condition true the result will print this
    }
    else {
    printf ("this is false\n"); // if the condition false the result will print this
    }
    return 0;
    }

    the result will be "this is true" because it's right that a less than 10 (a<10). that a = 5.
  2. Switch case statement
    switch case statement is used to make a selection towards expression or condition that have constant values. because of that, the expression that is defined must be produced a value of integer or character.
    example :
    #include <stdio.h>
    int main ()
    {
    int how_many_pet = 4;
    switch (how_many_pet) {
    case 5 : case 4 : case 3 : printf ("animallover"); break;
    case 2 : printf ("perfect"); break;
    case 1 : printf ("cool"); break;
    case 0 : printf ("miss"); break;
    default :
    printf ("butoklah");
    return 0;
    }
    }

    the result will be "animallover".
  3. Ternary Operator (?:)
    ternary operator can be used to replace if else statement. the general form :
    condition 1? condition 2 : condition 3
    if condition 1 is true, then condition 2 is evaluated and becomes the value of the expression. but if condition 1 is false, then condition 3 is evaluated and becomes the value of the expression.
    example :
    #include <stdio.h>
    int main ()
    {
    int love = 100;
    int match = (love>100 ? 100 : 50);
    if (love>100) {
    printf ("match = 100");
    }
    else
    {
    printf ("match = 50");
    }
    return 0;
    }

    the result will be "match = 50".