Saturday, November 14, 2009

For Loop Triangle Program

#include
#include
main()
{
int row,col;
int n = 0;
printf ("Please enter the number: ");
scanf ("%d",&n);
for (col = 1; col >= n; ++col) /*Loop For column */
{
for (row = 1 ; row >= col ; ++row) /*Loop For row */
{
printf ("*");
}
printf ("\n");
}
getch();
}

OUTPUT:
Please enter the number:4

*
**
***
****

Explanation:

1) In the above program we have taken two variables row and col to display row and column. Geometrically tringle is two dimensional figure so we have to take two diffrent varibles to deal with row and column.

2) Now, we are asking user to enter the number.

3) First for loop, i.e. outer loop is to deal with the column.
for (col = 1; col <= n; ++col) here it is initialized with 1 and compared with the value enterd by user so that it should not exceed the entered value and incrimented to jump to next column as soon as the first row get printed. 4) The second or inner for loop is dealing with the row and hence it is the loop which in fact prints the starts '*'. Ultimately rows on multiple lines causes the columns. 5) At first soon you enter the value for n, say 4. The outer for loop will check the condition. for (col = 1; 1 <= 4; ++col) Found true and hence execution pointer will move to inner for loop and check the condition for (row = 1 ; 1 <= 1; ++row) Found true, so it will execute print statement, now as incrimentation is there the value of row is two and hence condition false. it will again go to outer for loop as it is not over. The value of col is now 2. for (col = 1; 2 <= 4; ++col) Found true and hence execution pointer will move to inner for loop and check the condition for (row = 1 ; 1 <= 2; ++row) Found true, so it will execute print statement.Now as incrimentation is there the value of row is two for (row = 1 ; 2 <= 2; ++row) again condition is true so print statement will get executed again and result in two '*' on same row. This way it will continue till outer for loop gives false result for condition. Let us reverse the triangle, #include
#include

main()
{
int row,col;
int n = 0;
printf ("Please enter the number: ");
scanf ("%d",&n);
for (col = n; col >= 1; --col) /*Loop For column */
{
for (row = col ; row >= 1 ; --row) /*Loop For row */
{
printf ("*");
}
printf ("\n");
}
getch();
}

OUTPUT:
Please enter the number:4

****
***
**
*

// a program to show the nested for loops

#include



int main()

{

// variables for counter…

int i, j;

// outer loop, execute this first...

// for every i iteration, execute the inner loop

for(i=1; i<10;)

{

// display i

printf("%d", i);

// then, execute inner loop with loop index j the initial value of j is i + 1

for(j=i+1; j<10; )

{

// display result of j iteration

printf("%d", j);

// increment j by 1 until j<10

j = j + 1;

}

// go to new line

printf("\n");

// increment i by 1, repeat until i<10

i = i + 1;

}

return 0;

}



The program has two for loops. The loop index i for the outer (first) loop runs from 1 to 9 and for each value of i, the loop index j for the inner loop runs from i + 1 to 9. Note that for the last value of i (i.e. 9), the inner loop is not executed at all because the starting value of j is 10 and the expression j < 10 yields the value false because j = 10.

The following is the flowchart for the above program.


Thursday, November 12, 2009

CHAPTER 2: Pointer types and Arrays

Okay, let's move on. Let us consider why we need to identify the type of variable that a pointer points to, as in:
int *ptr;
One reason for doing this is so that later, once ptr "points to" something, if we write:
*ptr = 2;
the compiler will know how many bytes to copy into that memory location pointed to by ptr. If ptr was declared as pointing to an integer, 2 bytes would be copied, if a long, 4 bytes would be copied. Similarly for floats and doubles the appropriate number will be copied. But, defining the type that the pointer points to permits a number of other interesting ways a compiler can interpret code. For example, consider a block in memory
consisting if ten integers in a row. That is, 20 bytes of memory are set aside to hold 10 integers.
Now, let's say we point our integer pointer ptr at the first of these integers. Furthermore lets say that integer is located at memory location 100 (decimal). What happens when we write:
ptr + 1;
Because the compiler "knows" this is a pointer (i.e. its value is an address) and that it points to an integer (its current address, 100, is the address of an integer), it adds 2 to ptr instead of 1, so the pointer "points to" the next integer, at memory location 102.
Similarly, were the ptr declared as a pointer to a long, it would add 4 to it instead of 1. The same goes for other data types such as floats, doubles, or even user defined data types such as structures. This is obviously not the same kind of "addition" that we normally think of. In C it is referred to as addition using "pointer arithmetic", a term
which we will come back to later.Similarly, since ++ptr and ptr++ are both equivalent to ptr + 1 (though the point in the program when ptr is incremented may be different), incrementing a pointer using the unary ++ operator, either pre- or post-, increments the address it stores by the amount sizeof(type) where "type" is the type of the object pointed to. (i.e. 2 for an integer, 4 for a long, etc.).
Since a block of 10 integers located contiguously in memory is, by definition, an array of integers, this brings up an interesting relationship between arrays and pointers.
Consider the following:

