Sie sind auf Seite 1von 11

1/7/2015

CProgramsfortechnicalinterviews
Google Search...

Home

WP Plugins

WordPress

Web & Dev

Linux

Academic

Internet

Projects

Downloads

Home Academic Programming C & C++ C & C++ Sample Prorgams 10 C programs you must know before appearing for technical interviews

Sponsors

10 C programs you must know


before appearing for technical
interviews
Posted by arnab on Jul 25, 2012 |

22 comments

AdvertiseHere

SRM B.Tech
Admission 2015

Software Testing
Courses

srmuniv.ac.in/Admissions

shiksha.com/Software-Testing

Admissions open. Apply online for


Engineering through SRMJEEE.

Find Top Training Centers in India.


Get Info on
Courses,Admission,Fees.

AdvertiseHere

AdvertiseHere

AdvertiseHere

AdvertiseHere

If you havent opened Turbo C++ for more than a year and the campus
placements are not very far away then you are at the correct place. The
interviewers have a thing for C programs and theres a great chance you
might be bombarded with them on the interview day. Ive compiled 10
programs that are very common and has been asked numerous times in
the interviews. Most importantly if you practice these programs you get
to revise the whole syllabus. I tried to include as many concepts as
possible keeping in mind the difficulty level matched the level of the interview questions. If you dont
get any of these questions in the interview feel free to sue this websites admin..

Powered By

Click here to check

out 10 java programs for technical interview.

#1: Swap two numbers (without using a


temporary variable)
Now there are a number of ways you can do this program but there is one way you can really impress
the interviewer which uses this cool technique using bitwise operators.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18

//Sortingwithoutusingtemporaryvariables
#include
#include
intmain(){
inta,b;
printf("Beforeswapping:\n");
printf("Entervalueofa:");
scanf("%d",&a);
printf("Entervalueofb:");
scanf("%d",&b);
//Sortingusing
a=a^b;//usesxoroperator
b=a^b;//toswapthevalues
a=a^b;//ofaandb
printf("Afterswapping:\n");
printf("Valueofa:%d\nValueofb:%d",a,b);
getch();
}

InTechgrity & Prod

Follow up questions:

Follow

+1

+ 34
Like 865peoplelikethis.

RecommendonGoogle

Follow@swashata

1,312followers

Enteryouremail
Subscribe

1.
RSSFeed

http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

Pinterest

GooglePlus

1/11

1/7/2015

CProgramsfortechnicalinterviews
DownloadFreebies

2.

Recent Projects

#2: Patterns (one of their favorites)


If the interviewer asks you a pattern and you dont know how to do that you are screwed big time.

WP Category Post List version 2 released

Often you might make a very simple mistake which the interviewer was actually looking for. Here well

iTg Sexy Horizontal 1 tier Dropdown menu

find out how to print this pattern

WP Simple Event Management Plugin by iTg Manage college fests and events

1
2
3
4
5

ABCDEDCBA
ABCDCBA
ABCBA
ABA
A

filtered by categories with thumbnails


Move Intense Debate Comment from Blogger
to WordPress using Export XML ~ First WP

And here is the code.


01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21

//Printingpattern
#include
#include
intmain(){
intn,i,j;
printf("Enternooflines:");
scanf("%d",&n);
for(i=0;i<n;i++){
for(j=0;j<i;j++){//forprintingspaces
printf("");
}
for(j=0;j<ni;j++){//forprintingtheleftside
printf("%c",'A'+j);//thevalueofjisaddedto'A'(asciivalue=65)
}
for(j=ni2;j>=0;j){//forprintingtherightside
printf("%c",'A'+j);
}
printf("\n");
}
getch();
}

WP Category Post List Plugin - List your posts

plugin by iTg
?

jQuery Fade n Slide Button Animator Plugin by


iTg
Fade In n Out Animation on hover w/ jQuery to
make image Buttons
Browse more Projects

Wordpress Stuff
Add dynamic Login Logout n Site Admin button
to Wordpress using WP API
The concept behind making an Interactive
Wordpress Custom Page

Follow up questions:

Five WordPress Plugins You Should be Using


Turn your WordPress blog into Feedback,
Survey or Quiz site using WP Feedback & Survey
Manager Plugin

1.

WordPress Advertisement Management with


Revenue Sharing - Coming soon

2.

Howto: Move WordPress site to another Host


remotely without downtime and downloading
Pros and Cons of using WordPress JetPack
comments on your self hosted blog

#3: Finding the nth Fibonacci number using


recursion

Creating default options on your WordPress


Plugin Installation - Options API #2

