Questions in C/C++ #1

There are a few common questions which may be asked in interviews for your Computer Society in college, or a company! So if have an interview lined up, go through these. All the best!

1. Write a program to print “Hello world!” without using a single semicolon.

void main()
{
if(printf(“Hello world!\n”))
{}
}

Explanation: The printf() function returns the number of characters it has printed. Since that is an integer, it can be used in combination with the if statement to printf the desired result without using a semicolon.

2. Swap 2 integers without using a temporary variable.

A common solution is,

a = a+b
b = a-b
a = a-b

Example: Let a=5 and b=7.
On a=a+b, a=12 and b=7.
On b=a-b, a=12 and b=5.
On a=a-b, a=7 and b=5.
Both the numbers have been swapped.

Copy contents of a file in reverse order using lseek()

The following is a C code for copying the contents of one file in reverse order in another file. It is fairly easy, once you understand how lseek works.

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

char buffer[1];

int main()
{
int fd1,fd2;     //the two file descriptors
char file1[50],file2[50];
printf(“Enter file to reverse: “);
gets(file1);   //Input path of first file
if((fd1=open(file1,O_RDONLY))==-1)  //open will return -1 if there is an error
{
printf(“File does not exist\n”);
return -1;
}
printf(“Enter file to output in: “);
gets(file2);   //Input path of second file
fd2=open(file2,O_RDWR | O_CREAT,0777);   // will open file in read-write mode or create it if it does not exist
int size=lseek(fd1,0,SEEK_END);   //to find the size of the file
printf(“%d”,size);
int i;
for(i=1;i<=size;i++)
{
if((lseek(fd1,-i,SEEK_END))==-1)   //will point to position -i from the end of the file fd1
{
printf(“%s\n”,strerror(errno));
}
int rd=read(fd1,buffer,1);    //read one char at a time from file1 (use fd1)
int wr=write(fd2,buffer,1);  //write one char at a time to file2 (use fd2)
if(wr==0)
{
printf(“Did not write to file\n”);
return -1;
}
}
return 0;
}

Disclaimer: This code is inefficient and is meant for homework assignments and lab excercises. It cannot be used in real world problem since reading and writing chars one at a time is a wasteful approach.