C/C++ Programms

1. Write a C program to find the largest of 3 numbers.
2. Write a C program to find the sum of the first 15 even numbers and calculate the square of the sum.
3. Write a C program to find the total and average of the marks given in an array.
4. Write a C program whether the given number is Armstrong number or not.
5. Write a C program whether the given number is Perfect number or not.
6. Write a C program for matrix multiplication.
7. Write a C program for matrix addition
8. Write a C program for matrix subtraction
9. Write a C program to find the exponential series of
                 1 + X + X2/2! + X3/3! + ………..+Xn/n! 
10. Write a C program to find the maximum of 3 numbers using Conditional Operator
11. Calculate grades of N students from 3 tests using arrays. 
12. Write a C program to Trace a matrix 
13. Write a C program to find string palindrome without using String functions
14. Write a C program to demonstrate Structures using student information.
15. Write a C program to calculate the Fibonacci series of a given number.
16. Write a C program to transpose the given matrix.
17. Write a C program for demonstrating Tower of Hanoi using Recursion
18. Write a C program to accept a numbers and generate Square root, cube and exponential values.
19. Write a C program to reverse the given number and check if the number is palindrome.
20. Write a C program to demonstrate the unions using employee information.
21. Write a C program for counting the number of words, lines, special characters in a given text.
22. Write a C program to find the Square root of a given number.
23. Write a C program to find the area and circumference of a circle.
24. Write a C program to find the area & perimeter of a rectangle.
25. Write a C program to convert the given decimal number to binary, Octal and Hexadecimal.
26. Write a C program to convert the given temperature from Centigrade to Fahrenheit.
27. Write a C program to swap 2 numbers using 3rd variable.
28. Write a C program to swap 2 numbers without using 3rd variable.
29. Write a C program to add, subtract, multiply and divide two numbers using functions.
30. Write a C program to generate prime numbers till the given number.
31. Write a C program to generate the Pascal Triangle as
                                      1 
                                  1      1 
                               1     2      1 
                            1     3     3      1 
                         1     4     6      4     1
32. Write a C program to display the given amount in word format.
       Eg: Rs. 245/- as Two hundred Forty five
33. Write a C program to sort the data.
34. Write a C program to search the given number in an array using binary search.
35. Write a C program to calculate the student total and average marks of the given subjects using structures.
36. Write a C program to demonstrate the string functions.
37. Write a C program to find the roots of the quadratic equation.
38. Write a C program to find the number of days in a month using enumerated data types.
39. Write a C program to demonstrate Math functions.
40. Write a C program to calculate factorial using recursive function.
41. Write a C Program convert from any base to any other base.
42. Write a C program to generate Fibonacci numbers using recursion.
43. Write a C program to generate a multiplication table.
44. Write a C program to find the sum of N natural numbers.
45. Write a C program to find the GCD of two integer values.
46. Write a C program to evaluate the polynomial shown as
            3X2 + 5X2 + 6 if x=5
47. Write a C program to determine if the year is a leap year.
48. Write a C program to demonstrate passing structures to functions.
49. Write a C program to demonstrate call by value and call by reference.
50. Write a C program to calculate the total and average of marks using function
51. C Program to count Number of Words in a Line

C++: Standard Template Library (STL)

Standard Template Library (STL) is a C++ library of container classes,algorithms and iterators.It provides many of the basic algorithms and data structures.
STL is a generic library, meaning that its components are heavily parameterized: almost every component in the STL is a template.

STL can be categorized into the following types:
  1. sequence containers (vector,qeque,list)
  2. associative containers (set,multiset,map,multimap)
  3. container adaptors (queue,priority_queue,stack)
  4. Other types of containers (bitset,valarray)

Linux: Shared Memory

  • Shared memory allows two or more process to share a given region of memory created by another process. 
  • This is fastest form of IPC, because the data does not need to be copied between the client and the server. 
  • The trick in using shared memory is synchronizing the access to a given region among multiple processes.
  • If the server is placing data into the shared memory region, the client shouldn’t try to access the data until the server is done. 
  • Often Semaphores are used to synchronize shared memory access.
