Showing posts with label Typical Programs. Show all posts
Showing posts with label Typical Programs. Show all posts

Friday, 10 January 2014

C Program to Add digits of the number using single statement

Add Digits of the Number Using Single Statement :
#include<stdio.h>
void main()
{
int number=12354;
int sum=0;
for(;number > 0;sum+=number%10,number/=10);
printf("nSum of the Digits : %d",sum);
}
Output :
15
How ?
for(initialization ; conditional ; increment)
{
  //body
}
  • In ‘For Loop‘ Condition is first tested and then body is executed.
  • Carefully Look at Semicolon at the end of ‘For Loop’ , which tells us two Things -
    • For Loop is Bodyless.
    • Only Condition and Increment Statements will be executed.

C Program to Reverse the digits of a number in 3 Steps

C program to reverse the digits of a number ? [ In 3 Steps ]

Problem Statement : Reversing the digits of number without using mod (%) Operator ?

Prerequisite :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

void main()
{
 int num1, num2;
 char str[10];
 clrscr();

    printf("nEnte the Number : ");
    scanf("%d",&num1);

    sprintf(str,"%d",num1);

    strrev(str);

    num2 = atoi(str);

    printf("nReversed Number : ");
    printf("%dn",num2);
    getch();
}
Output :
Enter the Number : 123
Reversed Number : 321

Explain Logic :
Step 1 : Store Number in the Form of String
  • Sprintf function sends formatted output to string variable specified
  • Number will be stored in String variable “str”
sprintf(str,"%d",num1);
Step 2 : Reverse the String Using Strrev Function
  • Strrev will reverse String
  • eg “1234″ will be reversed as “4321″
strrev(str);
Step 3 : Convert String to Number
  • [A to I ] =  [ Alphabet to Integer ] = atoi
  • Atoi function Converts String to Integer
num2 = atoi(str);

C Program to Add reversed number with Original Number

C program to add reversed number with Original Number ?


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

void main()
{
int num1, num2;
char str[10];
clrscr();

printf("nEnte the Number : ");
scanf("%d",&num1);

sprintf(str,"%d",num1);

strrev(str);

num2 = atoi(str);

printf("nReversed Number + Original Number = %d ",num1 + num2 );
getch();
}
Output:
Ente the Number : 123Reversed Number + Original Number = 444

C Program to Demonstrate Printf inside Another Printf Statement

Printf inside printf in C : Example 1

#include<stdio.h>
#include<conio.h>
void main()
{
int num=1342;
clrscr();
printf("%d",printf("%d",printf("%d",num)));
getch();
}

Output :
134241

How ?
  1. Firstly Inner printf is executed which results in printing 1324 
  2. This Printf Returns total number of Digits i.e  4 and second inner printf will looks like
  3. printf("%d",printf("%d",4));
  4. It prints 4 and Returns the total number of digits i.e 1 (4 is single digit number )
  5. printf("%d",1);
  6. It prints simply 1 and output will looks like 132441

Rule :
Inner printf returns Length of string printed on screen to the outer printf

C Program to Demonstrate Nested Printf Statements

nested Printf statements : Example 1

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%d",printf("abcdefghijklmnopqrstuvwxyz"));
getch();
}

Output :
abcdefghijklmnopqrstuvwxyz26

How ?
  1. “abcdefghijklmnopqrstuvwxyz” will be first Printed while executing inner printf
  2. Total Length of the “abcdefghijklmnopqrstuvwxyz” is 26
  3. So printf will return total length of string
  4. It returns 26 to outer printf
  5. This outer printf will print 26

C Program to Print Hello word without using semicolon

Part 1 : Printf Hello word in C without using semicolon [only ones ]

#include<stdio.h>
void main()
{
   if(printf("Hello"))
   {
   }
}

Output :
Hello

Part 2 : Printf Hello word in C without using semicolon [infinite times]

#include<stdio.h>
void main()
{
   while(printf("Hello"))
   {
   }
}

Part 3 : Printf Hello [Using Switch]

#include<stdio.h>
void main()
{
   switch(printf("Hello"))
   {
   }
}

Part 4 : Using Else-if Ladder

#include<stdio.h>
void main()
{
   if(printf(""))
      {
      }
   else if (printf("Hello"))
      {
      }
   else
      {
      }
}

Part 5 : Printf Hello [Using While and Not]

#include<stdio.h>
void main()
{
    while(!printf("Hello"))
    {
    }
}

Part 6 : Using #define

#include<stdio.h>
#define PRINT printf("Hello")
void main()
{
    if(PRINT)
    {
    }
}

C Program to Accept Paragraph using scanf

Accept Paragraph using scanf in C
#include<stdio.h>
void main()
{
char para[100];
printf("Enter Paragraph : ");
scanf("%[^t]",para);
printf("%s",para);
}

Output :[Press Tab to Stop Accepting Characters ]
Enter Paragraph : C Programming is very easy to understand
C
Language
is backbone of
C++
Language

