Showing posts with label Special. Show all posts
Showing posts with label Special. Show all posts

Friday, December 31, 2021

Use of #define in C program

Use of #define 

In the C Programming Language, the #define directive allows the definition of macros within your source code.

Macros are a portion of the code which is given some name. Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code.

In the following example, we have used

#define DISPLAY printf

During execution all the DISPLAY word will be replaced with printf first.

Example of #define in C program


#include<stdio.h>
#include<Windows.h>
#define DISPLAY printf

int main()
{
    int i;
    for(i=0; i<3; i++)
    {
      DISPLAY("..... Good Bye 2021 .....");
      Sleep(500);
      system("cls");
      Sleep(500);
    }
    
    for(i=0; i<3; i++)
    {
      DISPLAY("..... WEL COME 2022 .....");
      Sleep(500);
      system("cls");
      Sleep(500);
    }
    return 0;
}

Output of the program

This will blinks three times

 ..... Good Bye 2021 ..... 

and then blinks three times 

..... WEL COME 2022 ..... 



Sunday, March 3, 2019

Program to find execution time.


Program to find execution time.

This program will find total CPU execution time taken by a for loop of a program.

#include<stdio.h>
#include<time.h>
int main() 
{
int i;
float executionTime;
clock_t startTime, endTime;

startTime = clock();
//Get Time value before for loop execution 

for (i = 0; i < 100; i++) {
printf("%d, ", i);
}

endTime = clock();
//Get Time after for loop execution 

executionTime = ((float) (endTime - startTime)) / CLOCKS_PER_SEC;
//calulate total time

printf("\n\nTime taken to execute \"for loop\" 100 times is: %f seconds.", executionTime);
return 0;
}

Output of program

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,

Time taken to execute "for loop" 100 times is: 0.016000 seconds.



Recommended Readings: C Program Practicals / Special C Programs

Monday, December 31, 2018

Preprocessor Directives - Good Bye 2018, Welcome 2019


Example of Preprocessor Directives:

Following program shows example of use of #include and #define in the C program.

#include<stdio.h>
#include<Windows.h>
#define p printf
#define s Sleep

int main()
{
    int i;
    for(i=0; i<5; i++)
    {
p("..... Good Bye 2018 .....");
    s(500);
    system("cls");
    s(500);
    }
    
    for(i=0; i<5; i++)
    {
p("..... WEL COME 2019 .....");
    s(500);
    system("cls");
    s(500);
    }
    return 0;
}

Output of the program:

This program will blink five times 

..... Good Bye 2018 .....

and then blinks five times

..... WEL COME 2019 .....

Visit C Program Practicals Blog for more details.



Sunday, October 7, 2018

Graphical Report - Project Demo


Project Demonstration - Graphical Reports 

This project shows how to generate Graphical Reports of Student's Class Test from "classtest.txt" data file without use of <graphics.h>. 

Assume classtest.txt file contains RollNo and MarksObtained by the students. This program will display horizontal BAR chart of the Marks obtained by the students.

#include<stdio.h>
int main()
{
  FILE *fp;
  int marks, i;
  const char str[80], s[2]=" ";
  char *token;

  fp = fopen("classtest.txt","r");

  if(fp == NULL) { printf("File error.."); exit(0); }

  system("color A1");
  printf("  Class Test Graphical Report(2018)\n");
  printf("=====================================\n");
  printf(" Roll No.| Marks Obtained (Out of 20)\n");
  printf("=====================================\n");

  while(fgets(str,80,fp)!=NULL)
  {
token = strtok(str,s);
printf("     %s   | ", token);
token = strtok(NULL, s);
marks = atoi(token);
for(i=0; i<marks; i++)
  printf("%c", 254);
printf(" %d\n", marks);
  }
  fclose(fp);
  return 0;    
}

Output of Program

Project Demonstration - Graphical Report of Student Class Test

Check more interesting projects here..


Friday, October 5, 2018

Colors in C Project


Using Colors in C Project

Following C code demonstrates how to use Colors in C program without using <graphics.h>.

#include<stdio.h>

