Sunday, 30 September 2012

Program to delete a file using C


#include<stdio.h>
 
main()
{
   int status;
   char file_name[30];
 
   printf("Enter the name of file you want to delete\n");
   gets(file_name);
 
   status = remove(file_name);
 
   if( status == 0 )
      printf("%s file deleted successfully.\n", file_name);
   else
   {
      printf("Unable to delete the file\n");
      perror("Error");
   }
 
   return 0;
}

Output:
       Enter the name of file you want to delete multiply.c
       multiply.c file deleted successfully.

Thursday, 27 September 2012

How to make a Pyramid using C


#include<stdio.h>
 
main()
{
   int row, c, n, temp;
 
   printf("Enter the number of rows in pyramid of stars you wish to see ");
   scanf("%d",&n);
 
   temp = n;
 
   for ( row = 1 ; row <= n ; row++ )
   {
      for ( c = 1 ; c < temp ; c++ )
         printf(" ");
 
      temp--;
 
      for ( c = 1 ; c <= 2*row - 1 ; c++ )
         printf("*");
 
      printf("\n");
   }
 
   return 0;
}

Output:

Thursday, 20 September 2012

Fibonacci series program using c


#include<stdio.h>
 
main()
{
   int n, a = 0, b = 1, next, c;
 
   printf("Enter the number of terms\n");
   scanf("%d",&n);
 
   printf("First %d terms of Fibonacci series are :-\n",n);
 
   for ( c = 0 ; c < n ; c++ )
   {
      if ( c <= 1 )
         next = c;
      else
      {
         next = a + b;
         a = b;
         b = next;
      }
      printf("%d\n",next);
   }
 
   return 0;
}







Output:

Thursday, 13 September 2012

Best applications of C and C++ Language

The famous applications and software packages have been written in C or C++ programming languages due to the fact that most of the programs are partially or completely written in C or C++. Apart from applications there are some operating systems that are written in C++ programming language.

Ex:Windows 95, 98, 2000, XP, Apple OS X, Symbian OS and BeOS.

Adobe Systems:
All major applications of adobe systems are developed in C++ programming language. These applications include Photoshop & Image Ready, Illustrator and Adobe Premier.

Google:
Some of the Google applications are also written in C++, including Google file system and Google Chromium.

Mozilla:
Internet browser Firefox and email client Thunderbird are written in C++ programming language and they are also open source projects.

MySql:
MySQL is the world’s most popular open source database software, with over 100 million copies of its software downloaded or distributed throughout its history. Many of the world’s largest and fastest-growing organizations use MySQL to save time and money powering their high-volume Web sites, critical business systems, and packaged software — including industry leaders such as Yahoo!, Alcatel-Lucent, Google, Nokia, YouTube, Wikipedia, and Booking.com.


Alias System - Autodesk Maya:
Maya 3D software was originally developed by Alias System Corporation and was later carried over by Autodesk. Maya 3D software, now a days is widely used in computers, video games, television. It is a powerful, integrated 3D modelling, animation, visual effects, and rendering solution.

Winamp Media Player:
Winamp is the ultimate media player, allows you to manage audio and video files, rip and burn CDs, enjoy free music, access and share your music and videos remotely, and sync your music to your iPod , Creative, and Microsoft Plays for Sure devices . Winamp features album art support, streams audio and video content, and provides access to thousands of internet radio stations and podcasts.

12D solutions:
12D Solutions Pty Ltd is an Australian software developer specialising in civil engineering and surveying applications. Computer Aided Design system for surveying, civil engineering, and more. 12D Solutions clients include civil and water engineering consultants, environmental consultants, surveyors, local, state and national government departments and authorities, research institutes, construction companies and mining consultants.

Bloomberg:
Providing real-time financial information to investors.

callas software:
callas software develops pdf creation, optmisation, updation and pdf form creation tools and plugins.

Image systems:
These are the world leading motion analysys programs and film scanner systems.

Operating Systems developed in C++
Apple os x:
Few parts of apple OS X are written in C++ programming language. Also few application for iPod are written in C++.

Microsoft:
Literally most of the software are developed using various flavors of Visual C++ or simply C++. Most of the big applications like Windows 95, 98, Me, 200 and XP are also written in C++. Also Microsoft Office, Internet Explorer and Visual Studio are written in Visual C++.

Symbian os:
Symbian OS is also developed using C++. This is one of the most widespread OS’s for cellular phones.





Tuesday, 11 September 2012

