Monday 7 October 2013

Creation of a child process using fork system call

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>

int main()
{
    int p[2];
    pid_t pid;

    char inbuf[10],outbuf[10];

     if(pipe(p)==-1)
    {
               printf("pipe failed\n");
               return 1;
     }

    else
         printf(" pipe created\n");

if((pid=fork()))
{
    printf("In parent process\n");
    printf("type the data to be sent to child");
    scanf("%s",outbuf);
     write (p[1],outbuf,10);
      sleep(2);
      printf("after sleep in parent process\n");
}

else  
{
       printf("In child process\n");
       read(p[0],inbuf,10);
       printf("the data received by the child is %s\n",inbuf);
       sleep(2);
       printf("After sleep in child\n");
}
return 0;
}

Tags : OS LAB Program , Os programs , Creation of a child process using fork system call , OS fork program , fork system call , use of fork system call , fork() , working of fork() , fork() system call.

Monday 23 September 2013

Linux | Pipe - Read & Write Program


Read Pipe :

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<error.h>

int main()
{
int fd;

fd = open("MyPipe",O_RDONLY,0666);

if(fd<0)
{
perror("Open");
return 0;
}


char c;
int s;

while(1)
{
s=read(fd,&c,1);
if(!s)
break;
printf("%c",c);
}

printf("\n\n");

close(fd);

}


Write Pipe :


#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<error.h>

int main()
{
int fd;

fd = open("MyPipe",O_WRONLY,0666);

if(fd<0)
{
perror("Open");
return 0;
}


char c[]="Welcome";
int s;


s=write(fd,c,7);

printf("\n\n");

close(fd);

}

Linux | File Programs

                 

                    File Program 1

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<error.h>

int main()
{
int fd;

fd = open("test",O_RDONLY|O_CREAT,0477);

if(fd<0)
{
perror("Open");
return 0;
}


char c;
int s;

s=read(fd,&c,1);

if(s)
{
printf("\nRead Character: %c",c);
}

printf("\n\n");

close(fd);

}




 File Program 2


#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<error.h>

int main()
{
int fd;

fd = open("test",O_WRONLY|O_CREAT,0666);

if(fd<0)
{
perror("Open");
return 0;
}


char c[] = "Welcome To Files...";
int s;

s=write(fd,c,sizeof(c));

if(s)
{
printf("\nWritten Character: %d",s);
}

printf("\n\n");

close(fd);

}


 File Program 3


#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<error.h>

int main()
{
int fd;

fd = open("test",O_RDONLY|O_CREAT,0666);

if(fd<0)
{
perror("Open");
return 0;
}


char c;
int s;

while(1)
{
s=read(fd,&c,1);
if(!s)
break;
printf("%c",c);
}

printf("\n\n");

close(fd);

}




 File Program 4


#include<stdio.h>
#include<error.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>

int main()
{
int fd;

fd = open("test",O_RDWR,0644);
//fd = creat("test",0644);

if(fd<0)
{
perror("File Open");
exit(1);
}

int s,len;
char txt[100];

printf("\nEnter Text to be written to File: ");
gets(txt);

len = strlen(txt);

s = write(fd,txt,len);

printf("%d characters written to file...\n\n",s);

s = lseek(fd,0,SEEK_SET);

printf("\n[%d]\n",s);
strcpy(txt,"\0") ;
s = read(fd,txt,100);
printf("%s-%d",txt,s);
close(fd);
return 0;
}


 File Program 5

#include<stdio.h>
#include<error.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
struct stu
{
char name[40];
int rno;
double cg;
};
int main()
{
int fd;
struct stu s2,s1={"VS",333,9.9};

fd = open("test",O_RDWR|O_CREAT,0644);

if(fd<0)
{
perror("File Open");
exit(1);
}

int s;

s = write(fd,"This is Test File",10);
printf("%d characters written to file...\n\n",s);

s = write(fd,&s1,sizeof(s1));
printf("%d characters written to file...\n\n",s);

lseek(fd,-1*sizeof(s1),SEEK_CUR);
s = read(fd,&s2,sizeof(s2));
printf("Read Record: %s - %d - %lf\n\n",s2.name,s2.rno,s2.cg);

close(fd);
return 0;
}




 File Program 6

#include<stdio.h>
#include<error.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>

int main()
{
int fd;

fd = open("test",O_CREAT|O_WRONLY,0644);

if(fd<0)
{
perror("File Open");
exit(1);
}

int s,len;
char txt[100];

printf("\nEnter Text to be written to File: ");
gets(txt);

len = strlen(txt);

s = write(fd,txt,len);

printf("%d characters written to file...\n\n",s);


close(fd);
return 0;
}



 File Program 7

#include<stdio.h>
#include<sys/stat.h>
#include<error.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<time.h>

