# C Aptitude: Endianness, Pointer Arithmetic

C Aptitude 31

C program is one of most popular programming language which is used for core level of coding across the board. C program is used for operating systems, embedded systems, system engineering, word processors,hard ware drivers, etc.

In this site, we have discussed various type of C programs till date and from now on, we will move further by looking at the C aptitude questions.

In the coming days, we will post C aptitude questions, answers and explanation for interview preparations.

The C aptitude questions and answers for those questions along with explanation for the interview related queries.

We hope that this questions and answers series on C program will help students and freshers who are looking for a job, and also programmers who are looking to update their aptitude on C program.
Some of the illustrated examples will be from the various companies, and IT industry experts.
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.

Predict the output or error(s) for the following:

C aptitude 31.1

main() {
int i = 258;
int *iPtr = &i;
printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}

Explanation: The integer value 257 can be represented in binary as, 00000001 00000001. Remember that the INTEL machines are ‘small-endian’ machines. Small-endian means that the lower order bytes are stored in the higher memory addresses and the higher order bytes are stored in lower addresses. The integer value 258 is stored in memory as: 00000001 00000010.

C aptitude 31.2

main() {
int i=300;
char *ptr = &i;
*++ptr=2;
printf("%d",i);
}

Explanation:The integer value 300  in binary notation is: 00000001 00101100. It is  stored in memory (small-endian) as: 00101100 00000001. Result of the expression *++ptr = 2 makes the memory representation as: 00101100 00000010. So the integer corresponding to it  is  00000010 00101100 => 556.

C aptitude 31.3

main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
least = ((*ptr)<(least))?(*ptr):(least);
printf("%d", least);
}

Explanation: After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is ‘’. So the value of ‘str’ is less than that of ‘least’. So the value of ‘least’ finally is 0.

Learn C Programming
C Aptitude
C Interview questions

You can easily select the code by double clicking on the code area above. To get regular updates on new C programs, you can Follow @c_program You can discuss these programs on our Facebook Page. Start a discussion right now,

(you can send this program to your friend using this button) Like to get updates right inside your feed reader? Grab our feed!
To browse more C Programs visit this link. Or if you can’t find the program you are looking for, you can contact [email protected]. Thank you for visiting.

(c) www.c-program-example.com

# C Program to implement bucket sort

Write C program to implement bucket sort.
The idea of Bucket Sort is to divide the interval [0, 1] into n equal-sized sub intervals, or buckets, and then distribute the n input numbers into the buckets. To produce the output, we simply sort the numbers in each bucket and then go through the buckets in order, listing elements in each.
Bucket sort runs in linear time when the input is drawn from a uniform distribution. Read more about C Programming Language .
/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
*                      Happy Coding
***********************************************************/

#include<stdio.h>
void Bucket_Sort(int array[], int n)
{
int i, j;
int count[n];
for(i=0; i < n; i++)
{
count[i] = 0;
}
for(i=0; i < n; i++)
{
(count[array[i]])++;
}
for(i=0,j=0; i < n; i++)
{
for(; count[i]>0;(count[i])--)
{
array[j++] = i;
}
}
}
int main()
{
int array[100];
int num;
int i;
printf("Enter How many Numbers : ");
scanf("%d",&num);
printf("Enter the %d elements to be sorted:n",num);
for(i = 0; i < num; i++ )
{
scanf("%d",&array[i]);
}
printf("nThe array of elements before sorting : n");
for (i = 0;i < num;i++)
{
printf("%d ", array[i]);
}
printf("nThe array of elements after sorting : n");
Bucket_Sort(array, num);
for (i = 0;i < n;i++)
{
printf("%d ", array[i]);
}
printf("n");
return 0;
}

Data Structures

C Sorting

You can easily select the code by double clicking on the code area above.

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

(you can send this program to your friend using this button)

To browse more C Programs visit this link
Or if you can’t find the program you are looking for, you can contact [email protected]. Thank you for visiting.

(c) www.c-program-example.com

# C Aptitude Questions and answers with explanation