Advantages of Shared Memory:
 
Random Access
  • You can update a small piece in the middle of a data structure, rather than the entire structure 
Efficiency 
  • Unlike message queues and pipes, which copy data from the process into memory within the kernel, shared memory is directly accessed.
  • Shared memory resides in the user process memory, and is then shared among other processes.
Disadvantages of Shared Memory:
  • No automatic synchronization as in pipes or message queues (you have to provide any synchronization). Synchronize with semaphores or signals.
  • You must remember that pointers are only valid within a given process.
Creating Shared Memory:

        int shmget (key_t key, size_t size, int shmflg); 

   -key is either a number or the constant IPC_PRIVATE shmid is returned    -size is the size of the shared memory data 
   -shmflg is a rights mask (0666) OR’d with one of the following: 
             IPC_CREAT will create or attach 
             IPC_EXCL creates new or it will error if it exists.

Attaching to Shared Memory:

After obtaining a shmid from shmget(), you need to attach or map the shared memory segment to your data reference: 
      
         void * shmat(int shmid, void * shmaddr, int shmflg)          
         -shmid is the id returned from shmget() 
         -shmaddr is the shared memory segment address. Set this to NULL and  
              let the system handle it. 
         -shmflg is one of the following (usually 0):
                               SHM_RDONLY sets the segment readonly
                               SHM_RND sets page boundary access
                               SHM_SHARE_MMU set first available aligned address

dettaching to Shared Memory:

             int shmdt (void *shmaddr);

Shared Memory Control:
        
             int shmctl (int shmid, int cmd, struct shmid_ds * buf);

Linux: Message Queues

Message Queue is a linked list of message structures stored inside the kernel’s memory space and accessible by multiple processes. 

New messages are added at the end of the queue. 


Messages may be obtained from the queue either in a FIFO manner (default) or by requesting a specific type of message (based on message type).

Each message has a message type associated with it. A Message Queue reader can specify which type of message that it will read. Or it can say that it will read all messages in order.

It is quite possible to have any number of Msg Queue readers, or writers. In fact the same process can be both a writer and a reader.


  • Each message structure must start with a long message type:
      struct mymsg 
      {
           long msg_type;
           char mytext[512]; /* rest of message */
           int somethingelse;
      };

Each message queue is limited in terms of both the maximum number of messages it can contain and the maximum number of bytes it may contain.
 

New messages cannot be added if either limit is hit (new writes will normally block).

On linux, these limits are defined as (in /usr/include/linux/msg.h):
        –MSGMAX 8192 /*total number of messages */
        –MSBMNB 16384 /* max bytes in a queue */

Creating a Message Queue:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

            int msgget (key_t key, int msgflg);


The key parameter is either a non-zero identifier for the queue to be created or the value IPC_PRIVATE, which guarantees that a new queue is created. 

The msgflg parameter is the read-write permissions for the queue OR’d with one of two flags: 

IPC_CREAT will create a new queue or return an existing one.

IPC_EXCL added will force the creation of a new queue, or return an error.

Writing to a Message Queue:

           int msgsnd (int msqid, const void * msg_ptr, size_t msg_size, int msgflags);

   msgqid is the id returned from the msgget call
   msg_ptr is a pointer to the message structure 
   msg_size is the size of that structure 
   msgflags defines what happens when no message of the appropriate type is waiting, and can be set to the following: 
          IPC_NOWAIT (non-blocking, return –1 immediately if queue is empty)

Reading from a Message Queue:

      int msgrcv(int msqid, const void * msg_ptr, size_t msg_size, long msgtype, int msgflags);

   msgqid is the id returned from the msgget call
   msg_ptr is a pointer to the message structure
   msg_size is the size of that structure
   msgtype is set to: = 0 first message available in FIFO stack
                             > 0 first message on queue whose type equals type 
   msgflags defines what happens when no message of the appropriate type is waiting, and can be set to the following: 

        IPC_NOWAIT (non-blocking, return –1 immediately if queue is empty)