int main()
{
  int i;
  printf("\n\n\n");
  for(i=0;i<10;i++)
  {
     system("color B1");
     printf("%c ",254);
  }
  printf("\n\n MAIN MENU \n\n");
  for(i=0;i<10;i++)
  {
      system("color A1");
      printf("%c ",254);
  }
  return 0;    
}

Output of program
Colors in C Program
Adding Colors to C Program

Monday, June 25, 2018

Special Program - What's wrong?


What's wrong with this program?

Check your output...it's not as per your expectation!!!



#include<stdio.h>

void State_Guj_print(){
    printf("State - Gujarat India.\n");
}

void State_Maha_print(){
    printf("State - Maharastra India\n");

}
void State_Madhya-Prad_print(){
    printf("State - Madhya Pradesh India\n");
}

int main()
{
    int num;
    printf("Enter the number [1-3]:\n");
    scanf("%d",&num);
    switch(num)
    {
      case 1:
             State_Guj_print();
             break;
      case 2:
             State_Maha_print();
             break;
      case 3:
             State_Madhya-Prad_print();
             break;
      default:
             printf("Enter only number 1 to 3.\n");
             break;
    }
    return 0;
}
/*
Do share your answer in comments...
*/

Thursday, March 29, 2018

List Files in Directory


Following C Program will display the List of Files present in current directory. This C program is stored in D:\\CProgramPracticals\ directory; hence it will display all files stored in this directory.

Program to Display List of Files in Current Directory

#include <stdio.h>
#include <dirent.h> 
int main()
{
    DIR *my_dir;
    struct dirent *temp_dir;
    my_dir = opendir(".");
    if (my_dir)
    {
        while ((temp_dir = readdir(my_dir)) != NULL)
        {
            printf("%s\n", temp_dir->d_name);            
        }
        closedir(my_dir);
    }
    return 0;
}



Output of Program

.
..
Armstrong-number.c
bell-using-ascii-7.c
bitcoin_profitloss.c
bitcoin_profitloss.exe
blink.c
cprogrampracticals.h
digitsToWords.c
digitsToWords.exe
EMICalulator.c
EMICalulator.exe
leapYear.c
leapYear.exe
LifeInsurancePremiumCalculator.c
LifeInsurancePremiumCalculator.exe
piano.c
ReadIPAddress.c
ReadIPAddress.exe
StockBroker.c
StockClientBill.c
StockClientBill.exe
swap-variable.c
SystemDateTime.c


Saturday, March 24, 2018

Program Execution Time


This JAVA program will help you to find total time taken by FOR loop of the program. You can extend this JAVA program to find total execution time of the program.

Program will display Total time taken in milliseconds. 

Program Execution Time

class TimeTaken 
{
    public static void main(String[] args) 
    {
        long startTime = System.currentTimeMillis();
        long sum = 0;
        for (int i = 0; i < 10000000; i++) 
        {
            sum = sum + i;
        }
        long endTime = System.currentTimeMillis();
        long timetaken = endTime - startTime;

        System.out.println("FOR loop execution time = " + timetaken + " milliseconds.");
    }
}

Output of program

FOR loop execution time = 14 milliseconds.

Tuesday, March 20, 2018

Bitcoin Trading Profit Loss


Bitcoin Trading Profit Loss Calculation.

Following C Program will help you to calculate your Bitcoin Trading  profit or loss.

#include<stdio.h>

int main(){

   float current_btc_price, avg_cost;
   float total_btc, profitloss;

   printf("Enter Your Total Bitcoin: ");
   scanf("%f",&total_btc);

   printf("Enter Current Bitcoin Price: ");
   scanf("%f",&current_btc_price);

   printf("Your Average Bitcoin Purchase Price: ");
   scanf("%f",&avg_cost);

   //profitloss = (current_btc_price - averagecost) x total_btc

   profitloss = (current_btc_price - avg_cost) * total_btc;

   if(profitloss > 0)
printf("Bitcoin Trading Profit is: %0.2f",profitloss);
   else
printf("Bitcoin Trading Loss is: %0.2f",profitloss);

   return 0;
}


Output of program:

Enter Your Total Bitcoin: 2
Enter Current Bitcoin Price: 250000
Your Average Bitcoin Purchase Price: 150000
Bitcoin Trading Profit is: 200000.00


Friday, March 9, 2018

Life Insurance Premium Calculator


Life Insurance Premium Calculator

This practical will calculate monthly, quarterly, half-yearly and yearly life insurance premium based on given sum assured.

Life Insurance Premium is the amount of money that an individual or business must pay for their life insurance policy. This insurance premium is income for the insurance company, and represents a liability of the company to provide coverage for claims being made against the life insurance policy.

#include<stdio.h>
int main()
{
float sum_assured, years, monthly_premium
float quarterly_premium, half_yearly_premium, yearly_premium;

printf("Enter your sum assured:");
scanf("%d", &sum_assured);

printf("Enter life insurance policy term(in years):");
scanf("%d", &years);

printf("Your Monthly Premium    : %8.2f\n", sum_assured/(years*12));
printf("Your Quarterly Premium  : %8.2f\n", sum_assured/(years*4));
printf("Your Half Yearly Premium: %8.2f\n", sum_assured/(years*2));
printf("Your Yearly Premium     : %8.2f\n", sum_assured/(years));
printf("\nNote: Actual premium may vary because of various charges imposed by company.");
return 0;
}

Output of program

Enter your sum assured:250000
Enter life insurance policy term(in years):5
Your Monthly Premium    :  4166.67
Your Quarterly Premium  : 12500.00
Your Half Yearly Premium: 25000.00
Your Yearly Premium     : 50000.00

Note: Actual premium may vary because of various charges imposed by company.
* * * * *



Note: Insurance premiums charged by the insurance companies is determined by many parameter including statistics and mathematical calculations. The premium charged to a client is also depends on statistical data that exists about age, health and life history.

Thursday, March 8, 2018

Stock Broker


Stock Broker Client Billing C Program

This C program is simulation of one of the function of Online Stock Trading Software. Individual stock broker can print a client bill.


A stock broker is a professional generally associated with a brokerage firm or stock market broker dealer, who buys and sells stocks (shares) and other financial instruments (like Mutual Funds, Insurance, FDs, Bonds, etc. ) for both retail and institutional clients.

/* Stock Broker Client Billing C Program. Individual stock broker can print a client bill. */

#include<stdio.h>
#include<time.h>
int main()
{
int stock_quantity, client_id, brokerage = 45; 
float stock_price, total;
char choice, stock_name[20], client_name[20];
time_t t;
time(&t);


printf("Enter Client ID   : ");
scanf("%d",&client_id);

printf("Enter Client Name : ");
scanf("%s", client_name);

printf("Enter Stock Name  : ");
scanf("%s", stock_name);

printf("Enter Stock Quantity : ");
scanf("%d", &stock_quantity);

printf("Enter Stock Price    : ");
scanf("%f", &stock_price);

BACK:

printf("Enter your choice (B for Buy, S for Sell):");
scanf(" %c", &choice);

if(choice!='B' && choice!='S')
{
printf("\n"); goto BACK;
}

total = stock_quantity * stock_price;

printf("Collect Your Bill As Under...\n");

printf("========================================\n");
printf("      STOCK BROKER - CLIENT BILL\n");
printf("      --------------------------\n");
printf("Date and Time :%s",ctime(&t));
printf("Client ID and Name : %d, %s\n",client_id, client_name);
printf("----------------------------------------\n");
printf("Stock Name\t\t : %s \n", stock_name);
printf("Stock Quantity\t\t : %d\n", stock_quantity);
printf("Stock Price\t\t : %0.2f\n", stock_price);
printf("----------------------------------------\n");
printf("Total Stock Transaction Amount = %0.2f\n", total);
if(choice=='B')
printf("You will pay us INR %0.2f.\n", total+brokerage);
if(choice=='S')
printf("We will pay you INR %0.2f.\n", total-brokerage);
printf("========================================");

return 0;
}

Output of program

