C Program 2 – Electricity Bill calculation

This program is to display the electricity bill calculation based on the number of units consumed every month

Input : the number of units – variable name – unit

Output – Amount of rupee – variable name – amount

Logic:

Units Rupees
1-50 units 0.75/unit
51-100 0.85/unit
101-200 1.50/unit
201-300 2.20/unit
>300 3.00/unit

In all the cases, there will be service charge of Rs.20 will be collected.

#include <stdio.h>
#include <conio.h>
int main()
{
    float amount=0,units;;
    printf("Enter the number of units");
    scanf("%f", &units);
    if(units <=50)
    {
     amount = units * 0.75;       
    }   
    else if(units >50 && units <=100)
    {
         amount=0.75 * 50 + 0.85*(units-50);
    }
    else if(units >100 && units <200)
    {
         amount=(0.75*50) + (0.85*50 )+ (1.5 *(units-100));
    }
    else if(units >200 && units <300)
    {
         amount=(0.75*50) + (0.85*50 )+ (1.5 *100) + (2.20 *(units-200));
    }
    else
    {
         amount=(0.75*50) + (0.85*50 )+ (1.5 *100) + (2.20 * 100) +(3.0*(units-300));
    }
    amount=amount+(0.2*amount);
    printf("The total electricity bill is %f", amount);
    getch();
    return 0;
}

C Program 1 – To find the reversal of a given number

Assume the number 1234, after reversal the number becomes 4321.

Input: One number, Ex 1234, declared to num

Output : One number, Ex 4321, rev is the variable

Logic:

  1. separate each digit using modulo operator from the right and bring that number to front
  2. divide the given number by 10, so the right most digit will be discarded.
  3. run till the number becomes <=0

output the result

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

int main()
{
    int num,rev=0;
    printf("enter the number to be reversed");
    scanf("%d", &num);

    while(num>0) //till the number is positive, perform the process
    {
    rev=rev*10 + (num%10);
//separate each digit and bring it to the first
    num=num/10;
    }
    printf("The reversal is %d ",rev);
    getch();
    return 0;
}

Decision Making and Looping

C supports Decision Making and Looping (Interations)

In decision Making,

if, if-else, if- else if – else, switch – case is used.

if(condition)

{

//These statements are executed only if the condition is true or 1

}

if – else

if(condition)

{

//These statements are executed only if the condition is true or 1

}

else

{

//these statement are executed only if the condition is false or 0

}

(in the above example, there is no else part means that for some situation, there may not be a need for else part)

if – else if – else

if(condition 1)

{

//These statements are executed if the condition 1 is true or 1

}

else if (condition 2)

{

//These statements are executed if the condition 2 is true or 1

}

else

{

//These statements are executed neither condition 1 nor condition 2 are true

// if all the conditions fails, then this statement will execute

}

Switch Case

switch (expression)

{

case 1: statement 1;

break;

case 2: statement 2;

break;

case 3: statement 3;

break;

default: statement d;

break;

}

//Statement n;

The switch case works similar like a multiple if else if statement.

Assume if the expression takes 3 as the value and the statement 3 will be executed and next there is a break statement, so the control comes to statement n and it ill be printed.

so when case 3: is success, then

statement 3;

statement n;

will be printed

Looping

  • while()
  • do .. while();
  • for()

while ()

while(condition)

{

//statement 1

}

statement 1 will keep on execution till the condition becomes false

so this loop is called as entry controlled loop

do while()

do

{

//Statement 1

}while(condition);

in this, whether the condition is true or false, first time the loop will execute and only then it will check for validity of the condition.

so this loop is called as exit controlled loop

for loop

for (initialization: condition; increment/decrement)

{

//Statement

}

More details about the looping will be in subsequent posts.

Data types

Declaration of variable names does two things

  • it tells the compiler what the variable name is
  • specifies what type of data the variable will hold

So it is mandatory that each variable should belong to a particular data type. C supports different data types like integer, character, float, double, etc.