int main()
{
int fd;
struct stat st;

fd = lstat("File1.c",&st);

//fd = creat("test",0644);

if(fd<0)
{
perror("File Open");
exit(1);
}

printf("\nSize: %d",st.st_size);
printf("\nInode: %d",st.st_ino);
printf("\nDevice Number: %d,%d",major(st.st_dev),minor(st.st_dev));
printf("\nUser ID: %o",st.st_uid);
printf("\nGroup ID: %o",st.st_gid);
printf("\nMode: %o",st.st_mode);

struct tm *t;
char tt[50];
t = localtime(&st.st_atime);
strftime(tt,50,"%c",t);
printf("\nModification Time: %s",tt);
char *mt = ctime(&st.st_mtime);
printf("\nAccess Time: %s",mt);
char *ct = ctime(&st.st_ctime);
printf("\nChange Time: %s",ct);

printf("\n\n");


return 0;
}

Linux Ebook | Michael K Johnson , Erik W. Troan


CLICK HERE TO DOWNLOAD


CLICK HERE TO DOWNLOAD
CLICK HERE TO DOWNLOAD
CLICK HERE TO DOWNLOAD

Linux Application Development (2nd Edition)
Erik W. Troan, Michael K. Johnson | Addison-Wesley Professional | 2011-11-29 | 736 pages | English | PDF

"The first edition of this book has always been kept within arm's reach of my desk due to the wonderful explanations of all areas of the Linux userspace API. This second edition greatly overshadows the first one, and will replace it."
--Greg Kroah-Hartman, Linux kernel programmer
Develop Software that Leverages the Full Power of Today's Linux
Linux Application Development, Second Edition, is the definitive reference for Linux programmers at all levels of experience, including C programmers moving from other operating systems. Building on their widely praised first edition, leading Linux programmers Michael Johnson and Erik Troan systematically present the key APIs and techniques you need to create robust, secure, efficient software or to port existing code to Linux.
This book has been fully updated for the Linux 2.6 kernel, GNU C library version 2.3, the latest POSIX standards, and the Single Unix Specification, Issue 6. Its deep coverage of Linux-specific extensions and features helps you take advantage of the full power of contemporary Linux. Along the way, the authors share insights, tips, and tricks for developers working with any recent Linux distribution, and virtually any version of Unix.
Topics include
  • Developing in Linux: understanding the operating system, licensing,
  • and documentation
  • The development environment: compilers, linker and loader, and unique
  • debugging tools
  • System programming: process models, file handling, signal processing, directory operations, and job control
  • Terminals, sockets, timers, virtual consoles, and the Linux console
  • Development libraries: string matching, terminal handling, command-line parsing, authentication, and more
  • Hundreds of downloadable code samples
New to this edition
  • The GNU C library (glibc), underlying standards, and test macros
  • Writing secure Linux programs, system daemons, and utilities
  • Significantly expanded coverage of memory debugging, including Valgrind and mpr
  • Greatly improved coverage of regular expressions
  • IPv6 networking coverage, including new system library interfaces for using IPv6 and IPv4 interchangeably
  • Coverage of strace, ltrace, real-time signals, poll and epoll system calls, popt library improvements, Pluggable Authentication Modules (PAM), qdbm, and much more
  • Improved index and glossary, plus line-numbered code examples

Thursday 19 September 2013

Encrypt & Decrypting Messages

 /*
Exercise : Ex 3
Title : Sender Program..
Author :Aslam Jainul
*/

import java.io.*;
import java.net.*;
import java.util.*;
 class sender
{
public static void main(String args[])
{
try
{
int key;
DataInputStream dis=new DataInputStream(System.in);

key=2;
System.out.println("enter the name");
String f=dis.readLine();
File f1=new File(f);
FileReader fr=new FileReader(f1);
Socket s=new Socket("192.168.208.118",8081);
PrintWriter put=new PrintWriter(s.getOutputStream(),true);
put.println(f);
int c=0;
while((c=fr.read())!= -1)
{
put.println(c+key);
}
System.out.println("File content transferred");
fr.close();
s.close();
}
catch(Exception e)
{}
}
}


 /*
Exercise : Ex 3
Title : Receiver Program..
Author :Aslam Jainul
*/

import java.io.*;
import java.net.*;
import java.util.*;
 class receiver
{
public static void main(String args[]) throws IOException
{
ServerSocket ss;
Socket s;
try
{
System.out.println("waiting for client");
ss=new ServerSocket(8081);
s=ss.accept();
System.out.println("connection established");
BufferedReader get=new BufferedReader(new InputStreamReader(s.getInputStream()));
String fname;
fname=get.readLine();
fname="TR_"+fname;
System.out.println("file name is:"+fname);
File f=new File(fname);
FileWriter fw=new FileWriter(f);
String c;
while((c=get.readLine())!=null)

fw.write(Integer.parseInt(c));
System.out.println("received content stored");
fw.close();
s.close();
}
catch(Exception e)
{}
}
}

 /*
Exercise : Ex 3
Title : Decrypt File
Author :Aslam Jainul
*/