There are two rules in recursion:

Automatic login redirect to primary site & block


main site admin - WordPress MultiSite

i. The function must have a recursive definition or in simple words can be expressed in its own form.

Browse more WordPress stuff

ii. There is a terminating value for which we know the return value of the function.
We have to make a function fibonacci in a recursive form. Well make a function fibonacci() and make
them follow the above rules:
i. fibonacci(x) = fibonacci(x-1) + fibonacci(x-2) (recursive definition)
ii. if x==0 or x==1 then return 1 (terminating step)
Now we are good to write the code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18

#include
#include
inty;
fibonacci(intx){
if(x==1||x==0)//terminatingstep
returnx;
y=fibonacci(x1)+fibonacci(x2);//recursivedefinition
returny;
}
intmain(){
inta,r;
printf("Entertheposition:");
scanf("%d",&a);
r=fibonacci(a);
printf("Thenumberatposition%dis%d",a,r);
getch();
return0;
}

Follow up questions:
1.
http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

2/11

1/7/2015

CProgramsfortechnicalinterviews

2. What if we pass a negative number to the fibonacci()


?

#4: Armstrong number


You have done great so far but dont try to do the whole tutorial all at once. Take some rest and come
back later but if u want a challenge then continue. Now what is an Armstrong number? If a number has

n digits and the sum of the nth power of its digits is the number itself then the number is an
Armstrong number. Surely you got confused. Here are some examples to help you out.

214
Like

4
Tweet

98

5^1=5 (so its an Armstrong number)

1.
2.

1^4+6^4+3^4+4^4=1634 (so its another Armstrong number)

#2: Patterns (one of


favorites)

Dont scratch your head if you cant do it yourself. The code is given below. Feel free to peek.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

#include
#include
voidcheckArmstrong(inttemp){
intsum=0,remainder,num=temp,noOfDigits=0;
while(temp!=0){//countsnoofdigits
noOfDigits++;
temp=temp/10;
}
temp=num;
while(temp!=0){//calculatesthesumofthedigits
remainder=temp%10;//tothepowernoOfDigits
sum=sum+pow(remainder,noOfDigits);
temp=temp/10;
}
if(num==sum)//checksifthenumberisanarmstrongno.ornot
printf("%disanarmstrongnumber.",num);
else
printf("%disnotanarmstrongnumber.",num);
}

intmain(){
intn;
printf("Enteranumber:");
scanf("%d",&n);
checkArmstrong(n);
getch();
return0;
}

Navigate (TOC)

#1: Swap two numbe


(without using a tem
variable)

1.
2.

#3: Finding the nth F


number using recurs

1.
2. What if we pass
number to the fibo

#4: Armstrong numb

1. Is 0 an Armstron
number?
2. How many 2 dig
numbers are Arms
numbers?
3. Why aren't there
follow up question
program?

#5: Concatenate two


