Tuesday, May 6, 2008

Basic C programming answers

1)Program to find number of 1s and zeros in given integer.
Find the answer here http://gucatheprogrammer.blogspot.com/2007/10/simple-yet-useful-c-programs.html

2)Write a C program to check whether machine is Big endian OR little endian
#include

int main()
{
unsigned int n = 1;
char *p;

p = (char*)&n;
if (*p == 1)
printf("Little Endian\n");
else if (*(p + sizeof(int) - 1) == 1)
printf("Big Endian\n");
else
printf("What the crap?\n");

return 0;
}
3)C program to Convert decimal to binary
Find the answer here http://gucatheprogrammer.blogspot.com/2007/10/simple-yet-useful-c-programs.html

4)C program to do STRCPY without using strcpy
I will write just the function :
char * mystrcpy(char * dest,const char *src)
{
char *temp = dest;
while ((*dest++ = *src++) != '\0')
return temp;
}

5)C program to STRCAT without using strcat
char * mystrcat(char * dest, const char * src)
{
char *temp = dest;
while (*dest)
dest++;
while ((*dest++ = *src++) != '\0') ;
return temp;
}

6)Write a C macro which returns number of seconds in year
This is too general. This is just to check guy knows about the MACRO and its syntax.
#define NUMER_OF_SECONDS_YEAR (365*24*60*60)

7)C program to find sum of digits of any given integer number .
#include
int add_digits(int a);
main()
{
int a ;
printf("Enter the number\n");
scanf("%d", &a);
printf("Sum of digits = %d\n", add_digits(a));
}
int add_digits(int num)
{
int sum = 0;
while(num)
{
sum += num%10;
num /=10;
}
return sum;
}

8)C program to fine leap year or not
This is just to check how quick he can write ..
Better would be macro or function.
#include
main()
{
int year;
printf("Enter the year\n");
scanf("%d", &year);
if(year % 4 == 0){
printf("Given year is leap\n");
} else {
printf("Given year is NOT leap\n");
}
}

9)C program to swap two variables (using pointers), without using temp variable.
#include
void swap(int *p1, int *p2);
main()
{
int a, b;
printf("Enter the values for a and b\n");
scanf("%d%d",&a,&b);
swap(&a, &b);

printf("a = %d\n and b = %d\n", a, b);
}

void swap(int *p1, int *p2)
{
*p1 = *p1 + *p2;
*p2 = *p1 - *p2;
*p1 = *p1 - *p2;
return;

}

10)C program to find sum of given Array.
#include
int arr_sum(int *a, int size);
main()
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int sum = arr_sum(a,10);
printf("SUM = %d\n", sum);
}
int arr_sum(int *a, int size)
{
int sum = 0, i;
for(i =0; i
#define MIN(a,b) ((a>b)?b:a)
main()
{
int a=100, b=20;
printf("MIN = %d\n", MIN(a,b));

}

The below ones are left as exercise to students :) .. Actually I got bored to write :)
12)C program to find largest of three numbers
13)C program to store data for 10 student info
14)Write all infinite loops u can think off