import java.io.*;
import java.net.*;
import java.util.*;
 class decript
{
public static void main(String args[])
{
try
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter the encrypted file name with extension");
String fname=dis.readLine();
File f1=new File(fname);
FileReader fr=new FileReader(f1);
File f2=new File("dec_"+fname);
FileWriter fw=new FileWriter(f2);
int c=0;
while((c=fr.read())!=-1)
{
System.out.println(c-2);
fw.write(c-2);
}
fr.close();
fw.close();
}
catch(Exception e)
{}
}
}



UDP Receiver & Sender Program

 /*
Exercise : Ex 2(b)
Title : UDP Receiver Program..
Author :Aslam Jainul
*/
import java.io.*;
                 import java.net.*;
                 import java.util.*;
                 public class UdpReceiver
                 {
                     public static void main(String args[])throws IOException
                     {
                          try
                             {
                                 DataInputStream dis=new DataInputStream(System.in);                              
                                 byte[] rdata=new byte[1024];
                                                       
                       
                               DatagramSocket s=new DatagramSocket(9876);
                               DatagramPacket rpack=new DatagramPacket(rdata,rdata.length);
                             
                               System.out.println("Waiting for file name:");
                               s.receive(rpack);
                             
                               String fname=new String(rpack.getData());
                               System.out.println("From server : "+fname);
                                                       
                             fname="TR_"+fname;
                             System.out.println("File name is : "+fname);
                           
                             File f=new File(fname);
                             FileWriter fw=new FileWriter(f);
                           
                             
                             while(true)
                             {
                             
                             byte[] rdata1=new byte[1024];                          
                             DatagramPacket rpack1=new DatagramPacket(rdata1,rdata1.length);
                             
                             s.receive(rpack1);
                             String txt=new String(rpack1.getData());
                             fw.write(txt);
                             System.out.print(txt);
                             if(txt.trim().equals("done"))
                             {
                                  System.out.println("Process finished");
                                  fw.close();
                                  break;
                             }
                             
                             }
                         }
                         catch(IOException e)
                         {         System.out.println(""+e);
                         }
                     }  
                 }


 /*
Exercise : Ex 2(b)
Title : UDP Sender Program..
Author :Aslam Jainul
*/
  import java.io.*;
                   import java.net.*;
                   import java.util.*;
                   public class UdpSender
                   {
                        public static void main(String args[])
                        {
                             try
                             {
                                  DataInputStream dis=new DataInputStream(System.in);
                                  System.out.println("Enter the file name :");
                                  String f=dis.readLine();

                               
byte[] sdata=new byte[1024];                          
                            sdata=f.getBytes();
                               
                               InetAddress ipa=InetAddress.getByName("127.0.0.1");
                               DatagramSocket s=new DatagramSocket();
                               DatagramPacket spack=new DatagramPacket(sdata,sdata.length,ipa,9876);
                               s.send(spack);
                             
                                  File f1= new File(f);
                                  FileReader fr=new FileReader(f1);
                                  int n=0;
                                  byte[] buffer=new byte[1024];
                             
StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(f));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1)
        {
            String readData = String.valueOf(buf, 0, numRead);
            System.out.print(readData);
            buffer=readData.getBytes();
       DatagramPacket spack1=new DatagramPacket(buffer,buffer.length,ipa,9876);
          s.send(spack1);
        }                              
                             
byte[] endChar=new byte[1024];
endChar="done".getBytes();
spack=new DatagramPacket(endChar,endChar.length,ipa,9876);
s.send(spack);
         }
         catch(IOException e)
         {
          System.out.println(""+e);
         }
    }
}



TCP Receiver & Sender Program

/*
Exercise : Ex 2(a)
Title : TCP Receiver Program..
Author :Aslam Jainul
*/

import java.io.*;
import java.net.*;
import java.util.*;
public class TCPreceiver
{
public static void main(String args[])
{

ServerSocket ss;
Socket s;
try
{
System.out.println("Waiting for Client........");
ss=new ServerSocket(8081);
s=ss.accept();
System.out.println("Connection Done...!!");
BufferedReader get=new BufferedReader(new InputStreamReader(s.getInputStream()));
String fname;
System.out.println("From : " + s.getInetAddress() );

fname=get.readLine();
fname="TR_" +fname;
System.out.println("file name is:" +fname);
File f=new File(fname);
FileWriter fw=new FileWriter(f);
String c;
while((c=get.readLine())!=null)
fw.write(Integer.parseInt(c));
System.out.println("Contents Received..");
fw.close();
s.close();
}
catch(Exception e)
{}

}
}


/*
Exercise : Ex 2(a)
Title : TCP Sender Program..
Author :Aslam Jainul
*/

import java.io.*;
import java.net.*;
import java.util.*;
public class TCPsender
{
public static void main(String args[])
{
try
{
System.out.println("Enter the File Name you wanna transfer ...");
DataInputStream dis=new DataInputStream(System.in);
String f=dis.readLine();
File f1=new File(f);
FileReader fr=new FileReader(f1);
Socket s=new Socket("192.168.208.118",8081);
PrintWriter put=new PrintWriter(s.getOutputStream(),true);
put.println(f);
int c=0;
while((c=fr.read())!=-1)
put.println(c);
System.out.println("File Transfered....");
fr.close();
s.close();
}
catch(Exception e)
{}
}
}