C Aptitude 29
C program is one of most popular programming language which is used for core level of coding across the board. C program is used for operating systems, embedded systems, system engineering, word processors,hard ware drivers, etc.

In this site, we have discussed various type of C programs till date and from now on, we will move further by looking at the C aptitude questions.

In the coming days, we will post C aptitude questions, answers and explanation for interview preparations.

The C aptitude questions and answers for those questions along with explanation for the interview related queries.

We hope that this questions and answers series on C program will help students and freshers who are looking for a job, and also programmers who are looking to update their aptitude on C program.
Some of the illustrated examples will be from the various companies, and IT industry experts.
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.

Predict the output or error(s) for the following:

C aptitude 29.1

enum colors {BLACK,BLUE,GREEN}
main()
{

printf("%d..%d..%d",BLACK,BLUE,GREEN);

return(1);
}

Explanation: enum assigns numbers starting from 0, if not explicitly defined.

C aptitude 29.2

void main()
{
char far *farther,*farthest;

printf("%d..%d",sizeof(farther),sizeof(farthest));

}

Explanation: The second pointer is of char type and not a far pointer

C aptitude 29.3

main()
{
int i=400,j=300;
printf("%d..%d");
}

Explanation: printf takes the values of the first two assignments of the program. Any number of printf’s may be given. All of them take only the first two.

Learn C Programming
C Aptitude
C Interview questions

You can easily select the code by double clicking on the code area above.

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

(you can send this program to your friend using this button)

To browse more C Programs visit this link
(c) www.c-program-example.com

# C Aptitude Questions and answers with explanation

C Aptitude 24
C program is one of most popular programming language which is used for core level of coding across the board. C program is used for operating systems, embedded systems, system engineering, word processors,hard ware drivers, etc.

In this site, we have discussed various type of C programs till date and from now on, we will move further by looking at the C aptitude questions.

In the coming days, we will post C aptitude questions, answers and explanation for interview preparations.

The C aptitude questions and answers for those questions along with explanation for the interview related queries.

We hope that this questions and answers series on C program will help students and freshers who are looking for a job, and also programmers who are looking to update their aptitude on C program.
Some of the illustrated examples will be from the various companies, and IT industry experts.
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.

Predict the output or error(s) for the following:

C aptitude 24.1

main()
{
printf("%x",-1<<4);
}

Explanation: -1 is internally represented as all 1’s. When left shifted four times the least significant 4 bits are filled with 0’s.The %x format specifier specifies that the integer value be printed as a hexadecimal value.

C aptitude 24.2

main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}

Answer: Compiler Error : Type mismatch in redeclaration of function display

Explanation:In third line, when the function display is encountered, the compiler doesn’t know anything about the function display. It assumes the arguments and return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs.

C aptitude 24.3

main()
{
int c=- -2;
printf("c=%d",c);
}

Explanation: Here unary minus (or negation) operator is used twice. Same maths rules applies, ie. minus * minus= plus.
Note: However you cannot give like –2. Because — operator can only be applied to variables as a decrement operator (eg., i–). 2 is a constant and not a variable.

Learn C Programming
C Aptitude
C Interview questions

You can easily select the code by double clicking on the code area above.

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

(you can send this program to your friend using this button)

To browse more C Programs visit this link
(c) www.c-program-example.com

# C Aptitude Questions and answers with explanation

C Aptitude 14
C program is one of most popular programming language which is used for core level of coding across the board. C program is used for operating systems, embedded systems, system engineering, word processors,hard ware drivers, etc.

In this site, we have discussed various type of C programs till date and from now on, we will move further by looking at the C aptitude questions.

In the coming days, we will post C aptitude questions, answers and explanation for interview preparations.

The C aptitude questions and answers for those questions along with explanation for the interview related queries.

We hope that this questions and answers series on C program will help students and freshers who are looking for a job, and also programmers who are looking to update their aptitude on C program.
Some of the illustrated examples will be from the various companies, and IT industry experts.
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.

Predict the output or error(s) for the following:

C aptitude 14.1

main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}

Explanation: in the end of nested structure yy a member have to be declared

C aptitude 14.2

main()
{
extern int i;
i=20;
printf("%d",sizeof(i));
}