How ?
scanf("%[^t]",para);
  1. Here scanf will accept Characters entered with spaces.
  2. It also accepts the Words , new line characters .
  3. [^t]  represent that all characters are accepted except tab(t) , whenever t will encountered then the process of accepting characters will be terminated.
Drawbacks :
  1. Paragraph Size cannot be estimated at Compile Time
  2. It’s vulnerable to buffer overflows.
How to Specify Maximum Size to Avoid Overflow ?
//------------------------------------
// Accepts only 100 Characters
//------------------------------------
scanf("%100[^t]",para);

C Program to Write inline assembly language code in C Program

Add Two Numbers Using Inline Assembly Language ???
#include<stdio.h>
void main()
{
int a=3,b=3,c;

   asm {
       mov ax,a
       mov bx,a
       add ax,bx
       mov c,ax
      }

printf("%d",c);
}

  1. Assembly Language can be Written in C .
  2. C Supports Assembly as well as Higher Language Features so called “Middle Level Language”.
  3. As shown in above Program , “asm” Keyword is written to indicate that “next followed instruction is from Assembly Language”.
asm mov ax,a
  1. Opening Curly brace after “asm” keyword tells that it is the “Start of Multiple Line Assembly Statements”  i.e “We want to Write Multiple Instructions”
  2. Above Program Without “Opening and Closing Brace” can be written as – ["asm" keyword before every Instruction ]
asm mov ax,a
asm mov bx,a
asm add ax,bx
asm mov c,ax

What above Program Actually Does ?
  1. In 8086 Assembly Program for Storing Values AX,BX,CX,DX registers are used called General Purpose Registers .
asm mov ax,a
  1. Move Instruction Copies content of Variable “a” into Register “AX”
  2. Add Instruction adds Content of two specified Registers and Stores Result in “ax” in above example.
  3. Copy Result into Variable “c”

C Program to Input Password for Validation of User name

How to Input Password in C ?
#include< stdio.h>
#include< conio.h>

void main()
{
char password[25],ch;
int i;

clrscr();
puts("Enter password : ");

while(1)
    {
    if(i<0)
         i=0;
    ch=getch();

    if(ch==13)
        break;

    if(ch==8) /*ASCII value of BACKSPACE*/
        {
        putch('b');
        putch(NULL);
        putch('b');
        i--;
        continue;
        }

   password[i++]=ch;
   ch='*';
   putch(ch);
   }

password[i]='';
printf("nPassword Entered : %s",password);
getch();
}
Output :
Enter password : ******
Password Entered : rakesh

Explain ?
ch=getch();
  • Accept Character without Echo [ without displaying on Screen ]
  • getch will accept character and store it in “ch”
if(ch==13)
        break;
  • ASCII Value of “Enter Key” is 13
  • Stop Accepting Password Characters after “Enter” Key.
if(ch==8) /*ASCII value of BACKSPACE*/
        {
        putch('b');
        putch(NULL);
        putch('b');
        i--;
        continue;
        }
  • ASCII Value of “BACKSPACE” is 8
  • After hitting “backspace”following actions should be carried out -
    • Cursor Should be moved 1 character back.
    • Overwrite that character by “NULL”.
    • After Writing NULL again cursor is moved 1 character ahead so again move cursor 1 character back .
    • Decrement Current Track of Character. [i]
password[i++]=ch;
   ch='*';
  • Store Accepted Character in String array .
  • Instead of Displaying Character , display Asterisk (*)

C Program to Count number of digits in number without using mod operator

Problem Statement : Write a C Program to Find the Number of Digits in an entered number ?

#include<stdio.h>
#include<string.h>
void main()
{
int num,digits;
char ch[10];

printf("nEnter the Number : ");
scanf("%d",&num);

sprintf(ch,"%d",num);

digits = strlen(ch);

printf("nNumber of Digits : %d",digits);

getch();
}

Output:
Enter the Number : 1234
Number of Digits : 4

C Program to Swap two no’s without using third variable

Program to show swap of two no’s without using third variable

#include<stdio.h>
#include<conio.h>

void main()
{
int a,b;

clrscr();

printf("nEnter value for num1 & num2 : ");
scanf("%d %d",&a,&b);

a=a+b;
b=a-b;
a=a-b;

printf("nAfter swapping value of a : %d",a);
printf("nAfter swapping value of b : %d",b);

getch();
}
Output :
Enter value for num1 & num2 : 10 20

After swapping value of a : 20
After swapping value of b : 10

C Program to Implement Calender Program to display Day of the month

Calender Program in C Programming Language : Display Day of the month

Calender Program in C Programming Language :

Program will accept Year,Month and Date from the user and will display the day of the month.
#include<stdio.h>
#include<conio.h>
#include<math.h>

