Showing posts with label C Tutorials. Show all posts
Showing posts with label C Tutorials. Show all posts

Thursday, 14 February 2013



In case of any file input-output error or erroneous command line arguments, it is possible to terminate program execution. This can be done through the exit() function as shown in the following example:

if( argc!= 3)
{
printf("Invalid arguments\n");
exit();
}

An integer may also be passed as a parameter to the exit() function. In UNIX, this value is stored in the environmental variable "$?", and should be in the range 0 - 255.

Posted by Unknown


The stdin, stdout and stderr are names used to refer to the standard input device (keyboard) and standard output and error device (VDU). These are actually FILE type pointers, defined in the file stdio.h, and can be used with file input-output functions.

For example, the following statement:

fputc (c, stdout);

writes the value of the char type variable c onto the VDU.

The standard input, output and error files are not opened within C programs, since the operating system makes these devices available for all programs.

Posted by Unknown


In case fopen() is unsuccessfull in opening a file, it send s back a null(zero) value called NULL. NULL is defined in the file stdio.h.

For example, the following statement.

if((fp = fopen ("a.dat", "r")) == NULL)

can be used to test whether the file a.dat has been opened successfully or not.

Posted by Unknown

Closing Files

Each file is closed by one fclose() statement as shown in the following code:

#include<stdio.h>
main()
{
:
:
fclose(ptr1);
fclose(ptr2);
}

The above code is used to close files.

fclose() statement is used to close files.

Posted by Unknown


In C, character input-output functions from files are simple extensions of the corresponding functions for input-ouput from/to the terminal. So, there are funcitons such as:

fgetc()
fputc()

The only additional parameter of both functions is the appropriate file pointer, so that the file to be used for input-output is known.

The following code performs the actual copying of contents of a.dat to b.dat:

#include<stdio.h>
main()
{
char c;
:
:
while((c=fgetc(ptr1))!= EOF)
fputc(c, ptr2);
}

The fgetc() function reads one character at a time from a file, assigns it to a character variable, and moves the file pointer to the next character.

fgetc() actually returns an integer type of value, which is type cast into a character type before being assigned to c.

Posted by Unknown


The C statements that would do this are:

#include<stdio.h>
main()
{
FILE *ptr1, *ptr2;
ptr1 = fopen ("a.dat", "r");
ptr2 = fopen ("b.dat", "w");
----
----
}

The function fopen() opens a file in the appropriate access mode.

When a file is opened, certain information regarding that file automatically gets stored in different variables. These variables are collectively classified as the data type FILE. fopen() returns a pointer to this FILE type data. Hence, the following declaration is required for defining the two pointers:

FILE *ptr1, *ptr2;

The definition of the data type FILE is provided in a standard header file called stdio.h, which is therefore included in this program.

The parameters r and w in the fopen() statements indicate the mode of access to these files.

C allows a number of modes in which a file can be opened.


Posted by Unknown


The treatment of files in C is very simple, unlike that of other programming languages where there are special in-built and often rigid file structures and file-handling routines. C treats file input-output in much the same way as input-output from/ to the terminal, and provides file input-output functions, very similar to those for input-output from/to the terminal.

The simplicity of the input-output in C lies in the fact that it essentially treats a file as a stream of characters and accordingly allows input-output in streams of characters. Functions are available for single character as well as multiple character input-output from/to files.

This simplicity has the advantage that the programmer can read and write onto a file as he/she wishes to.

This post uses the example of a file-copy program, which copies the contents of a file called a.dat to a file called b.dat to explain file input-output.

The steps involved in copying are:

1. Opening both files, one to read from, the other to write to.

2. Reading one character from the file a.dat, writing it onto b.dat, until the end of a.dat.

3. Closing both files.

Posted by Unknown

atoi()


This function returns the int type value of a string passed to it and the value() in case the string does not begin with a digit.

For example, if the array str1 contains the string "1234", then the following statement:

y = atoi(str1);

will cause y to have the value 1234.

However, if the array str1 contains the string "ABC", then the following statement:

y = atoi(str1);

will cause y to have the value().

atof()


This function returns the double type value of a string passed to it and the value 0 in case the string does not begin with a digit or a decimal point.

For example, if the array str1 contains the string "1234", then the following statement:

y = atof(str1);

will caluse y to have the value 1234.0000.

However, to use atof(), the following declaration must be included in the program:

double atof();

since it returns a non-integer value.

Posted by Unknown


A brief description of some of the standard string functions of C given below,

strcmp()

strcmp() compares 2 strings (its parameters) character by character (ASCII comparison) and returns any of the integer values. less than(), greater than().

strcpy()

strcpy() copies the second string to the first string named in the strcpy() parameters.

For example, the following statement:

strcpy (str1, "ABC");