Explanation:extern declaration specifies that the variable i is defined somewhere else. The compiler passes the external variable to be resolved by the linker. So compiler doesn’t find an error. During linking the linker searches for the definition of i. Since it is not found the linker flags an error.

C aptitude 14.3

main()
{
printf("%d", out);
}

int out=100;

Answer: Compiler error: undefined symbol out in function main.

Explanation: The rule is that a variable is available for use from the point of declaration. Even though a is a global variable, it is not available for main.

Learn C Programming
C Aptitude
C Interview questions

You can easily select the code by double clicking on the code area above.

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

(you can send this program to your friend using this button)

To browse more C Programs visit this link
(c) www.c-program-example.com

# C Program to find day of birth from DOB

### Problem Statement

Write a C Program to find the day of birth when date of birth is given. For example, if we give 02/04/2107  (02nd April 2017) as input, the program should output that it was a Sunday.

### Solution

1. Pick a year as base year where January 1st falls on a Monday. We are using 1900 as base year in our program.
2. Then we find the number of years after base year. Day of the week in the beginning of the year shifts by 1 in every non leap year. 365 days -> 52 * 7 + 1.
3. Once we know on what day a given year started, we can calculate each month’s starting day.
4. From there it’s as simple as counting the days and finding which day it is.

In this program we find the day of birth like Monday, Sunday.. when date of birth is given. For a more detailed explanation of the method can be found here Converting a Month-Date-Year to the Day of the Week

### The Program

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 #include #include int main() { int d, m, y, year, month, day, i; printf("Enter date of birth (DD MM YYYY) :"); scanf("%d %d %d", &d, &m, &y); if( (d > 31) || (m > 12) || (y < 1900 || y >= 2100) ) { printf("INVALID INPUT. Please enter a valid date between 1900 and 2100"); exit(0); } year = y-1900; year = year/4; year = year+y-1900; switch(m) { case 1: case 10: month = 1; break; case 2: case 3: case 11: month = 4; break; case 7: case 4: month = 0; break; case 5: month = 2; break; case 6: month = 5; break; case 8: month = 3; break; case 9: case 12: month = 6; break; } year = year + month; year = year + d; /* Need to make sure extra day is not needed in leap year for dates before March */ if(( y > 1900 ) && ( y % 4 == 0 ) && ( m < 2 ) ) year--; day = year % 7; switch(day) { case 0: printf("Day is SATURDAY\n"); break; case 1: printf("Day is SUNDAY\n"); break; case 2: printf("Day is MONDAY\n"); break; case 3: printf("Day is TUESDAY\n"); break; case 4: printf("Day is WEDNESDAY\n"); break; case 5: printf("Day is THURSDAY\n"); break; case 6: printf("Day is FRIDAY\n"); break; } return 0; }
view raw day_of_birth.c hosted with ❤ by GitHub

### Sample Output

To browse more C Programs visit this List of C Programs

(c) www.c-program-example.com

# C program to print all the possible permutations of given digits

Write a C program to print all the possible permutations of given digits.
Permutations means possible way of rearranging in the group or set in the particular order.
Example:
Input:1, 2, 3
Output:1 2 3, 1 3 2, 2 1 3, 3 1 2, 2 3 1, 3 2 1
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int lev=-1,n,val[50],a[50];
void main()
{
int i,j;
clrscr();
printf("Enter how many numbers?n");
scanf("%d",&n);
printf("nEnter %d numbers:nn",n);
for(i=0;i<n;i++)
{
val[i]=0;
j=i+1;
scanf("%dnn",&a[j]);
}
visit(0);
getch();
}
visit(int k)
{
int i;
val[k]=++lev;
if(lev==n)
{
for(i=0;i<n;i++)
printf("%2d",a[val[i]]);
printf(" ");
}
for(i=0;i<n;i++)
if(val[i]==0)
visit(i);
lev--;
val[k]=0;

}
Learn C Programming
Recursion
Number System

You can easily select the code by double clicking on the code area above.

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

(you can send this program to your friend using this button)

To browse more C Programs visit this link
(c) www.c-program-example.com