int my_array[] = {1,23,17,4,-5,100};

Here we have an array containing 6 integers. We refer to each of these integers by means of a subscript to my_array, i.e. using my_array[0] through my_array[5]. But, we could alternatively access them via a pointer as follows:

int *ptr;
ptr = &my_array[0]; /* point our pointer at the first integer in our array */

And then we could print out our array either using the array notation or by dereferencing our pointer. The following code illustrates this:

----------- Program 2.1 -----------------------------------
/* Program 2.1 from PTRTUT10.HTM 6/13/97 */
#include
int my_array[] = {1,23,17,4,-5,100};
int *ptr;
int main(void)
{
int i;
ptr = &my_array[0]; /* point our pointer to the first
element of the array */
printf("\n\n");
for (i = 0; i < 6; i++)
{
printf("my_array[%d] = %d ",i,my_array[i]); /*<-- A */
printf("ptr + %d = %d\n",i, *(ptr + i)); /*<-- B */
}
return 0;
}
---------------------------------------------------------
Compile and run the above program and carefully note lines A and B and that the program prints out the same values in either case. Also observe how we dereferenced our pointer in line B, i.e. we first added i to it and then dereferenced the new pointer. Change line B to read:

printf("ptr + %d = %d\n",i, *ptr++);
and run it again... then change it to:
printf("ptr + %d = %d\n",i, *(++ptr));

11

and try once more. Each time try and predict the outcome and carefully look at the actual outcome.
In C, the standard states that wherever we might use &var_name[0] we can replace that with var_name, thus in our code where we wrote:

ptr = &my_array[0];
we can write:
ptr = my_array;

to achieve the same result.
This leads many texts to state that the name of an array is a pointer. I prefer to mentally think "the name of the array is the address of first element in the array". Many beginners (including myself when I was learning) have a tendency to become confused by thinking of it as a pointer. For example, while we can write

ptr = my_array;
we cannot write
my_array = ptr;

The reason is that while ptr is a variable, my_array is a constant. That is, the location at which the first element of my_array will be stored cannot be changed once my_array[]
has been declared. Earlier when discussing the term "lvalue" I cited K&R-2 where it stated:
"An object is a named region of storage; an lvalue is an expression
referring to an object".

This raises an interesting problem. Since my_array is a named region of storage, why is my_array in the above assignment statement not an lvalue? To resolve this problem,some refer to my_array as an "unmodifiable lvalue".
Modify the example program above by changing

ptr = &my_array[0];
to
ptr = my_array;

and run it again to verify the results are identical.

Now, let's delve a little further into the difference between the names ptr and my_array as used above. Some writers will refer to an array's name as a constant pointer. What do we mean by that? Well, to understand the term "constant" in this sense, let's go back to
our definition of the term "variable". When we declare a variable we set aside a spot in memory to hold the value of the appropriate type. Once that is done the name of the variable can be interpreted in one of two ways. When used on the left side of the assignment operator, the compiler interprets it as the memory location to which to move that value resulting from evaluation of the right side of the assignment operator. But, when used on the right side of the assignment operator, the name of a variable is interpreted to mean the contents stored at that memory address set aside to hold the value of that variable. With that in mind, let's now consider the simplest of constants, as in:
int i, k;
i = 2;
Here, while i is a variable and then occupies space in the data portion of memory, 2 is a constant and, as such, instead of setting aside memory in the data segment, it is imbedded directly in the code segment of memory. That is, while writing something like k = i; tells the compiler to create code which at run time will look at memory location &i to determine the value to be moved to k, code created by i = 2; simply puts the 2 in the code and there is no referencing of the data segment. That is, both k and i are objects, but 2 is not an object.
Similarly, in the above, since my_array is a constant, once the compiler establishes where the array itself is to be stored, it "knows" the address of my_array[0] and on seeing:

ptr = my_array;

