Showing posts with label simple c programs. Show all posts
Showing posts with label simple c programs. Show all posts

Friday, July 13, 2012

C interview Programs and Programming related questions answers [PDF]

In this post I will try to answer some common c interview questions related to coding or programming as a sample. You will find links to several solved c programming questions answers in this post that can help you to prepare for c interview. I will try my best to provide as many c interview programs as possible.

C in one of the first language taught to engineering students. Therefore knowledge of c is judged in interviews of both fresher’s as well as experienced programmers. C programs listed here can help freshers and even people with 1-3 years of experience in programming. Some typical c programs questions asked in interview are mentioned below:

C Interview code snippets | Good c interview question with answers for test


More commonly asked c interview question programs


Pattern questions asked in technical c interviews
*                   *
* * *           * * *
* * * * *   * * * * *
* * * * * * * * * * *
1
121
12321
1234321
12321
121
1
       2
     4 5 6
   6 7 8 9 10
     4 5 6
       2
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1

Tuesday, June 12, 2012

C program to reverse a number | Source code and Algorithm explanation

In order to reverse a number you should first input the number and then extract the digits of number one by one. In order to extract digit you can use % operator which results in remainder of division operation. 13%10 is  3. Thus by doing mod 10 you can get rightmost digit of number. After extracting digit you can remove the same from number by storing result of /10 in integer variable. Eg 13/10 is 1.3 but on storing it in integer variable only 1 is stored.

In order to reverse a number using while loop in c language you must run the loop till the number is not 0 that is all the digits haven't been extracted. Assuming that you want reverse of number in variable called y (initial value of y should be zero), you should write y=y*10+extracted digit in while loop.

Consider test input of a=123,y=0

iteration 1
y=0*10+3=3, a=12
iteration 2
y=3*10+2=32, a=1
iteration 3
y=32*10+1=321 a=0

thus we get reverse of number in y.

Here is source code of c program to reverse a number


 int main()  
 {  
   int a;  
   printf("Enter a number :");  
   scanf("%d",&a);  
   int y=0;  
   while(a)  
   {  
     y=y*10+a%10;  
     a=a/10;  
   }  
   printf("\nreverse= %d",y);  
   getch();  
   return 0;  
 }  

Saturday, April 14, 2012

C Program to calculate and display sum of two matrix

 #include<stdio.h>  
 #include<conio.h>  
 void main()  
 {  
 int a[3][3],b[3][3],c[3][3],i,j;  
 clrscr();  
 printf("Enter the elements into first matrix \n");  
 for(i=0;i<3;i++)  
      for(j=0;j<3;j++)  
      scanf("%d",&a[i][j]);  
      printf("\nEnter the elements into second matrix\n");  
      for(i=0;i<3;i++)  
           for(j=0;j<3;j++)  
           scanf("%d",&b[i][j]);  
      for(i=0;i<3;i++)  
           for(j=0;j<3;j++)  
           c[i][j]=a[i][j]+b[i][j];  
      for(i=0;i<3;i++)  
           {  
           printf("\t\t");  
           for(j=0;j<3;j++)  
           printf("%d\t",c[i][j]);  
           printf("\n\a");  
           }  
 getch();  
 }  

C language program to add numbers using pointers

 #include<stdio.h>  
 #include<conio.h>  
  void main()  
  {  
  int a[10],sum=0;  
  int *j;  
  int i,n;  
  clrscr();  
  printf("How many elements you want to add:");  
  scanf("%d",&n);  
  printf("Enter element:");  
  for(i=0;i<n;i++)  
  {  
  scanf("%d",&a[i]);  
  }  
  j=&a[0];  
  for(i=0;i<n;i++)  
    {  
     sum=sum+*j;  
     j++;  
    }  
  printf("sum=%d",sum);  
 }  

C Program to show use of command line arguments

 #include<stdio.h>  
 #include<conio.h>  
 #include<stdlib.h>  
 void main(int argc,char *argv[])  
 {  
 int sum=0,i;  
 //if wrong number of command line arguments
 if(argc<3)  
 {  
 printf("Incorrect number of arguments:\n");  
 getch();  
 return 0;  
 }  
 //Add all the numbers entered using atoi function  
 for(i=1;i<argc;i++)  
 {  
 sum+=atoi(argv[i]);  //string to number
 }  
 //print the sum  
 printf("Ans=%d",sum);  
 getch();  
 }  

