Monday, August 26, 2019

WAP to display pyramids of numbers.

//To print:
          1
       2   2
   3    3    3
4    4    4    4

#include<stdio.h>
void main()
{
    int i,j,k,n,t=1;
    printf("Enter any number:");
    scanf("%d", &n);
    for(i=1 ; i<=n ; i++)
    {
         for(j=1 ;j<=n-i ; j++)
         {
               printf("\t");
         }
         for(k=1 ; k<=2*i-1 ; k++)
         {
              if(k%2!=0)
              {
                  printf("%d",t);
               }
              else
              {
                  printf("\t");
               }
          }
          printf("\n");
          t=t+1;
     }
     getch();
}

Output:
Enter any number:4
          1
       2    2
    3    3    3
4    4    4    4

WAP to display triangle of 1 and 0.

//Program to display:
1
1  0
1  0  1
1  0  1  0
1  0  1  0  1

#include<stdio.h>
void main()
{
    clrscr();
    int i,j,n,k=0,t=1;
    printf("Enter any number:");
    scanf("%d",&n);
    for( i=1; i<=n ; i++)
    {
         for(j=1 ; j<=i ; j++)
         {
              if(j%2 != 0)
                  printf("%d", t);
              else
                  printf("%d", k);
          }
          printf("\n");
    }
    getch();
}

Output:
Enter any number:5
1
1  0
1  0  1
1  0  1  0
1  0  1  0  1

   

WAP ton display Floyd's Triangle.

//Program
1
2  3
4  5  6
7  8   9  10

#include<stdio.h>
void main()
{
    clrscr();
    int i,j,n,a;
    a=1;
    printf("Enter any number:");
    scanf("%d", &n);
    for( i=1 ; i<=n ; i++)
    {
         for( j=1 ; j<=i ; j++)
         {
              printf("%d",a);
              printf("  ");
              a=a+1;
         }
         printf("\n");
    }
    getch();
}

Output:
Enter any number:4
1
2  3
4  5  6
7  8  9  10
    

WAP to display triangle.

//Program to display
A
A  B
A  B  C
A  B  C  D

#include<stdio.h>
void main()
{
    char s;
    int a=65, n, i, j;
    clrscr();
    printf(" Enter any number:");
    scanf("%d", &n);
    for( i=0; i< n ; i++ )\
    {
         for( j=0; j<=i ; j++)
         {
              s=a+j;
              printf("%c",s,"\t");
          }
         printf("\n");
    }
getch();
}

Output:
Enter any number:4
A
A  B 
A  B  C
A  B  C  D

WAP to convert a given number of days into years, weeks, days.

//Program
#include<stdio.h>
void main()

    clrscr();
    int tdays, years, weeks, days, num1;
    prinf("Enter total number of days:");
    scanf("%d",&tdays);
    years = tdays / 365;
    num1 = tdays % 365;
    weeks = num1 / 7;
    days = num1 % 7;
    printf("\n Years = %d ", years);
    printf("\n Weeks =%d ", weeks);
    printf('\n Days=%d ", days);
    getch( );
}

Output:
Enter total number of days:365
Year = 1
Weeks = 52
Days = 365

Tokens or Lexical units in C Programming.

Tokens:


The smallest individual unit in a program is known as a Token or a lexical unit.
Tokens are the basic building blocks of C language which are constructed together to write a C program.
C has the following tokens:
                                  

                    Image result for tokens in c


Keywords:

Keywords are the words that convey a special meaning to the language compiler.These are reserved for special purpose and must not be used as normal identifier names.
Example: new,float,int,char,void,main,etc.

Identifiers:

An identifier is an arbitrarily long sequence of letters and digits.The first character must be a letter; the underscore( _ ) counts as a letter. Upper and lower-case letters are different. All characters are significant.
Example: Some valid identifiers are:
                Myfile, _Ds, File13,etc.

                The following are some invalid identifiers:
                 break   -     reserved keyword
                 29Clct   -    starting with a digit
                 My.file   -    contains special character

Literals ( or Constants):

Literals (often referred to as constants) are data items that never change their values during a program run.

C allows several kind of literals:
1. integer constant
2. floating constant
3. character constant

1. Integer Constants:

An integer constants are whole numbers without any fractional part. It must have at one digit and must not contain any decimal point. It may contain either + or - sign. A number with no sign is assumed to be positive. Commas cannot appear in an integer constant.

 C allows three types of integer constants:
1. Decimal ( base 10 ) : An integer constant consisting of a sequence of digits but it does not begin with digit 0 ( zero ).
For example: 1234,34,etc.
2. Octal ( base 8 ) : It is a constant in which the integer constant begins with digit 0 ( zero ).
For example: 9(in decimal) can be written as 011 (in octal).
3. Hexadecimal ( base 16 ) : It is a constant in which the integer begins with ox or OX.
For example: 11(in decimal) can be written as OXB (in hexadecimal).

2. Character Constants:

An character constants must contain one character and must be enclosed in single quotation marks.
For example: 'C' or 'a'.

C allows you to have certain nongraphic characters in character constants. Nongraphic characters are those characters that cannot be typed directly from keywords e.g., backspace, tabs, carriage return etc.These nongraphic characters can be represented by using escape sequences. 
An escape sequence is represented by a backslash (\) followed by one or more characters. It represents a single character and hence consumes one byte in ASCII representation.
For example: '\b' is used for Backspace, '\n' is used for newline, '\t' is used for horizontal tab, etc.

3. Floating Constants:

Floating constants are also called real constants.
A real constants in fractional form must have at least one digit before a decimal point and at least one digit after the decimal point. It may also have either + or - sign preceding it. A real constant with no sign is assumed to be positive.
For example: 2.0, 17.5, -23.0, -0.00325, etc.
A real constant in exponent form has two types: a mantissa and an exponent. The mantissa must be either an integer or a proper real constant. The mantissa is followed by a letter E or e and the exponent. The exponent must be an integer.
For example: 152E05, 1.52E07, 152E+8, -0.172E-3, etc.

String:


A string literal is a sequence of characters surrounded by double quotes.
For example: "abc", "\ab", etc.

Punctuators (or special symbols):

The following characters are used as punctuators ( also known as separators):      
               [    ]    (   )    {   }   ,   :   ;    *    ....   =   #

Operators:

Operators are tokens that trigger some computation when applied to variables and other objects in an expression. Unary operators are those operators that require one operator to operate upon.
For example: & (Address operator), + (Unary plus), - (Unary minus), ++ (Incremental operator), -- (Decremental operator), etc.
Binary operators are those operators that require two operands to operate upon.
For example: Arithmetic operators ( + , - . * , / , % )
                      Shift operators (<< , >>)
                      Bitwise operators ( & , ^ , | )
                      Logical operators ( && , || )
                      Relational operators (< ,<= ,> ,>= ,== ,!=)
                      Conditional operators (?, :)

The order of precedence for operators is as follows:
             
Image result for order of precedence in c


















Friday, August 16, 2019

WAP to check whether the year is leap or not.

// Program
//The year which is divisible by 400,100 and 4 is called leap year.

#include<stdio.h>
void main()
{
     int a,year;
     printf("Enter any year:");
     scanf("%d",&year);
     if((year%400)==0)
     {
            printf("Leap year");
      }
     else if((year%100)==0)
     {
            printf("Leap year");
      }
     else if((year%4)==0)
     {
            printf("Leap year");
     }
     else
            printf("Not leap year");
     getch();
}

Sample Input/Output:

Enter any year:2004
Leap year

WAP to swap two numbers using third variable.

//Program

#include<stdio.h>
void main()
{
      int a,b,temp;
      clrscr();
      printf("Enter any two numbers:");
      scanf("%d %d",&a,&b);
      prinft("Before swapping of numbers: a=%d and b=%d",a,b);
      temp=a;
      a=b;
      b=temp;
      printf("After swapping of numbers: a=%d and b=%d",a,b);
      getch();
}


Sample Input/Output:

Enter any two numbers:10
20
Before swapping of numbers a=10 and b=20
After swapping of numbers a=20 and b=10

WAP to check whether the given number is palindrome or not.

// Program

#include<stdio.h>
void main()
{
     int a,n,r,d;
     r=0;
     clrscr();
     printf("Enter any number:");
     scanf("%d",&n);
     while(n)
     {
          a=n;
          while(a>0)
          {
               d=a%10;
               r=(r*10)+d;
               a=a/10;
           }
      if(r==n)
           printf("The number is palindrome");
     else
           printf("The number is not palindrome");
     }
     getch();
}

Sample Input/Output:

Enter any number:1221
The number is palindrome

WAP to find a reverse of number.

// Program