will copy the string "ABC" to the array str1.

strcat()

strcat() appends the second string passed at the end of the first string passed to it.

For example:

strcat (str1, "ABC");

will add the string "ABC" to the contents of the array str1.

strlen()

This function returns the number of characters in the string passed to it. The length does not include the NULL character.

For example, if the array str1 contains the string "1234", then the following statement:

y = strlen(str1);

will cause y to have the value 4.

Posted by Unknown

Wednesday, 13 February 2013



Just as data can be passed to a function, so also, data can be passed back from a called function to its caller.

In C, functions can return values through the return verb as illustrated in the following example:

main()
{
int x, y, value;
scanf("%d %d", &x, &y);
fflush(stdin);
value = sun(x,y);
printf("Total is %d \n", vlaue);
}
sum (a,b)
int a,b;
{
return a + b;
}

In this example, the function sum() sends back the value of a + b to the function main(). The value returned to main() from sum() is stored in a variable called value, the value of which is printed out through the printf() statement in main().

The return statement not only sends back a value to a caller function, but also returns control to it.

Note that a function can return only one value, though it may return different values depending on certain conditions.

C assumes that the value  returned is an int type value. In case a function has to return a value which is not an integer, then the function itself has to be declared of the specific data type that it returns.

Posted by Unknown


Arrays are inherently passed to functions by the call by reference method. for instance, if an array called num_array of size 10 is to be passed to a function called stringfunc(), then it would be passed as follows:

stringfunc (num_array);

Recall that num_array is actually the address of the first element of the array. So, this would be a call by reference. The parameter of the called function, say, number_list could be declared in any of the following ways:

stringfunc(number_list)
int number_list[];
{
--
--

]

OR

stringfunc (number_list)
int number_list[10];
{
--
--
}

OR

stringfunc (number_list)
int *number_list;
{
--
--
}

Posted by Unknown


Call by reference means that the called function should be able to refer to the variables of the caller function directly, and not create its own copy of the values in different variables. This would be possible only if the address of the variables are passed as parameters to the function.

Consider the same program written using call by reference:

main()
{
int num1, num2;
char operator;
printf("Enter 2 numbers and an operator\n");
scanf("%d%d%c", &num1, &num2, &operator);
fflush(stdin);
calc(&num1, &num2, &operator);
}
calc(val1, val2, oper)
int *val1, *val2;
char oper;
{
switch(oper)
{
case '+' : printf("%d", *val1 + *val2);
break;
case '-' : printf("%d", *val1 - *val2);
break;
case '*' : printf("%d", *val1 * *val2);
break;
case '/' : printf("%d", *val1 / *val2);
break;
default: printf("Invalid operator \n");
}
}

In this program, the addresses of the variables num1, num2 and operator are passed as parameters to the function calc(), instead of their values.

Posted by Unknown


In C programs, functions that have parameters are invoked in one of two ways:

1). Call by value

2). Call by reference

These will be illustrated through the example of a program called computer that takes two numbers and a mathematical operator as input and perfoms the appropriate arithmetic operation on the numbers.

Call by Value

Consider the following code for the problem statement memtioned:

main()

{
int num1,num2;
char operator;

printf("Enter 2 numbers and an operator\n");
scanf("%d%d%c", &num1, &num2, &operator);
fflush(stdin);

calc(num1, num2, operator);
}

calc(val1, val2, oper)
int val1, val2;
char oper;
{
switch(oper)
{
case '+' : printf("%d", val1 + val2);
break;
case '-' : printf("%d", val1 - val2);
break;
case '*' : printf("%d", val1 * val2);
break;
case '/' : printf("%d", val1 / val2);
break;
default: printf("Invalid operator \n");
}
}
In this program, values entered for the variables num1, num2 and operator in the main() function are passed to the function calc().

Posted by Unknown


The term 'parameter' has been introduced earlier. To review, consider the following printf() statement:

printf("%d", value);

The printf() function expects two pieces of information:

1. The format(s) in which data is to be printed.
2. The variable(s) whose value(s) is/are to be printed in the specified format(s).

These are the parameters of the function printf().

Thus, parameter(s) of a function is/are the data that the function must receive when called or invoked from another function.

Not all standard functions require a parameter. An example is getchar(). Similarly, user-defined functions may or may not have parameters.

Consider the following examples:

main()
{
disp_head();
}

disp_head()
{
printf("Employee report");
}

The function disp_head() in program does not expect any data when invoked.

Posted by Unknown


Functions are the building blocks of C. All programs definitely consist of one function - main() - and inevitably refer to, or, in programming terminology, call or invoke standard functions of C such as printf(), scanf(), etc. as well as user-defined functions.

Advantages of Functions

Besides the obvious advantages of

-> Reusability, and
-> Structing of programs