int isdatevalid(int month, int day, int year)
{
  if (day <= 0) return 0 ;
  switch( month )
    {
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12: if (day > 31) return 0 ; else return 1 ;
      case 4:
      case 6:
      case 9:
      case 11: if (day > 30) return 0 ; else return 1 ;
      case 2:
        if ( day > 29 ) return 0 ;
        if ( day < 29 ) return 1 ;

    else return 0 ;
    }
  return 0 ;
}
//------------------------------------------------
int fm(int date, int month,int year)
{
int fmonth,leap;

//leap function 1 for leap & 0 for non-leap

if((year%100==0) && (year%400!=0))
    leap=0;
else if(year%4==0)
    leap=1;
else
    leap=0;

fmonth=3+(2-leap)*((month+2)/(2*month))+(5*month+month/9)/2;
//f(m) formula

fmonth = fmonth % 7; //bring it in range of 0 to 6

return fmonth;
}

//----------------------------------------------
int day_of_week(int date, int month, int year)
{
int dow; //day of week

int YY = year % 100;
int century = year / 100;

printf("nDate: %d/%d/%dnn",date,month,year);

dow = 1.25 *  YY + fm(date,month,year) + date - 2*( century % 4);
//function of weekday for Gregorian

dow = dow % 7; //remainder on division by 7

switch (dow)
    {
    case 0:
        printf("weekday = Saturday");
        break;
    case 1:
        printf("weekday = Sunday");
        break;
    case 2:
        printf("weekday = Monday");
        break;
    case 3:
        printf("weekday = Tuesday");
        break;
    case 4:
        printf("weekday = Wednesday");
        break;
    case 5:
        printf("weekday = Thursday");
        break;
    case 6:
        printf("weekday = Friday");
        break;
    default:
        printf("Incorrect data");
    }
return 0;
}
//------------------------------------------
void main()
{
int date,month,year;
clrscr();

printf("Enter the year ");
scanf("%d",&year);

printf("Enter the month ");
scanf("%d",&month);

printf("Enter the date ");
scanf("%d",&date);

day_of_week(date,month,year);

getch();
}

Output :

Enter the year 2012
Enter the month 02
Enter the date 29

Date: 29/2/2012

weekday = Wednesday

Thursday, 9 January 2014

C Program to Swap two no’s without using third variable

Program to show swap of two no’s without using third variable

#include<stdio.h>
#include<conio.h>

void main()
{
int a,b;

clrscr();

printf("nEnter value for num1 & num2 : ");
scanf("%d %d",&a,&b);

a=a+b;
b=a-b;
a=a-b;

printf("nAfter swapping value of a : %d",a);
printf("nAfter swapping value of b : %d",b);

getch();
}
Output :
Enter value for num1 & num2 : 10 20

After swapping value of a : 20
After swapping value of b : 10

C Program to Implement Calender Program to display Day of the month

Calender Program in C Programming Language : Display Day of the month

Calender Program in C Programming Language :

Program will accept Year,Month and Date from the user and will display the day of the month.
#include<stdio.h>
#include<conio.h>
#include<math.h>

int isdatevalid(int month, int day, int year)
{
  if (day <= 0) return 0 ;
  switch( month )
    {
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12: if (day > 31) return 0 ; else return 1 ;
      case 4:
      case 6:
      case 9:
      case 11: if (day > 30) return 0 ; else return 1 ;
      case 2:
        if ( day > 29 ) return 0 ;
        if ( day < 29 ) return 1 ;

    else return 0 ;
    }
  return 0 ;
}
//------------------------------------------------
int fm(int date, int month,int year)
{
int fmonth,leap;

//leap function 1 for leap & 0 for non-leap

if((year%100==0) && (year%400!=0))
    leap=0;
else if(year%4==0)
    leap=1;
else
    leap=0;

fmonth=3+(2-leap)*((month+2)/(2*month))+(5*month+month/9)/2;
//f(m) formula

fmonth = fmonth % 7; //bring it in range of 0 to 6

return fmonth;
}

//----------------------------------------------
int day_of_week(int date, int month, int year)
{
int dow; //day of week

int YY = year % 100;
int century = year / 100;

printf("nDate: %d/%d/%dnn",date,month,year);

dow = 1.25 *  YY + fm(date,month,year) + date - 2*( century % 4);
//function of weekday for Gregorian

dow = dow % 7; //remainder on division by 7

switch (dow)
    {
    case 0:
        printf("weekday = Saturday");
        break;
    case 1:
        printf("weekday = Sunday");
        break;
    case 2:
        printf("weekday = Monday");
        break;
    case 3:
        printf("weekday = Tuesday");
        break;
    case 4:
        printf("weekday = Wednesday");
        break;
    case 5:
        printf("weekday = Thursday");
        break;
    case 6:
        printf("weekday = Friday");
        break;
    default:
        printf("Incorrect data");
    }
return 0;
}
//------------------------------------------
void main()
{
int date,month,year;
clrscr();

printf("Enter the year ");
scanf("%d",&year);

printf("Enter the month ");
scanf("%d",&month);

printf("Enter the date ");
scanf("%d",&date);

day_of_week(date,month,year);

getch();
}

Output :

Enter the year 2012
Enter the month 02
Enter the date 29

Date: 29/2/2012

weekday = Wednesday