Simple C Program to show use of Comparison Operators in c language

 int main()  
 {  
 int number1 , number2;  
 printf("Enter the number1 number to compare.\n");  
 scanf("%d",&number1);  
 printf("Enter the number2 number to compare.\n");  
 scanf("%d",&number2);  
 printf("number1 > number2 has the value %d\n", number1 > number2);  
 printf("number1 < number2 has the value %d\n", number1 < number2);  
 printf("number1 == number2 has the value %d\n", number1 == number2);  
 return 0;  
 }  

What is fork() in C language?


As we know, our running program is a process. From this process we can create another process. There is a parent-child relationship between the two processes. The way to achieve this is by using a library function called fork( ). This function splits the running process into two processes, the existing one is known as parent and the new process is known as child. Here is a program that demonstrates this…

# include <sys/types.h>
int main( )
{
printf ( "Before Forking\n" ) ;
fork( ) ;
printf ( "After Forking\n" ) ;
}
Here is the output of the program…
Before Forking
After Forking
After Forking

As we know, fork( ) creates a child process and duplicates the code of the parent process in the child process. There onwards the execution of the fork( ) function continues in both the processes. Thus the duplication code inside fork( ) is executed once, whereas the remaining code inside it is executed in both the parent as well as the child process. Hence control would come back from fork( ) twice, even though it is actually called only once. When control returns from fork( ) of the parent process it returns the PID of the child process, whereas when control returns from fork( ) of the child process it always returns a 0. This can be exploited by our program to segregate the code that we want to execute in the parent process from the code that we want to execute in the child process. We have done this in our program using an if statement. In the parent process the ‘else block’ would get executed, whereas in the child process the ‘if block’ would get executed.