# C Program to toss a coin using random function.

Write a c program to toss a coin using random function.
In this Program,We use the rand()%2 function that will compute random integers 0 or 1.
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main(void) {
int toss = 0;
int call = 0;
srand(time(NULL));

toss = rand() % 2;

printf("Say head or tail! press 0 for head and 1 for tail:nn");
scanf("%d", &call);
if(call==0 || call==1)
{
if(toss == call)
{
if(toss==1)
printf("You called it correctly ... it is tailn");
else
printf("You called it correctly ... it is headn");
}
else
{
if(toss==1)
printf("No way ...it is head !n");
else
printf("No way ... it is tail!n");
}
}
else
printf("Invalid call!!!!!nn");
return 0;
}
Learn C Programming
Recursion
Number System

You can easily select the code by double clicking on the code area above.

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

(you can send this program to your friend using this button)

To browse more C Programs visit this link
(c) www.c-program-example.com

# C Program to lock file using semaphores.

Write a C Program to lock file using semaphores.
Using semaphores, We can control access to files, shared memory and other things. The basic functionality of a semaphore is that you can either set it, check it, or wait until it clears then set it (“test-n-set”). In C semaphores functions defined in the sys/sem library. Read more about C Programming Language . and read the C Programming Language (2nd Edition) by K and R.

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdio.h>
#include <sys/file.h>
#include <error.h>
#include <sys/sem.h>
#define MAXBUF 100
#define KEY 1216
#define SEQFILE "seq_file"
int semid,fd;
void my_lock(int);
void my_unlock(int);
union semnum
{
int val;
struct semid_ds *buf;
short *array;
}arg;
int main()
{
int child, i,n, pid, seqno;
char buff[MAXBUF+1];
pid=getpid();
if((semid=semget(KEY, 1, IPC_CREAT | 0666))= = -1)
{
perror("semget");
exit(1);
}
arg.val=1;
if(semctl(semid,0,SETVAL,arg)<0)
perror("semctl");
if((fd=open(SEQFILE,2))<0)
{
perror("open");
exit(1);
}
pid=getpid();
for(i=0;i<2;i++)
{
my_lock(fd);
lseek(fd,01,0);
{
exit(1);
}
printf("pid:%d, Seq no:%dn", pid, seqno);
seqno++;
sprintf(buff,"%dn", seqno);
n=strlen(buff);
lseek(fd,01,0);
if(write(fd,buff,n)!=n)
{
perror("write");
exit(1);
}
sleep(1);
my_unlock(fd);
}
}
void my_lock(int fd)
{
struct sembuff sbuf=(0, -1, 0);
if(semop(semid, &sbuf, 1)= =0)
printf("Locking: Resource…n");
else
printf("Error in Lockn");
}
void my_unlock(int fd)
{
struct sembuff sbuf=(0, 1, 0);
if(semop(semid, &sbuf, 1)= =0)
printf("UnLocking: Resource…n");
else
printf("Error in Unlockn");
}
C Basic
C Strings

You can easily select the code by double clicking on the code area above.

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

(you can send this program to your friend using this button)

To browse more C Programs visit this link
(c) www.c-program-example.com

# C Program to implement Simpson method.

Write a C Program to implement Simpson method.
Simpson method is used for approximating integral of the function.
Simpson’s rule also corresponds to the 3-point Newton-Cotes quadrature rule.
In this program, We use the stack to implement the Simpson method. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>

#include<conio.h>

#include<math.h>

char post_fix[80];

float stack[80];

char stack1[80];

int top=-1,top1=-1;

float eval(char post_fix[], float x1);

void infix_post_fix(char infix[]);

main()

