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);
}