# include <sys/types.h>
int main( )
{
int pid ;
pid = fork( ) ;
if ( pid == 0 )
{
printf ( "Child : Hello I am the child process\n" ) ;
printf ( "Child : Child’s PID: %d\n", getpid( ) ) ;
printf ( "Child : Parent’s PID: %d\n”, getppid( ) ) ;
}
else
{
printf ( "Parent : Hello I am the parent process\n" ) ;
printf ( "Parent : Parent’s PID: %d\n”, getpid( ) ) ;
printf ( "Parent : Child’s PID: %d\n", pid ) ;
}
}

What is C language Program and data type?


C language program


C program is instruction given to computer in c language to perform particular task. As a building is made of bricks, a C program is made of basic elements, such as expressions, statements, statement blocks, and function blocks.

C language data type

Data types are means to identify what type of data is being stored in variable.
The primary data types could be of three varieties—char, int, and float. It may seem odd to many, how C programmers manage with such a tiny set of data types. C programmers can derive many data types from these three types. A C programmer can always invent whatever data type he needs.
Not only this, the primary data types themselves could be of several types. For example, a char could be an unsigned char or a signed char. Or an int could be a short int or a long int. 

Basics of C programming language and notes


What is C language basic syntax?


This is basic hello world program in c language. You can use turbo c++ or dev c++ to compile and run the c language program.
 #include <stdlib.h>
 #include <stdio.h>

 int main()
 {
 printf ("Hello World \n");
 getch();
 }

C Language is Compiled Language and not Interpreted Language.


There are two types of programming languages: compiled language and interpreted language. A compiler is needed to translate a program written in a compiled language into machine understandable code (that is, binary code) before you can run the program on your machine. When the translation is done, the binary code can be saved into an application file. You can keep running the application file without the compiler unless the program (source code) is updated and you have to recompile it. The binary code or application file is also called executable code (or an executable file).

On the other hand, a program written in an interpreted language can be run immediately after you finish writing it. But such a program always needs an interpreter to translate the high-level instructions into machine-understandable instructions (binary code) at runtime. You cannot run the program on a machine unless the right interpreter is available. You can think of the C language as a compiled language because most C language vendors make only C compilers to support programs written in C.

What is C Language’s history?


The C language was developed by Dennis Ritchie in 1972 at AT&T Bell Labs.

For many years, the de facto standard for the C programming language was the K&R standard because of the book The C Programming Language, written by Brian Kernighan and Dennis Ritchie in 1978. However, there were many changes unofficially made to the C language that were not presented in the K&R standard.

Fearing that C might lose its portability, a group of compiler vendors and software developers petitioned the American National Standards Institute (ANSI) to build a standard for the C language in 1983. ANSI approved the application and formed the X3J11 Technical Committee to work on the C standard. By the end of 1989, the committee approved the ANSI standard for the C programming language.

The ANSI standard for C enhances the K&R standard and defines a group of commonly used C functions that are expected to be found in the ANSI C standard library. Now, all C compilers have the standard library, along with some other compiler-specific functions.

What is C Language programming ? C Language notes in pdf ppt doc


What is C Language?

C is a programming language. The C language was developed by Dennis Ritchie in 1972 at AT&T Bell Labs. It was called his newly developed language C simply because there was a B programming language already and the B language led to the development of C Language. C language is based on ALGOL and B languages.

As said above C language is a programming language. Programming language is any language that computer system can understand directly or indirectly to can perform the actions asked by the programmer as set of instructions in form of a computer program.

C language is a high-level programming language. In the computer world, the further a programming language is from the computer architecture, the higher the language's level. You can imagine that the lowest-level languages are machine languages that computers understand directly. The high-level programming languages, on the other hand, are closer to our human languages.

A computer program written in a high-level language, such as C, Java, or Perl, is just a text file, consisting of English-like characters and words. We have to use some special programs, called compilers or interpreters, to translate such a program into a machine-readable code. That is, the text format of all instructions written in a high-level language has to be converted into the binary format. The code obtained after the translation is called binary code. Prior to the translation, a program in text format is called source code. The smallest unit of the binary code is called a bit (from binary digit), which can have a value of 0 or 1. 8 bits make up one byte, and half a byte (4 bits) is one nibble.

  • ·         C is a general-purpose programming language.
  • ·         C is a high-level language that has the advantages of readability, maintainability, and portability.
  • ·          C is a very efficient language that allows you to get control of computer hardware and peripherals.
  • ·          C is a small language that you can learn easily in a relatively short time.
  • ·         Programs written in C can be reused.
  • ·          Programs written in C must be compiled and translated into machine-readable code before the computer can execute them.

What is C language in simple words?

C is a general-purpose programming language. It's a high-level language that has advantages such as readability, maintainability, and portability. Also, C allows you to get down to the hardware to increase the performance speed if needed. A C compiler is needed to translate programs written in C language into machine-understandable code. The portability of C is realized by recompiling the C programs with different C compilers specified for different types of computers.


You can browse this blog for good C Language notes.

Friday, April 13, 2012

c program for pascal triangle with and without arrays using for loops

Pascal triangle in c without using array  C code to print Pascal triangle  Simple c program for Pascal triangle  C program to generate Pascal triangle Pascal triangle program in c language  C program to print Pascal triangle using for loop


http://cquestionbank.blogspot.in/2010/06/write-c-program-to-print-pascal.html



c program to print pascal triangle [using arrays and for loop]


c program for prime number between 1 to n


I have assumed N to be hundred. You can use scanf to input N and display prime number between 1 to n.


Prime Numbers are numbers which are only divisible by two numbers. eg 2,3,5,7,11 etc.


c program for prime number


int main()
{
int i,j,n=0;
for(i=2;i<=100;i++)
{
for(j=1;j<=i;j++)
{
if(i%j==0)
{
n++;
}
}
if(n==2)
printf("%d\n",i);
n=0;
}
getch();
}

Tuesday, March 20, 2012

C Program to find factorial of a number

Simple C Program


int main()
{
int n,i,f=1;
printf("enter any num \n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("factorial is %d ",f);
system("pause");
}

Wednesday, March 14, 2012

FCFS First come first serve with arrival time CPU Scheduling Program in c dev cpp

 #include <stdio.h>  
 #include <conio.h>  
 /* First Come First Serve CPU Scheduling Algorithm  
   By Suraj Jha & Abhas Tandon  
 */  
 int wt[10],bt[10],at[10],tat[10],n;  
 float awt,atat;  
 void input(){  
        printf("Enter Number of processes:");  
        scanf("%d",&n);  
        int i;  
        for(i=0;i<n;i++)  
        {  
          printf("Enter Burst Time of process %d:",i+1);  
          scanf("%d",&bt[i]);         
          printf("Enter Arrival Time of process %d:",i+1);  
          scanf("%d",&at[i]);         
        }  
 }  
 void calculate(){  
    wt[0]=0;  
    atat=tat[0]=bt[0];  
    int btt=bt[0];//to store total burst time sum  
    int i;  
    for(i=1;i<n;i++){  
      wt[i]=btt-at[i];  
      btt+=bt[i];        
      awt+=wt[i];     
      tat[i]= wt[i]+bt[i];   
      atat+=tat[i];    
    }  
    atat/=n;  
    awt/=n;       
 }  
 void display(){  
    int i;  
    printf("SR.\tA.T.\tB.T.\tW.T.\tT.A.T.\n");  
    for(i=0;i<n;i++)  
    {  
    printf("%3d\t%3d\t%3d\t%3d\t%4d\n",i+1,at[i],bt[i],wt[i],tat[i]);          
    }    
    printf("Average Waiting Time: %f\nAverage Turn Around Time:%f",awt,atat);  
 }    
 int main(){  
       printf("FCFS CPU Scheduling Algorithm\n");  
       input();  
       calculate();  
       display();   
       getch();   
 }  

Short Job First Non PREEMPTIVE with arrival time CPU Scheduling Algorithm in C Source code program

 #include <stdio.h>  
#include <conio.h>
/* Short Job First NON PREEMPTIVE CPU Scheduling Algorithm
By Suraj Jha & Abhas Tandon
Please note that program has some extra printf statements that were used for debugging
They can be removed if required
*/
int n;
struct sjf{
int sr;
int wt,bt,at,tat;
int flag;
}arr[10];
struct sjf queue[15];
int f=-1,r=-1;
void enqueue(struct sjf x){
if(f==-1 && r==-1)
{
queue[++f]=x;
r++;
}
else{
queue[++r]=x;
}
printf("Added %d to queue\n",queue[r].sr);
}
int dequeue(){
int x=f;
if(f==r)
f=r=-1;
else
f++;
printf("Dequeue %d\n",queue[x].sr);
return queue[x].sr;
}
void sortQueue(){
int i,j;
for(i=f;i<=r;i++)
{
for(j=i+1;j<=r;j++) {
if(queue[i].bt>queue[j].bt)
{
struct sjf temp= queue[i];
queue[i]=queue[j];
queue[j]=temp;
}
}
}
}
void dispq(){
int i;
if(f==-1)
printf("Empty");
for(i=f;i<=r;i++)
printf("%d ",queue[i].sr);
printf("\n%d %d\n",f,r);
}
float awt,atat;
void input(){
printf("Enter Number of processes:");
scanf("%d",&n);
int i;
for(i=0;i<n;i++)
{
printf("Enter Burst Time of process %d:",i+1);
scanf("%d",&arr[i].bt);
printf("Enter Arrival Time of process %d:",i+1);
scanf("%d",&arr[i].at);
arr[i].sr=i;
arr[i].flag=0;
}
}
void calculate(){
int i,j,btto;
arr[0].wt=0;
//arr[0].flag=1;
int btt=arr[0].bt;
arr[0].tat=arr[0].bt;
atat=arr[0].bt;
i=0;
do{
printf("Start of Do While\n");
for(j=1;j<n;j++){
printf("cmp arr[j] %d btt %d jFlag %d\n",arr[j].at,btt,arr[j].flag);
if(arr[j].at<btt )
enqueue(arr[j]);
}
sortQueue();
printf("Sorted Queue\n");
btto=btt;//Starting time for this process
printf("Btto=%d\n",btto);
int pid=dequeue();
while(arr[pid].flag==1){
pid=dequeue();
}
btt+=arr[pid].bt;
printf("After Adding %d btt =%d\n",queue[f].bt,btt);
arr[pid].flag=1;//to show that process is executed
printf("%d Process %d executed",i,pid);
arr[pid].wt=btto - arr[pid].at;
arr[pid].tat= arr[pid].bt+ arr[pid].wt;
printf("A %d %d %d %d\n",btto,arr[pid].at,arr[pid].bt,arr[pid].wt);
awt+=arr[pid].wt;
atat+= arr[pid].tat;
//printf("%d %d\n",f,r);
i++;
printf("I incremented\n");
dispq();
while(f!=-1)
dequeue();
printf("Queue refresed Ready for next run\n");
}while(i<n-1);
awt/=n;
atat/=n;
}
void display(){
int i;
printf("SR.\tA.T.\tB.T.\tW.T.\tT.A.T.\n");
for(i=0;i<n;i++)
{
printf("%3d\t%3d\t%3d\t%3d\t%4d\n",i+1,arr[i].at,arr[i].bt,arr[i].wt,arr[i].tat);
}
printf("Average Waiting Time: %f\nAverage Turn Around Time:%f",awt,atat);
}
int main(){
printf("SJF CPU Scheduling Algorithm\n");
input();
calculate();
display();
getch();
}

Thursday, October 13, 2011

Rest In Peace Dennis Ritche : Creator of C & unix

/*A 'c' program in memory of Dennis Ritche*/

#include
int main(){
printf("%c%c%c%c%c%c%c%c%c%c%c%c%c",printf("\n")*82,printf("\n")*46,printf("\n")*73,printf("\n")*46,printf("\n")*80,printf("\n")*46,printf("\n")*32,printf("\n")*82,printf("\n")*105,printf("\n")*99,printf("\n")*104,printf("\n")*105,printf("\n")*101);
getch();
return 0;
}

Saturday, May 21, 2011

C Program to implement telephone billing System

/*Code to accept 10 telephone customers’ data into a structure
object.
The fields are:
Customer name
Telephone number
Units to be billed
Calculate Bill Amount, which is Rent of Rs. 250 plus Re 0.80 for each
unit. Prepare the Bill and print it.*/


int main()
{
int n,i;
struct bill
{
char name[20];
int num;
int units;
}a[50];


printf("\nEnter the no of customers");
scanf("%d",&n);
for(i=0;i {
printf("\nEnter the customer's name");
scanf("%s",&a[i].name);
printf("\nEnter the customer's number");
scanf("%d",&a[i].num);
printf("\nEnter the no of units");
scanf("%d",&a[i].units);
}
for(i=0;i {
printf("\nname %s",a[i].name);
printf("\nnumber %d",a[i].num);
printf("\nBill is Rs %f",((a[i].units)*0.8)+250);



}
system("pause");
return 0;
}

C program to explain use of Structures

/*Code a program to do the following with a structure:
a. Declare the structure with the following members:
Name char 20
Age int
Gender char 1
Marks float
b. Initialize the members with your values.
c. Print the memory space occupied by the structure object.
d. Print the formatted structure data.*/

int main()
{
int n,i;
struct marks
{
char name[20];
int age;
char gen;
float marks;
}a[50];


printf("\nEnter the no of entries");
scanf("%d",&n);
for(i=0;i {
printf("\nEnter the name");
scanf("%s",&a[i].name);
printf("\nEnter the age");
scanf("%d",&a[i].age);
printf("\nEnter the gender");
scanf("%c",&a[i].gen);
printf("\nEnter the no of marks");
scanf("%f",&a[i].marks);
}
for(i=0;i {
printf("size of object a%d is %d",i,sizeof(a[i]));
}
for(i=0;i {
printf("\nname %s",a[i].name);
printf("\nage %d",a[i].age);
printf("\n%c",a[i].gen);
printf("\n%f",a[i].marks);
}
system("pause");
return 0;
}