Message Queue Control:

    int msgctl(int msqid, int cmd, struct msqid_ds * buf);

Linux: Process & Threads


  • Threads share the address space of the process that created it; processes have their own address space. 
  • Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process. 
  • Threads can directly communicate with other threads of its process; processes must use inter process communication to communicate with sibling processes. 
  • Threads have almost no overhead; processes have considerable overhead. 
  • New threads are easily created; new processes require duplication of the parent process. 
  • Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes. 
  • Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.

Linux: Device drivers

Device drivers interface applications to hardware.They are run in Kernel space. they are part of Kernel process and are loaded dynamically. 

Linux provides a feature called Kernel modules through which we can extend the functionality of the Kernel at run time.

Device Drivers in Linux are Kernel Modules. 
Device drivers are classified into three types:
  1. Character device driver
  2. Block device driver
  3. Network device driver
Character Device driver:
  • Device which works on stream of bytes. 
  • This type of device is exposed to client via character device driver. 
  • Driver implements – open, close, ioclt, read, write, mmap functionality. 
Block Device driver:
  • Devices which work on data chuncks/blocks. Example Hard disk/Flash drives. 
  • Block drivers have a completely different interface from character drivers. 
Network interfaces:
  • Any network transaction is made through this interface. 
  • Interface is defined and implemented for communication with network drivers by linux kernel.

C++ Quiz 3

1) By default, all members of a class have ___________ access for all its members     

    a) Public
    b) Protected
    c) No access
    d) private

2) Which operator is used to define a member of a class from outside the class definition itself?
    

    a) ::
    b) :
    c) >>
    d) <<


3) What is a constructor?   

    a) A class automatically called whenever a new object of this class is  
        created.
    b) A class automatically called whenever a new object of this class is 
        destroyed.
    c) A function automatically called whenever a new object of this class is 
        created.
    d) A function automatically called whenever a new object of this class is 
        destroyed.

4) Under what conditions a destructor destroys an object?    

    a) Scope of existence has finished
    b) Object dynamically assigned and it is released using the operator 
       delete.
    c) Program terminated.
    d) Both a and b.

5) If no constructor is declared, the compiler assumes the class to have a default constructor with no arguments    
   
    a)True
    b) False


6) How would you read the expression x.y as?

    a) member y of object pointed by x
    b) member y of object x
    c) member x of object y
    d) All of the above


7) Which type of class has only one unique value for all the objects of that same class?    

    a) this
    b) Friend
    c) Static
    d) both a and b


8) What is the output of the following code snippet?
    class test 
    {
           public:
                   static int n;
                   test () { n++; };
                   ~test () { n--; };
    };
    int test::n=0;
    int main () 
    {
         test a;
         test b[5];
         test * c = new test;
         cout << a.n << endl;
         delete c;
         cout << test::n << endl;
       return 0;
    }

    a) 7 6
    b) 6 7
    c) 5 6
    d) 6 5

9) For which type of class private and protected members of the class can be accessed from outside the same class in which they are declared    

    a) No such class exist
    b)
Friend
    c) Static
    d) Virtual

10) Which of the following cannot be inherited from the base class?

    a) Constructor
    b) Friend
    c)
Both a and b cannot be inherited
    d) Both a and b can be inherited

11) If a class x needs to be derived from a class y, which of the following ways is correct to do so?

    a) class x : public y
    b) class y : public x
    c) class x derives public y
    d) class y derives public x

12) A class cannot inherit members from more than one class

    a) True
    b)
False

13) What is a virtual member?

    a) A member of a friend class that can be redefined in its derived classes
    b) A member of a virtual class that cannot be redefined in its derived classes
    

    c) A member of a static class that can be redefined in its derived classes
    d) A member of a class that can be redefined in its derived classes

14) What is the output of the following code snippet assuming user enters the side as 4?    

    class square
    {
        public:
                double side1;
                double area()
                {
                      return(side1*side1);
                }
    };

    int main(){
         double area1=0;
         square c1,c2;
         cout << "Enter the length of the square" << endl;
         cin >> c1.side;
         cout << "The area of the square is : " << c1.area1() << endl;
      return(0);
    }
   

   a) 16
   b) Will result in an error
   c) 8
   d) 12