without using strcat(

1.
2. What if we don't
end of the string?

#6: Sort elements of


using pointers (selec
technique)

1. What is the bub


technique?
2. What are the oth
techniques that ar
during the intervie

Follow up Questions:

#7: Enter and print d


employees using stru
and dynamic memor
allocation

1. Is 0 an Armstrong number?

1. What is malloc?
2. What are the oth
functions used in d
memory allocation
allocation?
3. Why using a link
do this program be
option?

2. How many 2 digit numbers are Armstrong numbers?

#8: Tower of Hanoi u


recursion

1. Can we write of
without using recu

3. Why aren't there any follow up question on the


program?

#9: Add numbers us


Command line argum

1. How can i run th


program?
2. What if i run it in
way?

#5: Concatenate two strings without using


strcat()

#10: Print its own so


using File

We are so used to using strcat() when it comes to concatenate two strings but how can we do that

1. What are the mo


in fopen?
2. What is feof?

without using strcat()? To answer that you have to know what is string in C and how it is printed.
Strings in C are represented by character arrays. The end of the string is marked by a special character
known as the null character(). So to concatenate two strings you just have to add the characters of the
second character array after the first and place a null character at the end.
The code is as follows:

Hadoop,BigDataSession
knowbigdata.com
FreeIntroductiontoHadoop&BigDataon7Jan.SignUpNow!

01
02
03
04
05
06
07
08
09
10
11

#include
#include
#include
voidconcatenate(chara[],charb[]){
charc[strlen(a)+strlen(b)];//sizeofcissumofaandb
inti=0,j=0;
while(i<strlen(a))//addsthefirststringtoc
c[i++]=a[i];
while(j<strlen(b))//addsthesecondstringtoc
c[i++]=b[j++];
c[i]='\0';//finallyaddthenullcharacter

http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

3/11

1/7/2015

CProgramsfortechnicalinterviews
12
13
14
15
16
17
18
19
20
21
22
23
24

printf("Afterconcatenation:\n");
printf("Value=%s",c);
}
intmain(){
chara[30],b[30];
printf("Enterthefirststring:");
gets(a);
printf("Enterthesecondstring:");
gets(b);
concatenate(a,b);
getch();
return0;
}

Follow up Questions:
1.

2. What if we don't use at the end of the string?

#6: Sort elements of an array using pointers


(selection sort technique)
Sorting is a one of the most favorite topic asked during the interviews. It is usually accompanied by
something or the other like here sorting is done indirectly using pointers. There are many sorting
techniques but usually bubble sort or selection sort is asked. Here well using the selection sort
technique to sort in ascending order. Sorting the elements of the array using pointers makes the
program a bit challenging. If there is an integer array arr[], arr is a pointer which stores the address of
the first element of arr[]. *arr can be used to refer to the value stored at that location. To access the
next element we can use *(arr+1). Using this knowledge you can start writing the program. The code is
as follows:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

#include
?
#include
intmain()
{
intarr[20],n,i,j,pos,temp;
printf("Enternumberofelements(max20):");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enterno%d:",i+1);
scanf("%d",(arr+i));//(arr+i)isthepointertotheindividualelementsofthearray
}
for(i=0;i<(n1);i++){//selectionsortingisdone
pos=i;
for(j=i+1;j<n;j++){if(*(arr+pos)>*(arr+j))//checksifarr[pos]isgreaterthanarr[j]
pos=j;
}
if(pos!=i){//ifvalueofposchangestheswappingisdone
temp=*(arr+i);
*(arr+i)=*(arr+pos);
*(arr+pos)=temp;
}
}
printf("Sortedlistinascendingorder:\n");
for(i=0;i<n;i++)
printf("%d",*(arr+i));
getch();
return0;
}

Follow up Questions:
1. What is the bubble sort technique?

2. What are the other sorting techniques that are asked


during the interviews?

#7: Enter and print details of n employees using


structures and dynamic memory allocation
This program is used to show the most basic use of structures. The structure is made of a character
array name[], integer age and float salary. Well make an array of the structure for the employees. Well
also use dynamic memory allocation using malloc. You can also use a linked list to the same which is a
better option. Lets check the code.
01
02
03
04

#include
#include
typedefstruct{//structureofemp
charname[30];

http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

4/11

1/7/2015

CProgramsfortechnicalinterviews
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

intage;
floatsalary;
}emp;
intmain(){
intn,i;
emp*employee;
printf("Enternoofemployees:");
scanf("%d",&n);
employee=(emp*)malloc(n*sizeof(emp));//dynamicmemoryallocationusingmalloc()
for(i=0;i<n;i++){
printf("\n\nEnterdetailsofemployee%d\n",i+1);
printf("Entername:");
scanf("%s",employee[i].name);
printf("Enterage:");
scanf("%d",&employee[i].age);
printf("Entersalary:");
scanf("%f",&employee[i].salary);
}
printf("\nPrintingdetailsofalltheemployees:\n");
for(i=0;i<n;i++){
printf("\n\nDetailsofemployee%d\n",i+1);
printf("\nName:%s",employee[i].name);
printf("\nAge:%d",employee[i].age);
printf("\nSalary:%.2f",employee[i].salary);
}
getch();
return0;
}

Follow up Questions:
1. What is malloc?

2. What are the other functions used in dynamic


memory allocation/deallocation?

3. Why using a linked list to do this program be a better


option?

#8: Tower of Hanoi using recursion


Now take a small break because you deserve it. But if you have the interview tomorrow, gulp a glass of
health drink and continue. The Tower of Hanoi is a mathematical game consisting of three rods A, B
and C and a number of disks of different sizes which can slide onto any rod. The objective of the game
is to move the entire stack from A to C using B as an auxiliary. There are few rules- Only one disk can
be moved at a time and no disk can be placed on top of a smaller disk.
Recursive solution:
1.

move n1 discs from A to B. This leaves disc n alone on peg A

2.

move disc n from A to C

3.

move n1 discs from B to C so they sit on disc n

Heres the code:


01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