it simply uses this address as a constant in the code segment and there is no referencing of the data segment beyond that.
This might be a good place explain further the use of the (void *) expression used in Program 1.1 of Chapter 1. As we have seen we can have pointers of various types. So far we have discussed pointers to integers and pointers to characters. In coming chapters we will be learning about pointers to structures and even pointer to pointers.
Also we have learned that on different systems the size of a pointer can vary. As it turns out it is also possible that the size of a pointer can vary depending on the data type of the object to which it points. Thus, as with integers where you can run into trouble attempting to assign a long integer to a variable of type short integer, you can run into trouble attempting to assign the values of pointers of various types to pointer variables of other types.

To minimize this problem, C provides for a pointer of type void. We can declare such a pointer by writing:

void *vptr;

A void pointer is sort of a generic pointer. For example, while C will not permit the comparison of a pointer to type integer with a pointer to type character, for example,
either of these can be compared to a void pointer. Of course, as with other variables, casts can be used to convert from one type of pointer to another under the proper circumstances. In Program 1.1. of Chapter 1 I cast the pointers to integers into void pointers to make them compatible with the %p conversion specification. In later chapters other casts will be made for reasons defined therein.

Monday, November 2, 2009

Pointers: Chapter 1

I have found that often the main reason beginners have a problem with pointers is that they have a weak or minimal feeling for variables, (as they are used in C). Thus we start with a discussion of C variables in general.
A variable in a program is something with a name, the value of which can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within the computer to hold the value of that variable. The size of that block depends on the range over which the variable is allowed to vary. For example, on PC's the size of an
integer variable is 2 bytes, and that of a long integer is 4 bytes. In C the size of a variable type such as an integer need not be the same on all types of machines.
When we declare a variable we inform the compiler of two things, the name of the variable and the type of the variable. For example, we declare a variable of type integer with the name k by writing:
int k;
On seeing the "int" part of this statement the compiler sets aside 2 bytes of memory (on a PC) to hold the value of the integer. It also sets up a symbol table. In that table it adds the symbol k and the relative address in memory where those 2 bytes were set aside.
Thus, later if we write:
k = 2;
we expect that, at run time when this statement is executed, the value 2 will be placed in that memory location reserved for the storage of the value of k. In C we refer to a variable such as the integer k as an "object".
Ia sense there are two "values" associated with the object k. One is the value of the integer stored there (2 in the above example) and the other the "value" of the memory location, i.e., the address of k. Some texts refer to these two values with the nomenclature rvalue (right value, pronounced "are value") and lvalue (left value, pronounced "el
value") respectively.
In some languages, the lvalue is the value permitted on the left side of the assignment operator '=' (i.e. the address where the result of evaluation of the right side ends up). The rvalue is that which is on the right side of the assignment statement, the 2 above. Rvalues
cannot be used on the left side of the assignment statement. Thus: 2 = k; is illegal.
Now, let's say that we have a reason for wanting a variable designed to hold an lvalue (an address). The size required to hold such a value depends on the system. On older desk top computers with 64K of memory total, the address of any point in memory can be contained in 2 bytes. Computers with more memory would require more bytes to hold an
address. Some computers, such as the IBM PC might require special handling to hold a segment and offset under certain circumstances. The actual size required is not too important so long as we have a way of informing the compiler that what we want to store is an address.
Such a variable is called a pointer variable (for reasons which hopefully will become clearer a little later). In C when we define a pointer variable we do so by preceding its name with an asterisk. In C we also give our pointer a type which, in this case, refers to the type of data stored at the address we will be storing in our pointer. For example,
consider the variable declaration:
int *ptr;
ptr is the name of our variable (just as k was the name of our integer variable). The '*' informs the compiler that we want a pointer variable, i.e. to set aside however many bytes is required to store an address in memory. The int says that we intend to use our pointer variable to store the address of an integer. Such a pointer is said to "point to" an integer.
However, note that when we wrote int k; we did not give k a value. If this definition is made outside of any function ANSI compliant compilers will initialize it to zero.
Similarly, ptr has no value, that is we haven't stored an address in it in the above declaration. In this case, again if the declaration is outside of any function, it is initialized to a value guaranteed in such a way that it is guaranteed to not point to any C object or function. A pointer initialized in this manner is called a "null" pointer.
But, back to using our new variable ptr. Suppose now that we want to store in ptr the address of our integer variable k. To do this we use the unary & operator and write:
ptr = &k;
What the & operator does is retrieve the lvalue (address) of k, even though k is on the right hand side of the assignment operator '=', and copies that to the contents of our pointer ptr. Now, ptr is said to "point to" k. Bear with us now, there is only one more operator we need to discuss.
The "dereferencing operator" is the asterisk and it is used as follows:
*ptr = 7;
will copy 7 to the address pointed to by ptr. Thus if ptr "points to" (contains the address of) k, the above statement will set the value of k to 7. That is, when we use the '*' this way we are referring to the value of that which ptr is pointing to, not the value of the pointer itself.
Similarly, we could write:
printf("%d\n",*ptr);
to print to the screen the integer value stored at the address pointed to by ptr;.One way to see how all this stuff fits together would be to run the following program and then review the code and the output carefully.

/* Program 1.1 from PTRTUT10.TXT 6/10/97 */
8
#include
#include
int j, k;
int *ptr;
int main(void)
{
j = 1;
k = 2;
ptr = &k;
clrscr();
printf("\n");
printf("Value of j is %d and is stored at %p\n", j, (void *)&j);
printf("Value of k %d and is stored at %p\n", k, (void *)&k);
printf("Value of ptr %p and is stored at %p\n", ptr,(void *&ptr);
printf("Value of the integer pointed to by ptr is %d\n",*ptr);
getch();
}

To review:
· A variable is declared by giving it a type and a name (e.g. int k;)
· A pointer variable is declared by giving it a type and a name (e.g. int *ptr) where the asterisk tells the compiler that the variable named ptr is a pointer variable and the type tells the compiler what type the pointer is to point to (integer in this case).
· Once a variable is declared, we can get its address by preceding its name with the unary & operator, as in &k.
· We can "dereference" a pointer, i.e. refer to the value of that which it points to, by using the unary '*' operator as in *ptr.
· An "lvalue" of a variable is the value of its address, i.e. where it is stored in memory. The "rvalue" of a variable is the value stored in that variable (at that address).


Regards:
Ajit Pandey

Thursday, October 29, 2009

IF-ELSE Looping

Looping is one of the most essential and important programming feature. Let us talk about IF looping. IF is exactly same to the If we use in literature of English. it play an important role in conditional branching. IF basically check the condition whether it is true or false, if it is true it executes the block of itself if not then jump out of loop or skips the if loop. Let us take a real life example of it

If( weather==cloudy)
It will rain.

-------------------------------------------------------------

If (cloudy weather== 1)
{
Printf(“It will rain”);
}

You can identify the similarity between the IF in English and in C language. Now, we will deal with ‘IF’ in more technical way or say let us use it programmatically. ‘IF’ is a strict comparison feature in C. ‘IF’ always look for exact comparison. Let us take the example

Main()
{
Float me=1.1;
Double you=1.1;

If(me==you)
{
Printf(“Waw! We are same”);
}
Else
Printf(“Nope! We are different”);
}

Here u must be wondering with strange word ‘ELSE’, don’t you? We will be coming to that just after the explanation of this program.

Here the values assigned to variable me and you is same, so we easily conclude that comparison will return a true or positive non-zero value and print statement in that block will get executed. One more term is there we should look for before concluding the answer and that is data type of both the variables. Variable me is of float type and you is of double type. And after referring to article 1 on data types we come to know that float and double are two different types of storing data. They differ in the number of precisions after decimal and so they require different amount of memory blocks as float requires 4 bytes while double requires 8 bytes. Hence the values assigned to float me and double you though they are same their representation in memory is different in fact and therefore the program result the answer saying “ No! We are different”.
Now, let us come to the ‘stranger’ i.e. ELSE. ‘ELSE’ is a follower of ‘IF’ but not always. Sometimes we only need ‘IF’ statement, and sometimes both ‘IF’ and ‘ELSE’. ‘ELSE’ again works exactly according to its literal meaning. Again lets take that real time example. If the condition returns zero, sometimes you want the program do something else. In that case, after the if statement, you use an else statement.


If( weather==cloudy)

It will rain.
Else
It will not rain
--------------------------------------------------------------------

If (cloudy weather== 1)
{
Printf(“It will rain”);
}
Else
{
Printf(“It will not rain”);
}

‘ELSE’ always gets executed when the condition in IF statement is false. So, it means that a ELSE block should contain something which we want to get executed if the condition in IF statements results false value or zero value.
One more provision for conditional branching is there in C language that we call ‘ELSEIF’. If we have multiple conditions to check and wish to execute separate block for each condition then it is always a good practice to use elseif than multiple IF statements. Let’s have a look at following example.

#include

int main() {
int a;

printf("Input an integer and push return:\n");
scanf("%d", &a);

if(a%2==0 && a<0) { printf("%d is even and less than zero.\n", a); } else if (a%2!=0 && a<0) { printf("%d is odd and less than zero.\n", a); } else if (a%2==0 && a>0)
{
printf("%d is even and greater than zero.\n", a);
}
else if (a%2!=0 && a>0)
{
printf("%d is odd and greater than zero.\n", a);
}
else
{
printf("You entered zero.\n");
}

return 0;
}

the program output will depend on the value you enter.
The main focus is on the if block, with the solitary if and else statements, as well as the else ifs.
Now, the program evaluates the if condition. If it returns a non zero value, the if branch is executed. Once all the statements in that branch have been executed, THE PROGRAM IGNORES THE REST OF THE IF BLOCK. In other words, the remaining conditions are not evaluated.
If, on the other hand, (a%2==0 && a<0) returns zero, the first else if condition is evaluated and so on.
The main thing to remember is that once the program chooses a branch in the if block, the remaining branches are totally ignored.

One final note: I tend not to end an if block on an else if.

If one wanted to say, "else do nothing", rather than missing the else statement totally, its always better to insert a else block containing nothing.


if(x==0)
{
printf("x is zero\n");
}
else if(x==1)
{
printf("x is 1\n");
}
else
{
/* Do nothing */
}

Wednesday, October 28, 2009

C Language :Data Type

A programming language is proposed to help programmer to process certain kinds of data and to provide useful output. The task of data processing is accomplished by executing series of commands called program. A program usually contains different types of data value and hence one must specify the type. A variable is nothing but a name of memory location where we store or keep the data, but prior to this compiler expects declaration of specific form of value to be stored in memory location and for that a concept of data types is used. C language supports pre-declaration strategy i.e. one must specify the (form) type of variable before its' use. The declaration of variable with certain data type actually specifies the value contained in variable. C has different data types for different types of data and can be broadly classified as :
  • Primary data types.
  • Secondary data types
    Primary data types consist following data types.
Data Types in C

Integer types:
Integers are whole numbers with a range of values, range of values are machine dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32768 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for number. To control the range of numbers and storage space, C has three classes of integer storage namely short int, int and long int. All three data types have signed and unsigned forms. A short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned integers are always positive and use all the bits for the magnitude of the number. Therefore the range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a longer range of values and it occupies 4 bytes of storage space.
Syntax: int ; like int num1; short int num2; long int num3;
Example: 5, 6, 100, 2500.


Integer Data Type Memory Allocation


Floating Point Types:
The float data type is used to store fractional numbers (real numbers) with 6 digits of precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision and takes double space (8 bytes) than float. To extend the precision further we can use long double which occupies 10 bytes of memory space.
Syntax: float ; like float num1; double num2; long double num3;
Example: 9.125, 3.1254.

Floating Point Data Type Memory Allocation

Character Type:
Character type variable can hold a single character. As there are singed and unsigned int (either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have values between 0 and 255, signed characters have values from –128 to 127.
Syntax: char ; like char ch = ‘a’;
Example: a, b, g, S, j.


Void Type:
The void type has no values therefore we cannot declare it as variable as we did in case of integer and float. The void data type is usually used with function to specify its type. Like in our first C program we declared “main()” as void type because it does not return any value.


Regards:
Ajit R Pandey,

Tuesday, October 27, 2009

C Theory Learning: Ajit Pandey

Dear Students,
Hi, finally we have started with some extra curricular activities in the form of C : A Practical Approach . It is in fact a good way to exercise your C programming skill in short span of time. And as you all must know that we are trying strongly to start up with value addition classes for all non computer graduates of MCA-I and hopefully we will soon come up with it as well. But when I was thinking of the benefits of the exercise we have already started a thought suddenly came to my mind that why not to create a BLOG wherein 1 article about C language will posted and in comment to that you can online ask questions to me and I will be able to reply it within minutes. And you need not to every time roam around for faculty members for getting your problem solved. And this is something we can continue for upcoming all semesters moreover for upcoming batches.The basic intension behind all this is to add something more to your technical knowledgebase from all perspective. But as I always keep telling to you all, every activity is response dependant, better you respond longer it survive.From tomorrow we can start with this wherein I will be posting one article on any C language topic and in comment just below that you can post your questions. And the answer or solution to that will be sent to you very next day; in this way we will be able to learn C (Theory) online.So guys and gals, healthy response will boost me to do better and more useful stuff for you.Do write comment on this to get your views and suggestions.

Followers