#include<stdio.h>
void main()
{
    int a,b,n;
    clrscr();
    printf("Enter any number:");
    scanf("%d",&n);
    b=0;
    while(n!=0)
    {
          a=n%10;
          b=(b*10)+a;
          n=n/10;
     }
    printf("Reverse of a number=%d",b);
    getch();
}

Sample Input/Output:

Enter any number:1234
Reverse of a number=4321

WAP to find the sum of digits of entered number.

//Program

#include<stdio.h>
void main()
{
     int n,i,r;
     int s=0;
     clrscr();
     printf("Enter any number:");
     scanf("%d",&n);
     while(n!=0)
     {
          r=n%10;
          s=s+r;
          n=n/10;
     }
     printf("Sum of digits=%d",s);
     getch();
}

Sample Input/Output:

Enter any number:1234
Sum of digits=10

WAP to check whether the entered character is vowel or not using switch case statement.

// C program

#include<stdio.h>
void main()
{
     char ch;
     clrscr();
     printf("Enter any character:");
     scanf("%c",&ch);
     switch(ch)
     {
          case 'a' || 'A':
          case 'e' || 'E':
          case 'i' || 'I':
          case 'o' || 'O':
          case 'u' || 'U':
                                printf("The character is a vowel");
                                break;
          default: printf("The character is not vowel");
                       break;
      }
      getch();
}

Sample Input/Output:

Enter any character: A
The character is a vowel

WAP to find factorial of a number.

// C program 

#include<stdio.h>
void main()
{
     int a,f=1;
     clrscr();
     printf("Enter a number:");
     scanf("%d",&a);
     for(int i=1,i<=a;++i);
     {
              f=f*i;
      }
      printf("Factorial of a number is %d",f);
      getch();
}

Sample Input/Output:

Enter a number: 5
Factorial of a number is 120
     

WAP to find the largest of three number's.

// C program

#include<stdio.h>
void main()
{
    int a,b,c;
    clrscr();
    printf("Enter any three numbers:");
    scanf("%d %d %d",&a,&b,&c);
    if((a>b)&&(a>c))
        printf("%d",a," is a largest number");
   elseif((b>a)&&(b>c))
        printf("%d",b," is a largest number");
   else
        printf("%d",c," is a largest number");
  getch();
}

Sample Input/Output:

Enter any three numbers:10
20
30
30 is a largest number

WAP for finding a number is even or odd

// C program

#include<stdio.h>
void main()
{
    int n;
    clrscr();
    printf("Enter the number:");
    scanf("%d",&n);
    if ((n%2)==0)
         printf("\n The number is even.");
    else
         printf("\nThe number is odd.");
    getch();
}

Sample Input/Output:

Enter the number:8
The number is even.

WAP for calculation of perimeter and area of a rectangle.

// C program

#include<stdio.h>
int main()
{
    int l,b,a,p;
    printf("Enter the value of length and breadth:");
    scanf("%d %d",&l,&b);
    p=2*(l+b);
    a=l*b;
    printf("\nThe perimeter of a rectangle=%d",p);
    printf("\nThe area of a rectangle=%d",a);
    return 0;
}

Sample Input/Output:

Enter the value of length and breadth:10
5

The perimeter of a rectangle=30
The area of a rectangle=50

 
    

WAP for addition,subtraction,multiplication and division of two numbers.

// C program to add,subtract,multiply and divide.

#include<stdio.h>
int main()
{
    int a,b;
    printf("Enter two numbers:");
    scanf("%d",&a);
    scanf("%d",&b);
    printf("Addition=%d",a+b);
    printf("\nSubtraction=%d",a-b);
    printf("\nMultiplication=%d",a*b);
    printf("\nDivision=%d",a/b);
    return 0;
}

Sample Input/Output:

Enter two numbers:20
20
Addition=40
Subtraction=0
Multiplication=400
Division=1

Errors in C programming

Errors in C:

Errors are the mistakes which are created by the programmer. It is also known as bugs.It is abnormal condition whenever it occurs the execution of program is stopped.

Basically, there are five types of errors in c programming:
1. Runtime error
2. Compile error
3. Semantic error
4. Logical error
5. Linker error

Runtime Errors:

Those errors that occur during the execution of  a c program and generally occur due to some illegal operation performed in the program.
For example: Divide any number by zero, Lack of free memory space, etc.
These type of error are hard to find as the compiler doesn't point the line at which the error occurs.