Sunday 15 September 2013

Operating System - Silberschatz - Seventh edition

Another defining moment in the evolution of operating systems
Small footprint operating systems, such as those driving the handheld devices that the baby dinosaurs are using on the cover, are just one of the cutting-edge applications you'll find in Silberschatz, Galvin, and Gagne's Operating System Concepts, Seventh Edition.

By staying current, remaining relevant, and adapting to emerging course needs, this market-leading text has continued to define the operating systems course. This Seventh Edition not only presents the latest and most relevant systems, it also digs deeper to uncover those fundamental concepts that have remained constant throughout the evolution of today's operation systems. With this strong conceptual foundation in place, students can more easily understand the details related to specific systems.
New Adaptations
* Increased coverage of user perspective in Chapter 1.
* Increased coverage of OS design throughout.
* A new chapter on real-time and embedded systems (Chapter 19).
* A new chapter on multimedia (Chapter 20).
* Additional coverage of security and protection.
* Additional coverage of distributed programming.
* New exercises at the end of each chapter.
* New programming exercises and projects at the end of each chapter.
* New student-focused pedagogy and a new two-color design to enhance the learning process.

                                     CLICK HERE TO DOWNLOAD

                                     CLICK HERE TO DOWNLOAD

                                     CLICK HERE TO DOWNLOAD

* After Opening Press Ctrl + S (or) Go to File --> Download


Tags : Operating System - Silberschatz - Seventh edition ebook download , Operating System - Silberschatz - Seventh edition pdf , Operating System - Silberschatz - Seventh edition ebook pdf , Operating System - Silberschatz - Seventh edition .

DBMS - Ramez Elmasri - 6th edition



2010-04-09 | ISBN: 0136086209 | 1200 pages | PDF | 8,29 MB


Clear explanations of theory and design, broad coverage of models and real systems, and an up-to-date introduction to modern database technologies result in a leading introduction to database systems. Intended for computer science majors, Fundamentals of Database Systems, 6/e emphasizes math models, design issues, relational algebra, and relational calculus.

A lab manual and problems give students opportunities to practice the fundamentals of design and implementation. Real-world examples serve as engaging, practical illustrations of database concepts. The Sixth Edition maintains its coverage of the most popular database topics, including SQL, security, and data mining, and features increased emphasis on XML and semi-structured data.

��Fundamentals of Database Systems is a leading example of a database text that approaches the subject from the technical, rather than the business perspective. It offers instructors more than enough material to choose from as they seek to balance coverage of theoretical with practical material, design with programming, application concerns with implementation issues, and items of historical interest with a view of cutting edge topics.
CHenry A. Etlinger, Rochester Institute of Technology

This is an outstanding, up-to-date database book, appropriate for both undergraduate and graduate courses. It contains good examples, and clearly describes how to design good, operable databases as well as retrieve and manipulate data from an existing database.

                                     CLICK HERE TO DOWNLOAD

                                     CLICK HERE TO DOWNLOAD

                                     CLICK HERE TO DOWNLOAD

* After Opening Press Ctrl + S (or) Go to File --> Download


Tags : DBMS - Ramez Elmasri  - 6th edition , DBMS ebook download , DBMS pdf download ,DBMS best book , DBMS - Ramez Elmasri  - 6th edition download ,DBMS - Ramez Elmasri  - 6th edition pdf , DBMS - Ramez Elmasri  - 6th edition ebook download , free ebook websites , free it ebooks , free dbms ebooks , DBMS - Ramez Elmasri  - 6th edition

Computer Networks - Tanenbaum 5th edition



                         *** Redirected to another Page... ***

Wednesday 4 September 2013

SCANIT Online Test Answer - Day 1( 27/08/2013)

                                     
                                         Multiple Choice Question


1. The control automatically passes to the first statement after the loop in ______________.

Answer : break statement


2. Predict the output of following C program.
main()
{
      int x=20,y=35;
      x = y++ + x++;
      y = ++y + ++x;
      printf("%d",y);
}

Solution:

x = 20 + 35 = 55
y = 36 + 1 + 56 + 1 = 94

The value of y is 94.


3. What will be the result for the following statement?

                      printf (“%d”, printf (“tifaccore”));

Solution:
The output is ‘tifaccore9’ , ‘tifaccore’ due to inner printf statement and 9 as length due to outer printf statement.


4.Initially the value of n is -54 , what will be the output generated for this program ?

if (n < 0)
{
        printf ("-");
        n = -n;
}

if (n % 10)
     printf ("%d", n);
else
     printf ("%d", n/10);

printf ("%d", n);

Solution:
      The output is -5454 . Here n%10 doesn’t affect n value.



5.How many times ‘SCAN IT’ will be printed in the following C program ?
main()
{
int a=0,b=5;
if(a=0) printf("SCAN IT ");
if(b=5) printf("SCAN IT ");
if((a>b)==1) printf("SCAN IT ");
printf("SCAN IT ");
}