Bubble sort program using c


#include <stdio.h>
 
int main()
{
  int array[100], n, c, d, swap;
 
  printf("Enter number of elements\n");
  scanf("%d", &n);
 
  printf("Enter %d integers\n", n);
 
  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);
 
  for (c = 0 ; c < ( n - 1 ); c++)
  {
    for (d = 0 ; d < n - c - 1; d++)
    {
      if (array[d] > array[d+1]) /* For decreasing order use < */
      {
        swap       = array[d];
        array[d]   = array[d+1];
        array[d+1] = swap;
      }
    }
  }
 
  printf("Sorted list in ascending order:\n");
 
  for ( c = 0 ; c < n ; c++ )
     printf("%d\n", array[c]);
 
  return 0;
}

Monday, 10 September 2012

C Program snippets-6

1.main()
{
clrscr();
}
clrscr();
Answer:
No output/error
Explanation:
The first clrscr() occurs inside a function. So it becomes a function call. In the second clrscr(); is a function declaration (because it is not inside any function).
2. enum colors {BLACK,BLUE,GREEN}
 main()
{
  
 printf("%d..%d..%d",BLACK,BLUE,GREEN);
   
 return(1);
}
Answer:
0..1..2
Explanation: enum assigns numbers starting from 0, if not explicitly defined.

3.void main()
{
 char far *farther,*farthest;
  
 printf("%d..%d",sizeof(farther),sizeof(farthest));
   
 }
Answer:
4..2
Explanation:
the second pointer is of char type and not a far pointer
4.main()
{
 int i=400,j=300;
 printf("%d..%d");
}
Answer:
400..300
Explanation:
printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values. If more number of assignments given in the program,then printf will take garbage values.
5.main()
{
 char *p;
 p="Hello";
 printf("%c\n",*&*p);
}
Answer:
H
Explanation:
* is a dereference operator & is a reference operator. They can be applied any number of times provided it is meaningful. Here p points to the first character in the string "Hello". *p dereferences it and so its value is H. Again & references it to an address and * dereferences it to the value H.

Sunday, 9 September 2012

Program to print Floyd's triangle using C


#include <stdio.h>
 
