Introduction To Programming

Why programs ? Programming is nothing but making the computers think the same way a human thinks. Programs are made for obtaining a specific solution which can even be solved by humans which when solved by us may consume time..

Friday, October 30, 2009

Print String using integer:

Print String using integer:

Type casting:

Type casting is used to change the variable data_type from one to another data_type temporarily for the expression.

Eg:
char c=’a’;
int i=(int)c;

in this c is converted from char to int for temporarily. It’ll give integer equivalent of that character. Small a integer value is 97(ASCII). so i=97 .

#include < stdio.h >
void main()
{
int i;
char a[5]=”selva”;
for(i=0;i<5;i++)
{
printf(“%c”,((char*)i[&a]);
}
}

Output:
Selva

How?
Are you amaze with the output ?
i is an integer value using type casting we can convert it into another data type.
Here ((char*)i) will convert i into character pointer. In square brackets address of
a is given. This will make ((char*i)[&a] is point to ith place of string a.

consider a starting address is 1000 then characters will store in a string like this





















10001001100210031004
selva
a[0]a[1]a[2]a[3]a[4]


in for loop at first i=0, &a=1000
((char*)i[&a] will point to 0th place of 1000.
and It’ll print s
now i’ll increase i=1,&a=1000
((char*)i[&a] will point to 1th place of 1000.
And it’ll print e
Now I’ll increase i=2,&a=1000
((char*a)i[&a] will point to 2th place of 1000
So It’ll print l
now i=3,&a=1000
((char*a)i[&a] will point to 3rd place of 1000
So it’ll print v
Now i=4,&a=1000
((char*a)i[&a] will print 4th place of 1000.
So it’ll print a.

Logical programs :

#include < stdio.h >
void main()
{
int a,b;
b=1;
if(a=b);
else
a=2;
a=3;
printf(“%d \t%d “,a,b);
while(b<3)
a+=++b;
printf(“\n %d \t %d”,a,b);
}

What’s the output? Can you answer it ? or it’ll make error?
It’ll successfully run without compilation errors.

Output:

3 1
8 3

How?
At first b=1
As per I said before , it can possible to assign value for variables in if and also if can end with semicolon
if(a=b);
is equivalent to
if(a=b)
{
}

Now a =1
if(a=b) i.e. if(1)
so it won’t go to else part.
So a=3
In while b<3
a+=++b is equivalent to a=a+(++b)
at first b=1 ,a=3
1<3 true so a=3+(2)=5 ,b=2
2<3 true so a=5+(3)=8, b=3
3<3 false
Now a=8 b=3