Solution:
       2 times it will be printed. “ If(a=0)” result false so it won’t print . The reason is assigning a variable to zero is always returns 0 but in case of assigning a variable to other values , it will return 1.


6. What will happen if we execute the following code ?
int main(void)
{
      http://www.sastra.edu
     printf("SASTRA UNIVERSITY");

       return 0;
}

Solution:
The output is ‘SASTRA UNIVERSITY’ . The code will not affect because of http://www.sastra.edu . ‘http:’ will be considered as goto statement. ‘//www.sastra.edu’ will be assumed as comments and it will be ignored.


7. What will be output when you will execute following c code?
void main()
{
int check=2;
switch(check){
case 1: printf("Vijay");
case 2: printf("Ajith");
case 3: printf("Surya");
case 4: printf("Rajini");
default: printf("Kamal");
}
}

Solution:
The output is ‘Ajith Surya Rajini Kamal’ . There is no break statement.


8.Which of the following operation is illegal in structures?
(a)Typecasting of structure
(b)Pointer to a variable of same structure
(c)Dynamic allocation of memory for structure
(d)All of the mentioned

Answer : (a) Typecasting of structure.


9.What will be the output of the program?
int main()
{
int i=3;
switch(i)
{
case 1:
printf("Online Test");

case 2:
printf(“is");

case 3:
continue;

case 4:
printf("Boring");

default:
printf("Very Interesting");
}
return 0;
}

Solution:
It results in Compiler Error . We can use continue statement only for loop .. If we use loop inside switch that time we can use continue statement.


10.What will be the output of the program?
int main()
{
    int x=1, y=1;
    for(; y; printf("%d %d", x, y))
    {
        y = x++ <= 5;
    }
    return 0;
}

Solution:
2 1 3 1 4 1 5 1 6 1 7 0


11. The operation between float and int would give the result as 

Answer : int


12. What will be output when you will execute following c code?
void main(){
     int movie=1;
     switch(movie<<2+movie){
        default:printf("Thalaiva");
        case 4: printf("Billa 2");
        case 5: printf("Singam 2");
        case 8: printf("Vishwaroopam");
     } 
}


Solution : 
1 << 3  ==> 8 ( Shifting the bit to left  00001  to 001000 )
So only case 8 will be executed.

The output is Vishwaroopam.


13.Find the output for the following.
    int main()
    {
        int i = 1;
        if (i++ && (i == 1))
            printf("SCANIT");
        else
            printf("ACE");
    }


Solution : The output is "ACE"..  if statement returns false because while comparing i value becomes 2 ( because of increment operator )


14.Consider the following declaration of enum.

(i)enum  cricket {Sachin,Dhoni,Dravid}c;
(ii)enum  cricket { Sachin,Dhoni,Dravid };
(iii)enum   { Sachin,Dhoni=-5,Dravid }c;
(iv)enum  c {Sachin,Dhoni,Dravid };

Choose correct one:
Solution : All the four statements are correct .

15.What will be the output of following code?  
      int main()    
    {        
             fun();  
             fun();
             fun();    
             return 0;    
     }

    void fun()    
    {      
             auto int i=0;        
             register int j=0;      
             static int k=0;      
              i++; j++; k++;        
              printf(“%d %d %d”,i,j,k);  
    }

Solution :
   1 1 1 1 1 2 1 1 3
    Everytime while printing 'i' and 'j' value will be 1. But k value will change ' 1 2 3 ' because it is static so it will get last defined value.

16. Comment on the output of this C code?      
        struct temp      
       {          
              int a;      
       } s;      

       void change(struct temp);      

        main()      
       {          
                s.a = 10;          
                change(s);          
                printf("%d", s.a);      
        }      

       void change(struct temp s)      
      {          
                  s.a = 1;      
      }

Solution : The output will be 10.


17.What is the output of following code?    
       void main()   
       {       
             int x = 0;       
             if (x = 0)           
                printf("Vijay");       
            else           
                printf("Ajith");   
       }

Solution :  The output will be "Ajith" .. If(x=0) returns false so it won't execute if statement so else should be executed..


                  Program Type Question

1. A number of “Cats” got together and decided to kill 999919 mice. Every cat killed equal number of “mice”. Write a program to find different possible number of cats.

Solution:
Logic : (999919 % x ==0) The value of x is from 0 to 999919. There may be different possible solution. For example the number of cats may be one , in that case 1 cat killed 999919 mice .. Assume there are 999919 cats , in that each cats killed 1 mice.. Using loop and the above if statement , you can write the code.


2. Write a C program to add two numbers without using '+' operator.

Solution:

Logic 1 : sum = a - (-b) ;

Logic 2 : sum = a -( ~b ) -1; (~b is equivalent to –b-1)


  3.Replace X by some expression in such a manner you should get output as “SASTRA UNIVERSITY”.   
        
                   if(X)            
                          printf(“SASTRA”);       
         
                 else            
                          printf(“UNIVERSITY”);

Solution:
X should be replaced by "(printf("SASTRA") == 0)"

So first SASTRA will be printed and returns 1 , then the condition "1==0" becomes false so else will be executed.

4. There are some goats and ducks in a farm. There are 60 eyes and 86 foot in total. Write a program to find number of goats and ducks in the farm.

Solution:

Logic : 2(x+y) = 60 so that x + y = 30 == > 1st Equation – eyes.
            4x + 2y = 86 . Solve the equation and get the value of x and y (i.e. Number of goats and ducks.)



5. Pragadeesh has a money pouch containing Rs.700. There are equal number of 25 paise coins, 50 paise and one rupee coins. Write a C program to find how many of each are there?

Solution:

             Logic x = 700 / (0.25+0.50+1);



6.  Write a program to print in the following pattern :
1
3 5
7 9 11

Solution:

int main()
{
    int i,j,v,t;

    t=0;

    for(i=0;i<3;i++)
    {
        for(j=0;j<=i;j++)
        {
            v=((2*t)+1) ;
            printf("%d \t",v);
            t=t+1;   
                
        }
            printf("\n");

    }

    return 0;

}


7.Write a C program to find the smallest of three integers without using any of the comparison operators.

Solution:

int smallest(int x,int y,int z)
{
  int c = 0;
  while ( x && y && z )
  {
      x--;  y--; z--; c++;
  }
  return c;
}

int main()
{
   int x = 12, y = 15, z = 5;
   printf("Minimum of 3 numbers is %d", smallest(x, y, z));
   return 0;

}


8. Write a C program to print numbers from 1 to 100 without using conditional operators.


Solution :

int main()
{
    int num = 1;

    print(num);
    return 0;
}


int print(num)

{
       if(num<=100)

      {
         printf("%d ",num);
         print(num+1);
       }
}



                  Aptitude Questions.

1. An analog clock reads 3:15. What is the angle between the minute hand and hour hand ?
( The answer is not zero !)

Solution: At 3:15 , the hour hand will be ¼ of between 3 and 4 & the minute hand will be at 3.. The angle is ¼ of between 3 and 4. The total clock angle is 360. Half ( 12 to 6) is 180.. 180/6 will return angle between each number ( 2 and 3 , 3 and 4). SO the angle between 3 and 4 is 30 . ¼ of between 3 and 4 is 7.5..


2. Arun works in cryptology department.One fine morning when Arun entered his room in office he saw that his system is already logged in and all his important files are gone. Arun then went to his boss cabin and said "I need my system to be secure for that i need new password.My old password is hacked and all my important files are gone".Boss told him "I know your important files are gone and for that i issued you new password.Your new password is unbreakable,trust me".

Arun said "But what is my new password?"

Boss said "This is important.If you will listen carefully you will get your new password." 

* Your new password is in someway opposite to your old password and you already heard that. 

* Your new password and old password has 3 letters in common.

 * Your new password length is one less then the double of your old password length.  

* Always remember more the length of password more it is difficult to crack.

Arun then went to his cabin and logged in with new password.How he must have guessed the new password?What is his new password?What was his old?

Solution:

Old Password - hacked
New Password - unbreakable

3. There is a room with a door (closed) and three light bulbs. Outside the room there are three switches, connected to the bulbs. You may manipulate the switches as you wish, but once you open the door you can't change them. Identify each switch with its bulb.

Solution :
Switch the first one on for a couple of minutes then switch it off, switch the second one on, and keep the third turned off. Get into the room, the first should be hot and not lit, the second is lit, and the third is cold and not lit.


4. Find out the wrong number in the given sequence of numbers 582, 605, 588, 611, 634, 617, 600
Solution :
634. Alternatively 23 is added and 17 is subtracted from the terms. So, 634 is wrong.


5. Yesterday in a party, I asked Mr. Shah his birthday. With a mischievous glint in his eyes he replied. "The day before yesterday I was 83 years old and next year I will be 86." Can you figure out what is the Date of Birth of Mr. Shah? Assume that the current year is 2000.

Solution:
Mr. Shah's date of birth is 31 December, 1915

Today is 1 January, 2000. The day before yesterday was 30 December, 1999 and Mr. Shah was 83 on that day. Today i.e. 1 January, 2000 - he is 84. On 31 December 2000, he will be 85 and next year i.e. 31 December, 2001 - he will be 86. Hence, the date of birth is 31 December, 1915. Many people do think of Leap year and date of birth as 29th February as 2000 is the Leap year and there is difference of 3 years in Mr. Shah's age. But that is not the answer.


SCAN IT Online Test Answer - Day 5 ( 04 / 9 / 2013 )



    Day 4 Students & Day 5 Students had the same Question

                                             Multiple Choice Question

1. What will be the output for the following C code ?
#define TRUE 0
int main()
{
while(TRUE)
{
printf("Colosseum 2013 was a great Success !");
}
}

 Solution :

     Prints Nothing ! . In this case , it will be assumed as while(0) and exit the loop.



2.Find the output for the following question.
int main()
{
int x=5;
printf("%d  %d",x<<2,x>>2);
}

Solution:
 The binary value of 5 is 0101

 Now 5<<2 will shift the bit to left two times, so it results 010100 == 20.
And 5>>2 will results in 0001 == 1

The output is 20 1



3. Find error in following c snippet?
int x;
int x=0;
int x;
int main()
{
   printf("%d",x); 
   return 0;
}

Solution :

No Error. Prints 0. Multiple declaration of global variables doesn't results in error.!  

( Tested in both TURBO C and LINUX ENVIRONMENT)



4. What is the output of code given below?
int main()
{
printf("3rd Year");
goto asl;
printf("IT");
asl :printf("C Section");
}

Solution :
   Output will be 3rd Year C Section.. (Note that 'IT' will not be printed ).




5.The output of the code below is

int main()
{
int i=0, k;
label:printf("'faccha' is SASTRA colloquial for a freshman");
if(i==0)
goto label;
}

// The above context taken from Sastra Imprint XII Edition

Solution:
          Will be printed infinite times.




6.What would be the output of the following code?

int main(void)
{
int a = 10, b = 20, c = 30;
printf("%d..%d..%d", a+b+c, (b = b*2), (c = c*2));
return 0;
}

Solution:
    The precedence is from right to left.

     c = 30 * 2  == 60.
     b = 20 * 2  == 40.
     a+b+c = 10 + 40 + 60 == 110.

     Output will be 110..40..60




7. What will the output for the following snippet ?

if((strcmp("OS", "DBMS")) == 0)
    {
flag = 1;
    }

if(flag)
    {
printf("DBMS is great");
    }
else
    {
printf("OS is great");
    }

Solution :

    In case of strcmp() , if both strings are equal it will return zero otherwise it will print some other value. 

  Hence  " if((strcmp("OS", "DBMS")) == 0) " will return false.

   So 'if' will not be executed , only 'else' will be executed.

  The output will be "OS is great"


8. What will be the output for the following code ?

if((printf("Online Test is ") > 0 ? 1 : 0))
printf("Boring !");
else
printf("Interesting !");


Solution:

  First it will print "Online Test is" and it will return '1' . (Always a successful statement will return '1') . So 1>0 will also return true and replaced by 1 (Conditional Operator). And if(1) prints "Boring !".

Hence the output is "Online Test is Boring !".





9.What will be the output for the following program ?

void main()
{
  if(((printf("SCANIT ")),(printf("is going ")))&&((printf("to conduct "))||(printf("web designing class"))))
                printf(5+"from next week");

   else
            printf(3 + "from tomorrow");
}

Solution :

Some Tips :

*  Normally printf(4+"SASTRA")  will displays "RA" (display data from 4th character i.e 5th and other character)

* if(1,1) returns 1
   if(0,0) returns 0
   if(1,0) returns 0
   if(0,1) returns 1

* A Successful statement always returns 1. (printf(), scanf())

Hence printf() statement will be executed one by one. if((1,1)&&(1 || 1)) returns true and execute the statement inside if. And 'from' will be skipped as it starts from 5th character. 

 "web designing class" will not be executed. The reason is ( 1 || printf("web designing class")) will returns true without considering the printf statement.

The output will be "SCANIT is going to conduct next week"




10. In C , modulus operator(%) can be applied to ___ Variables.

(i) int
(ii) char
(iii) double
(iv) float

Solution :  int and char.




11.What will be the output for the following code ?

int main()
{
            float me = 1.1;
            double you = 1.1;
            if(me==you)
                  printf("Hi !");
            else
                  printf("Hello !");
}

Solution :
The output will be "Hello !".  In this case , if() will returns false.

For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value  represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double.
Rule of Thumb: 
Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) . 