#include
#include
voidtowers(intn,charfrompeg,chartopeg,charauxpeg){
//Ifonly1disk,makethemoveandreturn
if(n==1){
printf("\nMovedisk1frompeg%ctopeg%c",frompeg,topeg);
return;
}
//Movetopn1disksfromAtoB,usingCasauxiliary
towers(n1,frompeg,auxpeg,topeg);
//MoveremainingdisksfromAtoC
printf("\nMovedisk%dfrompeg%ctopeg%c",n,frompeg,topeg);
//Moven1disksfromBtoCusingAasauxiliary
towers(n1,auxpeg,topeg,frompeg);
}
intmain(){
intn;
printf("Enterthenumberofdisks:");
scanf("%d",&n);
printf("TheTowerofHanoiinvolvesthemoves:\n\n");
towers(n,'A','C','B');
getch();
return0;
}

Follow up Question:
1. Can we write of Hanoi without using recursion?

http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

5/11

1/7/2015

CProgramsfortechnicalinterviews

#9: Add numbers


arguments

using

Command

line

Questions on command line arguments are very often asked in the interviews. This program will
explain most of the details about command line arguments. The main() must have two parameters- int
argc and char *argv[]. argc is the argument count and argv[] will store the arguments passed by the
user. argv[0] is the name of the program. In this program well have to add all the arguments passed
starting from the argv[1] to argv[argc].
The code is given below:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#include
#include
#include

intmain(intargc,char*argv[])
{
intsum=0,i;
//Compareifpropernumberofargumentshavebeenentered
if(argc<3)
{
printf("Insufficientnumberofarguments...\n");
getch();
return0;
}

//Addallthenumbersenteredusingatoifunction
for(i=1;i<argc;i++)
{
sum+=atoi(argv[i]);
}

//printthesum
printf("Ans=%d",sum);
getch();
}

Follow up Questions:
1. How can i run this program?

2. What if i run it in the usual way?

#10: Print its own source code using File


This is a very interesting program. Well print the source file (programName.c) without taking any input
from the user. Well be using command line arguments. As we know the first argument is the file name
well be using this concept to make programName.c by adding .c to the file name. Then we will open
the file in read mode and print the characters from the file. The source code is given below:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16

#include
#include
intmain(intargc,char*argv[])
{
FILE*fp;
argv[0]=strcat(argv[0],".c");//toadd.ctothenameofthefile
fp=fopen(argv[0],"r");//opensthefileinreadmode
charch;
while(!feof(fp))//tillitreachestheendoffile
{
fscanf(fp,"%c",&ch);
printf("%c",ch);
}//endwhile
getch();
return0;
}//endmain

Follow up Questions:
1. What are the modes used in fopen?

2. What is feof?
We have reached the end of this long tutorial. Hopefully you enjoyed reading this and good luck for
your campus placements. If you have any doubts please use the comments. Thank you and visit our
academic section for more tutorials. You can also find 10 Java concepts for interviews by clicking on
this link.

Related Articles
http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

6/11

1/7/2015

CProgramsfortechnicalinterviews

How to write pattern


programs in C in a few
easy steps (Answers)

Bubble Sort Code


example in C & CPP
Understand the
algorithm too

C Program: Replacing a
substring from a string

C Program: Adding
two polynomials using
Linked List

C & C++ Sample Prorgams

c interview programs, C programs, c programs for


interviews, c programs for technical interviews,
common c programs, frequently asked c programs in
interviews, sample c programs

Howto: Move WordPress site to another Host


remotely without downtime and downloading

EnterYourEmail...

WordPress Advertisement Management with


Revenue Sharing Coming soon

Go
Search

arnab has written 12 posts


Hi, I'm a student and I'm programming in C/CPP for the the past 8years. I
also have knowledge on Java, Html, JavaScript and Php. Also I'm a failed
stand-up comic and will be testing my skills in this blog...:D

COMMENTS

PINGS

TOP

Comments Feed

22 Responses

Comment Now

arnab das says:


August 3, 2012 at 3:26 am

nice work some pointers on pointers ,memory management issues are very helpful for
campus-sing enthusiasts for e litmus ,netscape, tallys c rounds.well done,keep posting.

Sayan Bose says:


July 20, 2013 at 10:37 am
Thank you Arnab Da

bandya says:
October 5, 2013 at 7:56 pm
ekdum kadak bhaijaanjumma ki mubarak ho aapko
reply
reply

reply

tharaka prasad says:


October 17, 2012 at 8:17 pm

nice work.well done.

reply

http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

7/11

1/7/2015

CProgramsfortechnicalinterviews

Doma says:
January 17, 2013 at 10:59 am
Hi
Can you help me in the below situation
I have an array a={1,2,3,4,-1,-1,-1}. Am considering this -1 as junk values. I have to
remove these junk values and return an array containing b={1,2,3,4}.
I have tried different ways with no help.
Please share your ideas so that it will help me.