// C program to illustrate run-time error
#include<stdio.h>
void main()
{
   int n=9,d;
   d=n/0;
   printf("d=%d",d);
}

Error:
 warning: division by zero
                 d=n/0;

Compile Errors:

Errors that are generated at the time of compilation is known as compile time error, in general these are raised while break down the rules and regulations of programming language.
For example: Missing semicolon, writing keywords in upper case, writing variable declaration,etc.
It is also known as syntax error.

//C program to illustrate compile error
#include<stdio.h>
void main()
{
    int a=10;
    printf("%d",a)     //semicolon missed
}

Error:
   error: expected ';' before '}' token.

Semantic Errors:

This error occurs when the statements written in the program are not meaningful to the compiler.
For example:
//C program to illustrate semantic error
#include<stdio.h>
void main()
{
    int a,b,c;
    a+b=c;               //semantic error
 }


Error:
    error: lvalue required as left operand of assignment
    a+b=c;   //semantic error

Logical Errors:

The type of errors which provide incorrect output but appears to be error free are called logical errors.It occur when a program does not do what the programmer experts it to do.
For example:
// C program to illustrate logical error
#include<stdio.h>
void main()
{
      int i;
      int f=1;
      for(i=1;i<=5;++i)
          f=f+i;              //Logical error. Correct statement: f=f*i;
}

Error:
The output which we were expecting will not be shown.

Linker Errors:

Errors that occurs when we do not include header files for the predefined functions used in a program and when we misspell a standard c function. 
For example:
// C program to illustrate linker error
#include<stdio.h>
int Main()                //Linker error as 'main' is misspell as 'Main'
{
    printf("Hello World!");
    return(0);
}


Compilation process in C

Compiler:

A compiler is a computer program that converts high-level programming language code, or source code, into machine code, which consists of binary or hexadecimal instructions that a computer can respond to directly.
gcc is a C compiler that we will be using today.

Compilation process:

There are four main stages that our program has to go through to become an executable file:
1. Preprocessor
2. Compiler
3. Assembler
4. Linker

Let us consider the below program hello.c that we'll be using to demonstrate C compilation:

#include<stdio.h>
/** 
* prints " Hello world"
*/
int main(void)
{
    printf("Hello Worlds!");
return(0);
}

Flowchart showing the compilation process in C :

                                              Image result for stages of compilation in c


Stage 1: Preprocessor

The first stage of compilation is called preprocessing. In this stage, lines starting with a # character are interpreted by the preprocessor as preprocessor commands. These commands form a simple macro language with its own syntax and semantics. This language is used to reduce repetition in source code by providing functionality to inline files, define macros, and to conditionally omit code.
Before interpreting commands, the preprocessor does some initial processing. This includes joining continued lines (lines ending with a \) and stripping comments.

To print the result of the preprocessing stage, pass the -E option to cc:
            cc -E hello.c

Stage 2: Compiler

The second stage of compilation is confusingly enough called compilation. In this stage, the preprocessed code is translated to assembly instructions specific to the target processor architecture. These form an intermediate human readable language.
The existence of this step allows for C code to contain inline assembly instructions and for different assemblers to be used.
Some compilers also supports the use of an integrated assembler, in which the compilation stage generates machine code directly, avoiding the overhead of generating the intermediate assembly instructions and invoking the assembler.

To save the result of the compilation stage, pass the -S option to cc:
           cc -S hello.c

Stage 3: Assembler

During this stage, an assembler is used to translate the assembly instructions to object code. The output consists of actual instructions to be run by the target processor.

To save the result of the assembly stage, pass the -c option to cc:
            cc -c hello.c

Running the above command will create a file named hello.o, containing the object code of the program. 

Stage 4: Linker

The object code generated in the assembly stage is composed of machine instructions that the processor understands but some pieces of the program are out of order or missing. To produce an executable program, the existing pieces have to be rearranged and the missing ones filled in. This process is called linking.

The linker will arrange the pieces of object code so that functions in some pieces can successfully call functions in other ones. It will also add pieces containing the instructions for library functions used by the program. In the case of the “Hello World!” program, the linker will add the object code for the puts function.

The result of this stage is the final executable program. When run without options, cc will name this file hello.out.



Write a program to find gcd of two numbers using recursion.

About:  The process in which a function calls itself is called recursion and the corresponding function is called as recursive function. ...