12.What will be the output for the following code ?

             int main()
            {
            static int var = 5;
            printf("%d ",var--);
            if(var)
                        main();
            }


Solution :

The output is 5 4 3 2 1
 When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively. 




13.What will be the output for the following snippet ?

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

Solution:
Linker Error : Undefined symbol '_i'
Explanation: 
                        extern storage class in the following declaration,
                                    extern int i;
specifies to the compiler that the memory for i is allocated in some other program and that address will be given to the current program at the time of linking. But linker finds that no other variable of name i is available in any other program with memory space allocated for it. Hence a linker error has occurred .




14. What will be the output for the following code?

int main()
{
            int i=-1,j=-1,k=0,l=2,m;
            m=i++&&j++&&k++||l++;
            printf("%d %d %d %d %d",i,j,k,l,m);
}

Solution:
The output is 0 0 1 3 1

Variables i,j,k,l are incremented and the m value results one.




15.Predict output/error in the following snippet.
int main()
{
struct xx
{
      int x=3;
      char name[]="hello";
 };
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}

Solution:
Compiler Error. In structures ,you should not initialize variables in declaration.


                               Program Type Question



1.Write a C Program / Algorithm for the following problem statement :

SCANIT circular regarding ‘Online Test’ is passed to all the second and third year classes.  The circular says “Today you have Online Test  at IT LAB between 5pm and 6pm”. Unfortunately the test is only for third year students. In IT LAB , only 85 students are allowed to attend the test. One of our SCAN IT member will be there to guide the students. He is having the list of all second and third year students. He should allow only third year students.