{

float x0, xn, h, s,e1,e2, e3;

char exp[80], arr[80];

int i,n,l=0;

clrscr();

printf("nEnter an expression: nn");

gets(exp);

puts("nnEnter x0, xn and number of sub-intervals: nn");

scanf("%f%f%d", &x0, &xn, &n);

h=(xn-x0)/n;

if(exp[0]=='l'&& exp[1]=='o'&& exp[2]=='g')

{

l=strlen(exp);

for(i=0;i<l-3; i++)

arr[0]=exp[i+3];

arr[i]=";

infix_post_fix(arr);

e1=eval(post_fix,x0);

e2=eval(post_fix,xn);

e3=4*eval(post_fix, x0+h);

s=log(e1)+log(e2)+log(e3);

for (i=3;i<=n-1;i+=2)

s+=4*eval(post_fix,x0+i*h)+2*eval(post_fix, x0+(i-1)*h);

}

else

{

infix_post_fix(exp);

s=eval(post_fix,x0)+eval(post_fix,xn)+4*eval(post_fix, x0+h);

for (i=3;i<=n-1;i+=2)

s+=4*eval(post_fix,x0+i*h)+2*eval(post_fix, x0+(i-1)*h);

}

printf("nnThe value of integral is %6.3fn",(h/3)*s);

return(0);

}

/*Inserting the operands in a stack. */

void push(float item)

{

if(top==99)

{

printf("ntThe stack is full");

getch();

exit(0);

}

else

{

top++;

stack[top]=item;

}

return;

}

/*Removing the operands from a stack. */

float pop()

{

float item;

if(top==-1)

{

printf("ntThe stack is emptynt");

getch();

}

item=stack[top];

top–;

return (item);

}

void push1(char item)

{

if(top1==79)

{

printf("ntThe stack is full");

getch();

exit(0);

}

else

{

top1++;

stack1[top1]=item;

}

return;

}

/*Removing the operands from a stack. */

char pop1()

{

char item;

if(top1==-1)

{

printf("ntThe stack1 is emptynt");

getch();

}

item=stack1[top1];

top1–-;

return (item);

}

/*Converting an infix expression to a postfix expression. */

void infix_post_fix(char infix[])

{

int i=0,j=0,k;

char ch;

char token;

for(i=0;i<79;i++)

post_fix[i]=' ';

push1('?');

i=0;

token=infix[i];

while(token!=")

{

if(isalnum(token))

{

post_fix[j]=token;

j++;

}

else if(token=='(')

{

push1('(');

}

else if(token==')')

{

while(stack1[top1]!='(')

{

ch=pop1();

post_fix[j]=ch;

j++;

}

ch=pop1();

}

else

{

while(ISPriority(stack1[top1])>=ICP(token))

{

ch=pop1();

post_fix[j]=ch;

j++;

}

push1(token);

}

i++;

token=infix[i];

}

while(top1!=0)

{

ch=pop1();

post_fix[j]=ch;

j++;

}

post_fix[j]=";

}

/*Determining the priority of elements that are placed inside the stack. */

int ISPriority(char token)

{

switch(token)

{

case '(':return (0);

case ')':return (9);

case '+':return (7);

case '-':return (7);

case '*':return (8);

case '/':return (8);

case '?':return (0);

default: printf("nnInvalid expression");

}

return 0;

}

/*Determining the priority of elements that are approaching towards the stack. */

int ICP(char token)

{

switch(token)

{

case '(':return (10);

case ')':return (9);

case '+':return (7);

case '-':return (7);

case '*':return (8);

case '/':return (8);

case ":return (0);

default: printf("nnInvalid expression");

}

return 0;

}

/*Calculating the result of expression, which is converted in postfix notation. */

float eval(char p[], float x1)

{

float t1,t2,k,r;

int i=0,l;

l=strlen(p);

while(i<l)

{

if(p[i]==’x')

push(x1);

else

if(isdigit(p[i]))

{

k=p[i]-'0′;

push(k);

}

else

{

t1=pop();

t2=pop();

switch(p[i])

{

case '+':k=t2+t1;

break;

case '-':k=t2-t1;

break;

case '*':k=t2*t1;

break;

case '/':k=t2/t1;

break;

default: printf("ntInvalid expression");

}

push(k);

}

i++;

}

if(top>0)

{

printf("You have entered the operands more than the operatorsnn");

exit(0);

}

else

{

r=pop();

return (r);

}

return 0;

}

Data Structures

Learn C Programming

You can easily select the code by double clicking on the code area above.