functions also provide programmers a convenient way of designing programs in which complex computations can be built into the functions. Once properly designed, a programmer does not have to bother about how the calculations are done in the function; it is sufficient for him to know what it does. Thus, to the programmer, the function itself would be like a black box. The programmer has to the function.

The use of functions would probably save a programmer the often nerve-racking experience of debugging a program that refuses to 'function' properly.

Posted by Unknown


Now that we have laid the groundwork for understanding the concept of pointers, we will write a few functions to manipulate strings using pointers.

#include <stdio.h>
main()
{
char *ptr,str[20];
int size=0;
printf("\nEnter String :");
gets(str);
fflush(stdin);
for(ptr=str; *ptr != '\0' ; ptr++)
{
size++;
}
printf("String length is %d", size);
}

Posted by Unknown


Extending the logic of declaring one-dimensional character arrays, we can also declare two-d charater arrays.

char *things[6];

Individual strings can be initialised by separate assignment statements since each element of this array is a pointer.

things[0] = "Raindrops on roses";
things[1] = "And Whiskers on kittens";
things[2] = "Bright copper kettles";
things[3] = "And Warm woollen mittens";
things[4] = "Brown paper packages tied up with strings";
things[6] = "These are a few of my favourite things";

The third line of the song can be printed by the following statement:

printf("%s", things[2]);

Now, let us complicate things a little further and apply pointer arithmetic to two-d arrays.

Consider the following declaration:

int num[3][4] = {
{3,6,9,12},
{15,25,30,35},
{66,77,88,99},
};

This statements actually declares an array of 3 pointers (constant) num[0], num[1], num[2] each containing the address of the first element of three single dimensional arrays.

Posted by Unknown


Arithmetic operations of incrementing and decrementing can be performed on pointers. In fact, pointer arithmetic is one of the reasons why it is essential to declare a pointer as pointing to a certain datatype so that when the pointer is incremented or decremented, it moves by the appropriate number of bytes. Thus, a simple satement like

ptr++;

does not neccessarily mean that ptr now points to the next memory location. What memory location it will point to depend upon the datatype to which the pointer points.

Consider the following example:

#include<stdio.h>

char movie[] = "Jurassic Park";

main()
{
char *ptr;
ptr=movie;
printf("%s", movie);

printf("%s", ptr);

ptr++;

printf("%s", movie);

printf("%s", ptr);

ptr++;

printf("%s", movie);

printf("%s", ptr);

}

Posted by Unknown


Two-d character arrays are typically used to create an array of strings. Manipulating a character two-d array is however, slightly different from manipulating an integer or float two-d array. This is because a character two-d array is likely to be accessed in terms of strings rather than elements, and hence requires only the row subscript. Individual elements can be accessed as usual by specifying both subscripts.

Consider the following example:

#include <stdio.h>

char books[][40] = {
"This is first",
"This is second",
"This is third",
"This is forth"
};

main()
{
int num;
printf("\nEnter a semester number");
scanf("%d", &num);
fflush(stdin);
if(num>=1 && num<=6)
{
num--;
printf("Your book for thi semester is %s", books[num]);
}
else
printf("\nWrong semester !");
}

Consider the need to store the marks of the students belonging to a batch, in various subjects. The list of student names are stored in a two dimensional character array called student. The list of subjects is also stored in a two dimensional array called subject. The details of the marks of each student in each subject are going to be stored in a two dimensional integer array called marks.

Posted by Unknown

Tuesday, 12 February 2013



In the last cycle, we learnt the concept of one dimensional arrays in C language. C also supports multidimensinal arrays and the simplest form of the multidimensional array is the two - dimensional array. A two-d array is in essence an array of single dimensional arrays. The general form of declaration fo the two-d array would be

type arrayname[x][y];

Note that each dimension of the two-d array has been placed in a separate set of brackets. Two-d arrays are stored in a row-column matrix, in which the first index indicates the row and the second indicates the column. To access a specific element, both the indices or subscripts have to be specified.


Initialising Two Dimensional Arrays

The rules for initialising a two-d array are the same as for a one dimensional array. Initialisation at the time of declaration must be done outside the function or must be declared static within the function. Consider the following example:

int squares[10][2]={
{1,1}
{2,4}
{3,9}
{4,16}
{5,25}
}

The row subscript may be left blank for a more flexible declaration. The compilar will automatically calculate the row dimension based on the number of values initialised. The inner sets of curly braces are optional. However, in the case of initialising the array with only some and not all values, these curly braces assume a lot of importance.
For Example:

int sales[3][4]={
{143,274},
{336,543,876},
{442,421,765,996},
};

only two elements of the first row, three in the second row and four in the third row are initialised.

Posted by Unknown
Powered by Blogger.