15) In C++ two different functions can have the same name if their parameter types are same.   

   a) True
   b)
False

16) Can inline functions be used to improve performance?

   a) yes
   b) No
   c) yes, depends on the situation
   d)
Both a and b

17) Which type of casting can be used only with pointers and references to objects?

   a) Dynamic_cast
   b) cast
   c) Static_cast
   d) Pointer_Cast

18) What is reinterpret_cast used for?  

   a) converts integer pointer type to any other integer pointer type
   b) Converts any pointer type to any other pointer type
   c) converts any pointer type to only integer pointer type
   d)
Both a and b

19) Can #define accept parameters?   

   a) Yes
   b) No

20) #if or #elif can be used to evaluate   

   a) Constant expressions
   b) Macro expressions
   c)
Both a and b
   d) All expressions

C++ Tutorial

C++ Quiz Questions Set 2

1) What is the out put?
void main()
{
 int a, *pa, &ra;
 pa = &a;
 ra = a;
 cout << "a=" << a << "*pa=" << *pa << "ra=" << ra;
}
Answer:
Compiler Error: 'ra',reference must be initialized

Explanation:
Pointers are different from references. One of the main differences is that the pointers can be both initialized and assigned, whereas references can only be initialized. So this code issues an error.

C++ Quiz Questions Set 1

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

#include
using namespace std;
class Sample
{
public:
        int *ptr;
        Sample(int i)
        {
              ptr = new int(i);
        }
        ~Sample()
        {
              delete ptr;
        }
        void PrintVal()
        {
              cout « "The value is " « *ptr;
        }
};
void SomeFunc(Sample x)
{
     cout « "Say i am in someFunc " « endl;
}
int main()
{
     Sample s1= 10;
     SomeFunc(s1);
     s1.PrintVal();
}
Answer:
 prompt> g++ Sample.cpp
 prompt> ./a.out
       Say i am in someFunc 
       Null pointer assignment(Run-time error) 

Explanation: As the object is passed by value to SomeFunc the destructor of the object is called when the control returns from the function. So when PrintVal is called it meets up with ptr that has been freed.

The solution is to pass the Sample object by reference to SomeFunc:

void SomeFunc(Sample &x) 
      cout « "Say i am in someFunc " « endl; 
}

prompt> g++ Sample.cpp
prompt> ./a.out

      Say i am in someFunc
      The value is 10


because when we pass objects by reference that object is not destroyed. while returning from the function.

2) Which is the parameter that is added to every non-static member function when it is called?
 'this' pointer

3) What is the Out Put?
class base
{
        public:
               int bval;
               base()
               { 
                  bval=0;
               }
};
class deri:public base
{
        public:
               int dval;
               deri()
               { 
                  dval=1;
               }
};
void SomeFunc(base *arr,int size)
{
    for(int i=0; i‹size; i++,arr++)
         cout«arr-›bval;
    cout«endl;
}
int main()
{
    base BaseArr[5];
    SomeFunc(BaseArr,5);
    deri DeriArr[5];
    SomeFunc(DeriArr,5);
}
Answer:      
     00000
     01010

Explanation:
The function SomeFunc expects two arguments.The first one is a pointer to an array of base class objects and the second one is the sizeof the array.The first call of someFunc calls it with an array of bae objects, so it works correctly and prints the bval of all the objects. When Somefunc is called the second time the argument passed is the pointeer to an array of derived class objects and not the array of base class objects. But that is what the function expects to be sent. So the derived class pointer is promoted to base class pointer and the address is sent to the function. SomeFunc() knows nothing about this and just treats the pointer as an array of base class objects. So when arr++ is met, the size of base class object is taken into consideration and is incremented by sizeof(int) bytes for bval (the deri class objects have bval and dval as members and so is of size ›= sizeof(int)+sizeof(int) ).