Data type Size on a 16 bit machine Range
char 1 byte or 8 bits -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 255
short int or short 1 byte -128 to 127
int 2 bytes -32768 to 32767
unsigned int 2 bytes 0 to 65535
long int or long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long int 4 bytes 0 to 4,294,967,295
float 4 bytes 3.4E-38 to 3.4 E+38
double 8 bytes 1.7E-308 to 1.7E+308
long double 10 bytes 3.4E-4932 to 1.1E+4932

Example of declaring variables

int a=20,b=20,c;

int a=10;

int b=9;

int c=20;

float c=3.5;

char a =’A’;

long int al or long a;

short int b or short b;

double c;

long double c;

Tokens in C

Tokens are classified as

  • Keywords
  • Identifiers
  • Operators
  • Constants
  • Special Symbols

Keywords

Keywords are reserved by the compilers and keywords will not be redefined (means the keywords are not been declared as variable names, etc). There are standard 32 keywords in C compiler, and some compilers uses more keywords based on their specification. Here is the list of 32 keywords

auto break case char
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while

 

Identifiers

  1. Identifiers are variable names declared inside the program.
  2. They use alphabets, number, symbols like _ and $
  3. They must begin with  alphabet or _
  4. They are case sensitive i.e Var_name is different from var_name

Some valid identifiers are

john Value r_sie x1
x2 Chennai Sum1 abcd

invalid identifiers

123 % (super) 25th
1st ab-d sum of total  

 

Operators

operators are further classified into different categories like

  • Arithmetic operators

+  - for addition   1+3 = 4

-   for subtraction      3 – 2 = 1        

*  for multiplication 4* 2 = 8

/   for Division      4 / 2    = 2

% for modulo  4 % 3 = 1 (when 4 is divided by 3, the remainder is 1)

  • Increment/ Decrement operators

++  increment Ex: a++ or ++a

--  decrement Ex: a—or –a

  • relational Operators

< – less than

> – greater than

<= less than or equal to

>= greater than or equal to

== is equal to

  • logical operators

&&  - Logical AND

||   - Logical OR

!  - Logical NOT

  • bitwise operators

& Bitwise AND

| bitwise OR

^ bitwise XOR

~ one’s complement

<< shift left

>> shift right

  • Conditional Operators

? : Conditional operator

f =(a>b) ?a : b;

if the condition a> b is true then

a is assigned to f and if false then b is assigned to f

the statement can be rewritten as