Enter Client ID   : 121
Enter Client Name : Mr.Patel
Enter Stock Name  : RELIANCE
Enter Stock Quantity : 10
Enter Stock Price    : 1251.75
Enter your choice (B for Buy, S for Sell):
Collect Your Bill As Under...
========================================
      STOCK BROKER - CLIENT BILL
      --------------------------
Date and Time :Thu Mar 08 20:08:48 2018
Client ID and Name : 121, Mr.Patel
----------------------------------------
Stock Name               : RELIANCE
Stock Quantity           : 10
Stock Price              : 1251.75
----------------------------------------
Total Stock Transaction Amount = 12517.50
You will pay us INR 12562.50.
========================================


Tuesday, March 6, 2018

EMI Calculator

This C program will help you to calculate your EMI. EMI means  Equated Monthly Installment. You can also use this C program to calculate monthly loan installment or personal loan estimator. 

#include <stdio.h>
#include <math.h>

int main()
{
    float principal_amount, roi, time, emi;

    printf("Enter your principal amount (INR): ");
    scanf("%f", &principal_amount);

    printf("Enter rate of interest: ");
    scanf("%f",&roi);

    printf("Enter your loan time in years: ");
    scanf("%f",&time);

    roi = roi/(12*100); /*interest for one month*/
    time=time*12; /*time for one month*/

    emi= (principal_amount*roi*pow(1+roi,time))/(pow(1+roi,time)-1);

    printf("Monthly EMI (INR) = %0.2f\n",emi);
   
    return 0;
}

Output of program

Enter your principal amount (INR): 50000
Enter rate of interest: 12
Enter your loan time in years: 5
Monthly EMI (INR) = 1112.22

Monday, January 1, 2018

Program to display IP Address

C Program to display local IP Address.

#include<stdlib.h>
int main()
{
   system("C:\\Windows\\System32\\ipconfig");
   return 0;
}

Output of program

Program to display IP Address

Note: 
This program tested on Windows 7 OS.
Some of the details are intentionally removed for security reasons.

Sunday, December 31, 2017

Windows Message Box using C Program

C program to print message in Windows Message Box.


#include <windows.h>
int _stdcall WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow )
{
MessageBox ( 0, "Greetings!!!\n C Program Practicals", "MyWindow", 0 ) ;
return 0 ;
}

Output of program

This program will display following message in Windows message box.

Windows Message Box
Windows Message Box using C Program

Program of System Date and Time

C program to read System Date and Time.
#include <stdio.h>
#include <time.h>

int main()
{
   time_t t;
   time(&t);
      printf("System date and time is: %s",ctime(&t));
   getch();
   return 0;
}

Output of program

System date and time is: Sun Dec 31 15:49:15 2017

Saturday, May 13, 2017

C program without Semicolon




C program without Semicolon.

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

Output of program

Hello World

Note: Here printf( ) function is passed as a parameter to if statement; hence semi-colon is not needed at the end of printf() statement.


Wednesday, May 10, 2017

Importing content from other file to c program.



Importing content from other file to c program.

#include<stdio.h>
#include "kp.c"
int main()
{
char state_name[20];
p("Enter your state name:");
s("%s",state_name);

p("Your state name is %s", state_name);

return 0;
}

Output of program

Enter your state name:Gujarat
Your state name is Gujarat

Note:

kp.c file is stored in the same directory where above program is stored. Content of kp.c file is given below.

#define p printf
#define s scanf

Sunday, May 7, 2017

Convert given string to integer



C Program to convert given string to integer using atoi function.

Arithmetic operation is not possible on a String. Before performing any arithmetic operation we need to convert given string into integer. This conversion is possible in C using atoi function.

Note: atoi function is defined inside stdlib.h header file. Function atoi converts the string parameter to an integer.

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

int main(){
    char str[20];
    int number;
    printf("Enter your String:");
    gets(str);

    number = atoi(str);
   
    printf("Integer: %d \n\n", number);
    printf("Proof => Arithmetic operation on number:\n");
   
    printf("Adding same number %d + %d = %d",number, number, number + number);
   
    return 0;
}

Output of program

Enter your String:123
Integer: 123

Proof => Arithmetic operation on number:
Adding same number 123 + 123 = 246