4) What is the Out Put?
class base
{
        public:
              void baseFun()
              { 
                   cout«"from base"«endl;
              }
};
class deri:public base
{
        public:
              void baseFun()
              { 
                   cout« "from derived"«endl;
              }
};
void SomeFunc(base *baseObj)
{
    baseObj->baseFun();
}
int main()
{
    base baseObject;
    SomeFunc(&baseObject);
    deri deriObject;
    SomeFunc(&deriObject);
}
Answer:
       from base
       from base


Explanation:
As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer to a derived class object is passed, it treats the argument only as a base class pointer and the corresponding base function is called.

5) What is the Out Put?
class base
        {
        public:
         virtual void baseFun(){ cout«"from base"«endl;}
        };
 class deri:public base
        {
        public:
         void baseFun(){ cout« "from derived"«endl;}
        };
void SomeFunc(base *baseObj)
{
        baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}
Answer:        
            from base        
            from derived
Explanation:
Remember that baseFunc is a virtual function. That means that it supports run-time polymorphism. So the function corresponding to the derived class object is called.

Linux: Inter Process Communication

The Linux IPC (Inter-process communication) facilities provide a methods for multiple processes to communicate with one another.
IPC Types:
  • Half-duplex UNIX pipes
  • FIFOs (named pipes)
  • Message queues
  • Semaphore 
  • Shared Memory
  • Networking sockets
Shared memory is the fastest IPC mechanism.

Linux: Named Pipes(FIFO)

A named pipe is really just a special kind of file (a FIFO file) on the local hard drive. Unlike a regular file, a FIFO file does not contain any user information. Instead, it allows two or more processes to communicate with each other by reading/writing to/from this file.

A named pipe works much like a regular pipe, but does have some noticeable differences.
  • Named pipes exist as a device special file in the file system.
  • Processes of different ancestry can share data through a named pipe.
  • When all I/O is done by sharing processes, the named pipe remains in the file system for later use.
The easiest way to create a FIFO file is to use the mkfifo command. This command is part of the standard Linux utilities and can simply be typed at the command prompt of your shell. You may also use the mknod command to accomplish the same thing.

prompt> mkfifo /tmp/myFIFO

we can also use of the mknod() system call:

LIBRARY FUNCTION: mknod(); 
PROTOTYPE: int mknod( char *pathname, mode_t mode, dev_t dev);

RETURNS: 0 on success, -1 on error: 
              errno = EFAULT (pathname invalid) 
                         EACCES (permission denied) 
                         ENAMETOOLONG (pathname too long) 
                         ENOENT (invalid pathname) 
                         ENOTDIR (invalid pathname)

mknod("/tmp/MYFIFO", S_IFIFO|0666, 0);

Normally, blocking occurs on a FIFO. In other words, if the FIFO is opened for reading, the process will "block" until some other process opens it for writing. This action works vice-versa as well. If this behavior is undesirable, the O_NONBLOCK flag can be used in an open() call to disable the default blocking action

Linux: Pipes(Half Duplex)

Pipe is an effective way of communication(Half Duplex) between process. Pipe has two descriptors. One descriptor is used for reading while other end is used for writing.

Usage of pipe is to have communication between child and parent process. We also use pipe to redirect of output of a process to another process. We often use pipe in our shell scripts.


With half-duplex pipes, any connected processes must share a related ancestry. Since the pipe resides within the confines of the kernel, any process that is not in the ancestry for the creator of the pipe has no way of addressing it. This is not the case with named pipes (FIFOS).

SYSTEM CALL: pipe(); 
PROTOTYPE: int pipe( int fd[2] ); 

RETURNS: 0 on success -1 on error: 
               errno = EMFILE (no free descriptors) 
                          EMFILE (system file table is full) 
                          EFAULT (fd array is not valid) 

NOTES: fd[0] is set up for reading, fd[1] is set up for writing

Virtual File System on Linux


VFS is a kernel software layer that handles all system calls related to file systems. Its main strength is providing a common interface to several kinds of file systems.So that it is possible to separate actual "low-level" filesystem code from the rest of the kernel. 


Dynamic Memory Allocation in C