int main()
{
  int n, i,  c, a = 1;
 
  printf("Enter the number of rows of Floyd's triangle to print\n");
  scanf("%d", &n);
 
  for (i = 1; i <= n; i++)
  {
    for (c = 1; c <= i; c++)
    {
      printf("%d ",a);
      a++;
    }
    printf("\n");
  }

Java program to perform garbage collection

import java.util.*;
 
class GarbageCollection
{
   public static void main(String s[]) throws Exception
   {
      Runtime rs =  Runtime.getRuntime();
      System.out.println("Free memory in jvm (Java Virtual Machine) before Garbage Collection        ="+rs.freeMemory());
      rs.gc();
      System.out.println("Free memory in jvm (Java Virtual Machine) after Garbage Collection ="+rs.freeMemory());
   }
}

program to get ip address using java


import java.net.InetAddress;

class IPAddress
{
public static void main(String args[]) throws Exception
{
System.out.println(InetAddress.getLocalHost());
}
}


Explanation:
                  This program prints ip address of your computer system. InetAddress class of java.net package is used, getLocalHost method returns InetAddress object which represents local host.

Saturday, 8 September 2012

Program to shutdown or turn off computer using c

For Windows Xp

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

main()
{
char ch;

printf("Do you want to shutdown your computer now (y/n)\n");
scanf("%c",&ch);

if (ch == 'y' || ch == 'Y')
  system("C:\\WINDOWS\\System32\\shutdown -s");

return 0;
}

For Windows 7

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

main()
{
char ch;

printf("Do you want to shutdown your computer now (y/n)\n");
scanf("%c",&ch);

if (ch == 'y' || ch == 'Y')
system("C:\\WINDOWS\\System32\\shutdown /s");

return 0;
}


Fow Ubuntu

#include <stdio.h>

int main() {
system("shutdown -P now");
return 0;
}

Program to calculate factorial of given number

#include <stdio.h>

int main()
{
int c, n, fact = 1;

printf("Enter a number to calculate it's factorial\n");
scanf("%d", &n);

for (c = 1; c <= n; c++)
fact = fact * c;

printf("Factorial of %d = %d\n", n, fact);

return 0;

Add digits of number in c

#include <stdio.h>
 
main()
{
   int n, sum = 0, remainder;
 
   printf("Enter an integer\n");
   scanf("%d",&n);
 
   while(n != 0)
   {
      remainder = n % 10;
      sum = sum + remainder;
      n = n / 10;
   }
 
   printf("Sum of digits of entered number = %d\n",sum);
 
   return 0;
}
 
For example if the input is 78, sum(variable) is 0 initially
78%10 = 8 (% is modulus operator which gives us remainder when 98 is divided by 10).

sum = sum + remainder

so sum = 8 now.
78/10 = 7 because in c whenever we divide integer by another integer we get an integer.
7%10 = 7
sum = 8(previous value) + 7
sum = 15
7/10 = 0.

So finally n = 0, loop ends we get the required sum. 

Program to calculate the leap year

#include <stdio.h>
 
int main()
{
  int year;
 
  printf("Enter a year to check if it is a leap year\n");
  scanf("%d", &year);
 
  if ( year%400 == 0)
    printf("%d is a leap year.\n", year);
  else if ( year%100 == 0)
    printf("%d is not a leap year.\n", year);
  else if ( year%4 == 0 )
    printf("%d is a leap year.\n", year);
  else
    printf("%d is not a leap year.\n", year);  
 
  return 0;
}

Thursday, 6 September 2012

C Program Samples-5


1.#define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer:
64
Explanation:
the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64
2.main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s   %s",p,p1);
}
Answer:
ibj!gsjfoet
Explanation:
++*p++ will be parse in the given order
  • *p that is value at the location currently pointed by p will be taken
  • ++*p the retrieved value will be incremented
  • when ; is encountered the location will be incremented that is p++ will be executed

Hence, in the while loop initial value pointed by p is 'h', which is changed to 'i' by executing ++*p and pointer moves to point, 'a' which is similarly changed to 'b' and so on. Similarly blank space is converted to '!'. Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches '\0' and p1 points to p thus p1doesnot print anything.
3.#include‹stdio.h›
#define a 10 main() { #define a 50 printf("%d",a); }
Answer:
50
Explanation:
The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.

4.#define clrscr() 100
main()
{
clrscr();
printf("%d\n",clrscr());
}
Answer:
100
Explanation:
Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input program to compiler looks like this :
main()
  {
       100;
       printf("%d\n",100);
  }

5.main()
{
printf("%p",main);
}
Answer:
Some address will be printed.
Explanation:
Function names are just addresses (just like array names are addresses). main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers.


Wednesday, 5 September 2012

C Program Samples 4


1.#include‹stdio.h›
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8}  };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}
Answer:
SomeGarbageValue---1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not.
2.#include‹stdio.h›
main()
{
struct xx
{
      int x=3;
      char name[]="hello";
 };
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}
Answer: 