arnab says:
January 18, 2013 at 2:03 pm
1. Find out how many non junk values are present.
2. Then use malloc to generate an array of appropriate size
3. Copy the non junk values into the array
reply

reply

Sayeed says:
January 21, 2013 at 3:59 am

You have made a good job. We need more advance so keep it


up

reply

krishna says:
January 31, 2013 at 5:59 pm

hi arnab..can u tell me how to print anything on output screen using pointers and
without using any i/o function??
this was asked to me in an interview..a got a hint from someone that u shold put the
adress of the output in pointer and write that text in that memory.something like
thatcan u help??

arnab says:
January 31, 2013 at 7:34 pm
I didnt know the answer. I googled it for you. Check out this link
http://wiki.osdev.org/Printing_To_Screen

krishna says:
February 3, 2013 at 3:38 am
thanx a lot arnab.:)
reply
reply

reply

Durga says:
May 14, 2013 at 6:47 pm

thank u
good job

reply

http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

8/11

1/7/2015

CProgramsfortechnicalinterviews
reply

roopa says:
May 17, 2013 at 9:59 am

I am M.tech fresher , looking for career in Embed domain , I am doing well in C pls send
me some interview questions to my mail id
g.roopa043@gmail.com
thank you.

harouma says:
July 9, 2014 at 1:13 pm
hi sir i want c,c++,java interview coding programs and questions also
reply

reply

Siva says:
June 19, 2013 at 9:12 pm

Super but program is very so simple,,,,,,

reply

debanjali saha says:


July 7, 2013 at 7:55 pm

thankss a lott.

reply

sachin says:
August 5, 2013 at 7:40 pm

great job arnab

reply

Arpan Dixt says:


October 16, 2013 at 12:38 am

Good job arnab..@ i have 1 suggestion ..can u please put some quetions related to data
structures using c,like Array or linked list implementation.. that quetions which
generally asked in interview from data structures. Thanx

arnab says:
February 15, 2014 at 9:25 am
Ok Ill do that
reply

reply

Abhishek says:
February 10, 2014 at 7:36 pm

In the #7 program you should use -> operator instead of . operator since its a

http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

9/11

1/7/2015

CProgramsfortechnicalinterviews
pointer.

arnab says:
February 15, 2014 at 9:24 am
Yes sure you can do that

as you know Abhishek there are always thousand

different ways to do the same thing.


reply

reply

prabhu says:
July 8, 2014 at 2:42 pm

nice job arnab,thank u very much,,its very usefull for


freshers

reply

jayasri says:
October 15, 2014 at 12:25 pm

Its very useful for me to attend the interview

reply

Leave a Reply
Enteryourcommenthere...

Popular Posts
How to: Configure Modem & LAN
settings for your BSNL Broadband
Connection

Drop In
Name
Email

Login, Logout and Administrate using


PHP SESSION, COOKIE & MySQL Version 2 with remember me option

Message

Create Login Admin & Logout Page in


PHP w/ SESSION n MySQL
10 C programs you must know before
appearing for technical interviews

About Us!

8+2=

How to write pattern programs in C in a


few easy steps

InTechgrity.com,
formerly known as
greenTechspot,
was
started in 2009 by
Swashata Ghosh who
is
an
engineering
student by the day
and a web developer by the night. His friend
Pyrotechnicpixie is the creative force behind
the blog and also contributes to the lifestyle
and web designing related posts on iTg.They
are also the founders of itgwebtoolz and
itgdesignbox. Connect with them on twitter or
Facebook

Categories

5 Tips to lower your broadband usage


over internet Avoid unnecessary
downloads

SelectCategory
Automatically insert Current Date and
Time in MySQL table #Part 2.2
Speed up BSNL Broadband using Google
DNS & Open DNS - FREE DNS
alternatives
Write a love letter in C programming
language

Copyright 2009-2015 inTechgrity - Amalgamating Life & Technology ~ WordPress,

Archive

Privacy

Disclosure

Buy us Some beer

Top

Log in

PHP, MySQL, AJAX, jQuery, CSS, XHTML, Technology and much more...
Proudly Powered by WordPress | Designed by Elegant Themes

Developed by Pyrotechnicpixie & Swashata

http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

10/11

1/7/2015

CProgramsfortechnicalinterviews

http://www.intechgrity.com/10cprogramsyoumustknowbeforeappearingfortechnicalinterview/#

11/11

Das könnte Ihnen auch gefallen