Sample Test Case:

Your Register No  : 115015104
Result : You are allowed Inside.

Your Register No : 116015048
Result : The test is only for third year students.

Your Register No: 172678183
Result : Sorry . You are not an IT student.

Your Register No: 115015048
Result : Only 85 students are allowed at a time.


Logic :
               while(1)
                {
                      * get student reg no.

                      * compare the given reg no. with the record.

                                 if( reg > 115015001 && reg <115015150 && count <86)
                                {
                                     print "You are Allowed"
                                     increment count value;
                                 }
                                 
                                 else if( reg > 116015001 && reg <116015150)
                                  {
                                      print "The test is only for third year students"; 
                                    }

                                    else if( reg > 115015001 && reg <115015150 && count >85)
                                {
                                     print "Already 85 students entered the LAB";
                                 }
                           
                               else 
                                {
                                     print "You are not an IT student !";
                                 }
                 }




2. Write a C Program to print a semicolon without using semicolon in the code.

Solution:

#include <stdio.h>
int main() 
{
   if (printf("%c ", 59)) 
    { 
    }

}



3. Write a  C program to print some numbers without using any numbers in the program .

  The program should satisfies the following condition :
* Don’t get user input (Command Line Argument / Scanf())
* Datatype conversion is not allowed.
* You should use only variable in the program that should be of int type and while printing in printf also you should use only ‘%d’. 