Compiler Error
Explanation:
You should not initialize variables in declaration.
3.#include‹stdio.h›
main()
{
struct xx
{
int x;
struct yy
{
char s;
 struct xx *p;
};
struct yy *q;
};
}
Answer:
Compiler Error
Explanation:
The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.
4.main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
Answer:
hai
Explanation:
\n - newline
\b - backspace
\r - linefeed
5.main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
Answer:
45545
Explanation:
The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result.
  • #define square(x) x*x
    main()
    {
    int i;
    i = 64/square(4);
    printf("%d",i);
    }
    Answer:
    64
    Explanation:
    the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64





  •  

    Tuesday, 4 September 2012

    C Program Snippets 3


    1.main()
    {
     char string[]="Hello World";
     display(string);
    }
    void display(char *string)
    {
     printf("%s",string);
    }
    Answer:
    Compiler Error : Type mismatch in redeclaration of function display
    Explanation :
    In third line, when the function display is encountered, the compiler doesn't know anything about the function display. It assumes the arguments and return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs.
    2.main()
    {
     int c=- -2;
     printf("c=%d",c);
    }
    Answer:
    c=2;
    Explanation:
    Here unary minus (or negation) operator is used twice. Same maths rules applies, ie. minus * minus= plus.
     3.#define int char
    main()
    {
     int i=65;
     printf("sizeof(i)=%d",sizeof(i));
    }
    Answer:
    sizeof(i)=1
    Explanation:
    Since the #define replaces the string int by the macro char

    4.main()
    {
    int i=10;
    i=!i>14;
    printf("i=%d",i);
    }
    Answer:
    i=0
    Explanation:
    In the expression !i>14 , NOT (!) operator has more precedence than ‘ >’ symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero).
    5.#include‹stdio.h›
    main()
    {
    char s[]={'a','b','c','\n','c','\0'};
    char *p,*str,*str1;
    p=&s[3];
    str=p;
    str1=s;
    printf("%d",++*p + ++*str1-32);
    }
    Answer:
    77
    Explanation:
    p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98.
    Now performing (11 + 98 - 32), we get 77("M");
    So we get the output 77 :: "M" (Ascii is 77).


    Sunday, 2 September 2012

    Automatically create and delete a file in Java



    import java.util.*;
    import java.io.*;
    public class ab extends TimerTask
        {
         static File file;
         public static void main(String[] args ) throws IOException
             {
             file = new File ("test.dat");
             if (! file.exists() )
                 {
                 file.createNewFile();
             }
             System.out.println("File Created");
             ab test = new ab();
             Timer t = new Timer ();
             t.schedule(test, 30*1000L);
             try
                 {
                 while (file.exists())
                     {
                     System.out.print('.');
                     Thread.sleep(1000);
                 }
             }
             catch (InterruptedException ie)
                 {
                 System.out.println("Error");
             }
             System.exit(0);
         } //end of main
         public void run()
             {
             file.delete();
         }
    } //end of public class ab

    C Program Snippets 2


    1.main()
    {
     extern int i;
     i=20;
    printf("%d",i);
    }
    Answer:
    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 .
    2.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);
    }
    Answer:
    0 0 1 3 1
    Explanation :
    Logical operations always give a result of 1 or 0 . And also the logical AND (&&) operator has higher priority over the logical OR (||) operator. So the expression 'i++ && j++ && k++' is executed first. The result of this expression is 0 (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for '0 || 0' combination- for which it gives 0). So the value of m is 1. The values of other variables are also incremented by 1.
    3.main()
    {
     char *p;
     printf("%d %d ",sizeof(*p),sizeof(p));
    }
    Answer:
    1 2
    Explanation:
    The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2.
    4.main()
    {
     int i=3;
     switch(i)
      {
         default:printf("zero");
         case 1: printf("one");
         break;
        case 2:printf("two");
        break;
       case 3: printf("three");
        break;
       }  
    }
    Answer :
    three
    Explanation :
    The default case can be placed anywhere inside the loop. It is executed only when all other cases doesn't match.
    5.main()
    {
       printf("%x",-1<<4);
    }
    Answer:
    fff0
    Explanation :
    -1 is internally represented as all 1's. When left shifted four times the least significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be printed as a hexadecimal value.


    Saturday, 1 September 2012

    C Program Snippet Samples-1


    1. void main()
      {
       int  const * p=5;
       printf("%d",++(*p));
      }
      Answer:
      Compiler error: Cannot modify a constant value.
      Explanation:
      p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".
    2. main()
      {
       char s[ ]="man";
       int i;
       for(i=0;s[ i ];i++)
       printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
      }
      Answer:
      mmmm
      aaaa
      nnnn
      Explanation:
      s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].
    3. main()
      {
       float me = 1.1;
       double you = 1.1;
       if(me==you)
      printf("I love U");
      else
        printf("I hate U");
      }
      Answer:
      I hate U
      Explanation:
      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 (== , >, <, <=, >=,!= ).
      4.main()
       {
       static int var = 5;
       printf("%d ",var--);
       if(var)
        main();
       }
      Answer:
      5 4 3 2 1
      Explanation:
      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.
      5.main()
      {
        int c[ ]={2.8,3.4,4,6.7,5};
        int j,*p=c,*q=c;
        for(j=0;j<5;j++) {
        printf(" %d ",*c);
           ++q;   }
        for(j=0;j<5;j++){
      printf(" %d ",*p);
      ++p;   }
      }
      
      Answer:
      2 2 2 2 2 2 3 4 6 5


    Father of Popular Programming Languages

    C               -Mr.Dennis MacAlistair Ritchie

    C++          -Mr.Bjarne Stroustrup
                       -Without the C programing language though, there would be no C++. So indirectly, Dennis Ritchie & Brian Kernighan (Developers of C in 1972, also at Bell Labs) could be considered parents of the language as well. 

    C#             -Mr.Anders Hejlsberg

    Java          -Dr.James A. Gosling

    Html         -Mr.Tim Berners Lee 

    Php           -Mr.Rasmos Lerdoff

    Javascript -Mr.Brendan Eich

    Perl           -Mr.Larry Wall




    Related Posts Plugin for WordPress, Blogger...