if(a>b>

{

f=a;

}

else

{

f=b;

}

  • Other Operators

= assignment operator (this is not equality operator, it just assigns the value to some other variable from right to left assignment)

Example: a=b means b is assigned to a

, comma operator (This is to separate the array variables, etc)

sizeof() operator (to find out the various sizes of the entities like int, char, array size, etc)

  • Special symbols

{} This to begin and end any statement, loop in C program

[] This is for specifying the array index (Ex: int a[10];)

()  This is used for functions in C and helpful for grouping arithmetical operations

Constants

  • Constants is an entity will never changes it value during the execution of the program
  • They are different from variables

 

  • Integer constant

Examples are 2, –1, 0, 345, 324, etc

  • float Constant

Examples are 3.0, –2.345, 32.56, 4.65

  • String Constant

“abc”, “Pradeep Kumar”

  • Character constant

‘A’, ‘b’, ‘1’

There are two ways to declare a constant

1st way is to define at the preprocessing level

Example is

#define PI 31.4

2nd way is declare inside the program

const int a=3.14;

const is the keyword to define a constant.

printf() and scanf() Functions

Printf() is a function to print strings to the display unit and

scanf() is to scan the input through the keyboard

the f in the printf and scanf are called as format. That is, printf() and scanf() will print and scan in some particular format, it is the duty of the developer to provide that formats.

For example

printf(“a=%d, b=%d”, a,b); //This function will print a=10, b=20 if the values of a and b are 10 and 20

scanf(“%f”, &a); //this will accept a float number as the specifier is %f which is for float, See the Ampersand symbol which to tell the compiler to store the variable into the address.

Here is the list of format codes or format specifiers

scanf() format codes

Code Meaning
%c read a single character
%d read a decimal integer
%f read a floating point value
%e read a floating point value (even in exponential format)
%g read a floating point value
%h read a decimal, heaxadecimal or octal integer
%o read an octal integer
%s read a string
%u read an unsigned integer
%x read a hexadecimal integer

h for short integers like %hd

l for long integers like "%ld

L for long double like %Lf

printf() format codes

Code Meaning
%c prints a single character
%d print a decimal integer
%e print a floating point value in exponential form
%f print a float point value
%g print a float point value either in f type or e type depending on the value
%i print a signed decimal integer
%o prints an octal integer
%s prints a string
%u print an unsigned integer
%x print a hexadecimal number

 

Backslash Character constants or Escape Characters

There are some characters inside the double quotes for printf() and scanf() which are escaped by the compiler and hence it will the next character after the escape characters

Character What it will do
\n go to the new line
\t horizontal tab
\a alert bell
\f form feed
\r carriage return
\” will print “
\’ will print ‘
\? will print ?
\\ will print \
\v vertical tab
\b backspace

Sample C Program

/* This program is written by T S Pradeep Kumar on 28th Sep 2010

This is to display Hello World to the display unit

*/

#include <stdio.h> //including the standard IO functions like printf(), scanf()

int main()

{

printf(“Hello World \n”);

return 0;

}

  1. stdio.h is the library which contains the printf(), scanf() and other standard IO functions, so before we use any function we need to include in our C program. Most of the compilers will take stdio.h automatically, even if we dont include in our program
  2. int main() {} is the main function
  3. printf(“Hello World\n”); printf() is the function which is printing to the display unit and it is displaying Hello World. Whatever is there inside the double quotes will displayed as it is in the monitor except the format specifiers or format codes (%d, %f, %c)
  4. return 0; is the final statement which returns the integer value 0 (this is just to make the compiler happy)

Here in the above program, you can see there are semi colons ;

Every C statement must end with a semicolon. If a statement is not completed, then there need not be a semicolon.

Introduction to C Programming

Features of C Programming

  • C is a small language having lesser number of keywords than Java or pascal.
  • C is a native language of Unix, Linux. Not only that many of the windows packages, database programs, graphics libraries are written in C program
  • C is portable – it provides standard set of libraries that work on the same way with all machines
  • C is modular, as it supports functions to divide the program in to sub program
  • C is efficient on most machines, because certain constructs are machine dependant.

Structure of a C program

  • Comments
    • the comments are usually ignored by the compiler
    • so this part informs about the author of the program
    • what is the usefulness of this program
    • updation or creation of the program
    • Example: //  - Single line comment
    • /* ----- multi line comments    ….*/
  • Preprocessor Directives
    • before the compiler runs, the preprocessing takes place.
    • the preprocessors are prefix with a symbol #
    • Examples: #include, #define, #ifdef, #pragma, etc.
  • Function prototypes
    • This is to inform the compiler that the following functions are defined in this program.
    • it specifies the name of the function, arguments or parameters and return type and it ends with a semicolon
    • Ex: int sum(int,int);
  • Global Variables
    • Global variables which are declared above all the functions
    • As the name says, they are available to all the functions of that program
    • They are usually stored in the RAM
  • Main Function
    • main is the function which is main to the entire program
    • Every C program should have a main function
    • syntax: int main() { }
    • Earlier, the main program will return nothing, ie void, but now the compilers are instructing us to provide a return type for the main() function
  • User defined functions
    • After the main() function, the user defined functions are defined, as per the function prototype declared in the program
    • The function can be defined above the main function also, in that case there is not need for function prototype
    • Syntax:

int sum(int a, int b)

{

int f;

f=a+b;

return f;

}

Xgraph [dialog.o] error

If you are installing ns2 allinone package in fedora or ubuntu or any other linux, all the packages will be installed successfully. Occasionally the recent releases of linux flavors failed to install xgraph.

Problem:

The possible error you may get is [dialog.o] error,

Solution:

  1. Open the file dialog.c which is available under the folder xgraph-12.1/ (this is in my case)
  2. Find out the function getline() (will be at two places), usually line number 780 and 891 or 889, replace getline() function to newgetline() (at the both the places)
  3. save the file and at the prompt give ./configure
  4. give the command make

If there are no errors, xgraph will work now..