Solution :

** You can use any other idea **

Simple Logic :

int a;
a= printf("hiiiiiiii");
printf("%d",a);





4. Write a C program/algorithm for the following problem statement :

               Assume you have one secured file in your laptop. We need password to open that file. ( the password is chithvihar). Now the laptop is passed to all the 60 students in our class. But no one knows the password. The students entered the password randomly . The file is opened for eight students but none of the 60 students typed ‘chithvihar’. How is it possible ? How to overcome from this loophole ?

Solution:

#include<stdio.h>

int main(int argc, char *argv[])
{
    int flag = 0;
    char passwd[10];

    memset(passwd,0,sizeof(passwd));

    strcpy(passwd, argv[1]);

    if(0 == strcmp("chithvihar", passwd))
    {
        flag = 1;
    }

    if(flag)
    {
        printf("\n Password cracked \n");
    }
    else
    {
        printf("\n Incorrect password \n");

    }
    return 0;
}

Output Screen :

                              Click on the Image to ZOOM






The authentication logic in above password protector code can be compromised by exploiting the loophole of strcpy() function. This function copies the password supplied by user to the ‘passwd’ buffer without checking whether the length of password supplied can be accommodated by the ‘passwd’ buffer or not. So if a user supplies a random password of such a length that causes buffer overflow and overwrites the memory location containing the default value ’0′ of the ‘flag’ variable then even if the password matching condition fails, the check of flag being non-zero becomes true and hence the password protection is breached.




5. Write a program in C that returns 3 numbers from a function.

Logic :
               Using structures , you can return.

            ** Can use any New Idea **




           

                            Aptitude Question

1.You are trapped in a room with two doors...  One door lead to certain freedom and the other leads to a ton of worms that you'll have to eat.  You don't know which door goes to the worms and which door gets you out.

There are two guards in the room.  One guard always tells the truth and the other guard always lies.  You don't know which one is honest and which one is the liar.

If you just guessed, you'd have a 50-50 shot.

To figure out which door to choose, you get to ask one guard one question

What is your question and which guard will you ask?


Hint:
+ x - = -
- x + = -

Solution :

This is very tricky and one of the world's most famous logic problems.

Here's the question you should ask... and it doesn't matter which guard you ask:

"If I want freedom, what door will HE say I should go through?"

Think long and hard about it...

Let's say that the red door leads to freedom.

If you ask the honest guard, he will honestly tell you that the other guard will lie and tell you the blue door.

If you ask the lying guard, he will lie and tell you the honest guard will say the blue door.

They've both said the blue door -- the one that leads to the worms.

So, you ask your question... and, then, go through the OTHER door!






2. Use FIVE 0's and any math operators and get 120.

Solution:  
     (0! + 0! + 0! + 0! + 0!)!
  ==> (1+1+1+1+1)!
  ==>   5!
  ==>  5 * 4 * 3 * 2 * 1
  ==>  120.





3.Bridge Question..

Solution:

               Question is wrong..



4. There are three boxes. One is labeled "APPLES" another is labeled "ORANGES". The last one is labeled "APPLES AND ORANGES". You know that each is labeled incorrectly. You may ask me to pick one fruit from one box which you choose.

How can you label the boxes correctly?

Solution:

Pick from the one labeled "Apples & Oranges". This box must contain either only apples or only oranges.
E.g. if you find an Orange, label the box Orange, then change the Oranges box to Apples, and the Apples box to "Apples & Oranges."



5. Mary's mum has four children.
The first child is called April.
The second May.
The third June.
What is the name of the fourth child?

Solution : Mary