In dynamic memory management memory will be allocate at run time via a group of functions in the C standard library, namely malloc, realloc, calloc and free. This is also known as heap memory.

malloc:

The malloc() function dynamically allocates memory when required. This function allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error.


void * malloc (size_t size);

malloc allocates memory in bytes.malloc() does not initialize the memory allocated.

int *ptr = malloc(sizeof(int) * 10); // allocates 10 ints!

calloc:

void *calloc(size_t nvar,size_t size)

calloc allocates memory in blocks. calloc initializes the allocated memory to zero. calloc takes two arguments, number of variables to be allocated and size of each variable.

int num;
int *ptr = (int*)calloc(num, sizeof(int));

realloc:

The realloc() function changes the size of a block of memory that was previously allocated with malloc() or calloc(). The function prototype is

void *realloc(void *ptr, size_t size);

The ptr argument is a pointer to the original block of memory. The new size, in bytes, is specified bysize.
There are several possible outcomes with realloc():

  • If sufficient space exists to expand the memory block pointed to by ptr, the additional memory is allocated and the function returns ptr.
  • If sufficient space does not exist to expand the current block in its current location, a new block of the size for size is allocated, and existing data is copied from the old block to the beginning of the new block. The old block is freed, and the function returns a pointer to the new block.
  • If the ptr argument is NULL, the function acts like malloc(), allocating a block of size bytes and returning a pointer to it.
  • If the argument size is 0, the memory that ptr points to is freed, and the function returns NULL.
  • If memory is insufficient for the reallocation (either expanding the old block or allocating a new one), the function returns NULL, and the original block is unchanged.
free:

When you allocate memory with either malloc() or calloc(), it is taken from the dynamic memory pool that is available to your program. This pool is sometimes called the heap, and it is finite. When your program finishes using a particular block of dynamically allocated memory, you should deallocate, or free, the memory to make it available for future use. To free memory that was allocated dynamically, use free(). 


void free(void *ptr); 

The free() function releases the memory pointed to by ptr. This memory must have been allocated with malloc(), calloc(), or realloc(). If ptr is NULL, free() does nothing.

For loop syntax in C

for(<loop variable initialization>;<loop condition>;<loop variable increment/decrement>)
{
           loop statement 1;
           loop statement 2;
           loop statement 3;
              ………………….
           loop statement N;
}


Example:
#include<stdio.h>
#include<conio.h>
 
void main()
{
 
     int i;
     clrscr();
 
     for(i=1;i<=10;i++)
     {
            printf("%d for loop.\n",i);
     }
      getch();
}
When above “for loop” block (line no. 10 - 13) gets executed let me tell you what happens.

For loop execution steps:

  • At first value of “i” is set to 1, this happens only once in loop execution.
  • Next loop condition (i<=10) is tested. Since value of “i” is 1, it satisfies loop condition and loop statement is executed.
  • When we reach at closing brace of “for loop” then control moves back to beginning of “for loop” and where value of “i” is incremented by 1 (i++).
  • Again it starts from step no. 2. This looping will continue till loop condition (i<=10) is tested to false (means condition is no longer true because value of “i” would be greater than 10, i.e. 11).
  • When value of “i” reaches to 11 then control exits from loop and next statement, after loop block, is executed (in above program line no. 14).

What is Vtable & Vptr in C++

Vtable contains the addresses of virtual functions.The compiler creates a Vtable for each class that contains virtual functions and for classes that are derived from it.The Vtable contains the addresses in the order in which virtual functions are defined with in the class.

Let us understand the Vtable with the help of the following example:

class shape
{
   public:
          virtual void draw1()
          {
          }
          virtual void draw2()
          {
          }
};
class circle:public shape
{
   public:
          void draw1()
          {
          }
          void draw2()
          {
          }
};
void main()
{
   shape *p,q;
   circle c;
   p=&q;
   p->draw2();
   p=&c;
   p->draw2();
}

whenever we create an object of the class,the class gets loaded into the memory and the Vtable gets created.In this program we have created an object of shape as well as of circle.Hence there will be two Vtables in memory.

The address of the Vtable stored in the object Vptr.