Thursday, 28 July 2011

understanding structure of program,variables and operators in c



A simple c program

/* Purpose: display the message */

#include

int main()

{
printf("%s"," welcome to c programming writting");

return0;
}


Anatomy of a C Program

/*program header comment*/

preprocessor directives (if any)

int main ( ) /*it is the main function, program execution begins from here*/
{
statement(s)
return 0 ;
}

Program Header Comment
 

• A comment is descriptive text used to help a
  reader of the program understand its
  content.
• All comments must begin with the characters
     /* and end with the characters */
• These are called comment delimiters
• The program header comment always
   comes first.


Preprocessor Directives
• Lines that begin with a # in column 1 are
  called preprocessor directives
  (commands).
• Example: the #include directive
  causes the preprocessor to include a copy of
  the standard input/output header file stdio.h at
  this point in the code.
• This header file was included because it
  contains information about the printf ( )
  function that is used in this program.
  When we write our programs, there are
  libraries of functions to help us so that we
  do not have to write the same code over
  and over again.
• Some of the functions are very complex
  and long. Not having to write them
  ourselves make it easier and faster to
  write programs.
• Using the functions will also make it easier
  to learn to program!

int main ( ) or void main()
 

• Every program must have a function called
  main. This is where program execution begins.
• main() is placed in the source code file as the
  first function for readability.
• The reserved word “int” indicates that main()
  returns an integer value.
• The parentheses following the reserved word
  “main” indicate that it is a function.
• The reserved word “void” means nothing is
  there.

The Function Body

• A left brace (curly bracket) -- { -- begins the
  body of every function. A corresponding
  right brace -- } -- ends the function body.
• The style is to place these braces on
  separate lines in column 1 and to indent the
  entire function body 3 to 5 spaces.



printf (“Hello, World!\n”) ;

• This line is a C statement.
• It is a call to the function printf ( ) with a
  single argument (parameter), namely the
  string “Hello, World!\n”.
• Even though a string may contain many
  characters, the string itself should be
  thought of as a single quantity.
• Notice that this line ends with a semicolon.
  All statements in C end with a semicolon.

return 0 ;
 

• Because function main() returns an integer value,
there must be a statement that indicates what this
value is.
• The statement
return 0 ;
indicates that main() returns a value of zero to
the operating system.
• A value of 0 indicates that the program successfully
terminated execution.
• Do not worry about this concept now. Just
remember to use the statement.





Tokens

• The smallest element in the C language is
the token.
• It may be a single character or a sequence
of characters to form a single item.

Tokens are:
• Tokens can be:
– Numeric constants
– Character constants
– String constants
– Keywords
– Names (identifiers)
– Punctuation
– Operators

Numeric Constants

• Numeric constants are an uninterrupted
sequence of digits (and may contain a
period). They never contain a comma.
• Examples:
– 123
– 98.6
– 1000000


Character Constants
 

• One character from a defined character
set.
• Surrounded on the single quotation mark.
• Examples:
– ‘A’
– ‘a’
– ‘$’
– ‘4’

String Constants
• A sequence characters surrounded by
  double quotation marks.
• Considered a single item.
• Examples:
– “Akv”
– “I like ice cream.”
– “123”
– “D-skY”

Keywords
• Sometimes called reserved words.
• Are defined as a part of the C language.
• Can not be used for anything else!
• Examples:
– int
– while
– for

Names


• Sometimes called identifiers.
• Can be of anything length, but on the first 31 are
  significant (too long is as bad as too short).
• Are case sensitive:
– abc is different from ABC
• Must begin with a letter and the rest can be
  letters, digits, and underscores.
• There can be one exception to beginning letter
  that variable name can start with underscore( _ )
  but it is used by C library.

Punctuation
• Semicolons, colons, commas,
apostrophes, quotation marks, braces,
brackets, and parentheses.
• ; : , ‘ “ [ ] { } ( )

Operators
• There are operators for:
– assignments
– mathematical operations
– relational operations
– Boolean operations
– bitwise operations
– shifting values
– calling functions
– subscripting
– obtaining the size of an object
– obtaining the address of an object
– referencing an object through its address


What Are Variables in C?
• Variables in C have the same meaning as
Variables in algebra. That is, they represent
Some unknown, or variable, value.
x = a + b
z + 2 = 3(y - 5)

• Remember that variables in algebra are
  represented by a single alphabetic
  character.

Naming Variables
• Variables in C may be given representations
  containing multiple characters. But there are
  rules for these representations.
• Variable names (identifiers) in C
– May only consist of letters, digits, and
   underscores
– May be as long as you like, but only the first 31
   characters are significant
– May not begin with a digit
– May not be a C reserved word (keyword)


Reserved Words (Keywords) in C
• 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

Naming Conventions

 
• C programmers generally agree on the
following conventions for naming variables.
– Begin variable names with lowercase letters
– Use meaningful identifiers
– Separate “words” within identifiers with
underscores or mixed upper and lower case.
– Examples: surfaceArea surface_Area
surface_area
– Be consistent!
Use all uppercase for symbolic constants
(used in #define preprocessor directives).
• Note: symbolic constants are not variables,
but make the program easier to read.
• Examples:
#define PI 3.14159
#define AGE 52


Case Sensitivity
 

• C is case sensitive
– It matters whether an identifier, such as a
variable name, is uppercase or lowercase.
– Example:
area
Area
AREA
ArEa
are all seen as different variables by the
compiler


Which Are Legal Identifiers?

AREA
area_under_the_curve
3D
num45
Last-Chance
#values
x_yt3
pi
num$
%done
lucky***


Declaring Variables
 

• Before using a variable, you must give the
compiler some information about the variable;
i.e., you must declare it.
• The declaration statement includes the data
type of the variable.
• They must be declared just after the start of
block (i.e. start of a function) and before any
other executable statement.
• Examples of variable declarations:
int meatballs ;
float area ;

• When we declare a variable

– Space is set aside in memory to hold a value of
   the specified data type
– That space is associated with the variable name
– That space is associated with a unique address


 

Notes About Variables
 

• You must not use a variable until you
somehow give it a value.
• You can not assume that the variable will
have a value before you give it one.
– Some compilers do, others do not! This is the
source of many errors that are difficult to find.

Using Variables: Assignment

• Variables may have values assigned to them through
the use of an assignment statement.
• Such a statement uses the assignment operator =
• This operator does not denote equality. It assigns
the value of the right-hand side of the statement (the
expression) to the variable on the left-hand side.
• Examples:       
diameter = 5.9 ;
area = length * width ;
Note that only single variables (LValue) may appear
on the left-hand side of the assignment operator.







Getting Input from User

• Every process requires some input from
the user. Variables hold the input values.
• We have a function called scanf( ) that will
allow us to do that.
• The function scanf needs two pieces of
information to display things.
– The data type of input values
– Address where to store the values• scanf( “%f”, &diameter );



Displaying Variables

• Variables hold values that we occasionally
want to show the person using the
program.
• We have a function called printf( ) that will
allow us to do that.
• The function printf needs two pieces of
information to display things.
– How to display it
– What to display• printf( “%f\n”, &diameter );



Both printf and scanf Returns a Value
• We can call printf as
          i=810;
       n=printf(“%d”,i);
• We also can call a scanf
     m=scanf(“%d%f”,&i,&f)

check out the value of n & m if every thing goes fine?


Good Programming Practices

• Place each variable declaration on its own
   line with a descriptive comment.
• Place a comment before each logical
  “chunk” of code describing what it does.
• Do not place a comment on the same line as
   code (with the exception of variable
   declarations).
• Use spaces around all arithmetic and
   assignment operators.
• Use blank lines to enhance readability.
• Place a blank line between the last
  variable declaration and the first
  executable statement of the program.
• Indent the body of the program 3 to 5
  spaces -- be consistent!
• Comments should explain why you are
   doing something, not what you are doing
   it.
a = a + 1 /* add one to a */           /* WRONG */
              /* count new student */ /* RIGHT*/

Wednesday, 27 July 2011

starting with c



C basics
 

Before we embark on a brief tour of C's basic syntax and structure we offer a brief history of C and consider the characteristics of the C language.
In the remainder of the Chapter we will look at the basic aspects of C programs such as C program structure, the declaration of variables, data types and operators.

History of c
 

C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972.
The milestones in C's development as a language are listed below:
 

• UNIX developed DEC PDP-7 Assembly Language
• BCPL -- a user friendly OS providing powerful development tools 

                developed from BCPL. Assembler tedious long and error prone.
• A new language ``B'' a second attempt. come in 1970.
• A totally new language "C" a successor to ``B''. comes in 1972
• By 1973 UNIX OS almost totally written in ``C''.

Characteristics of C
 

We briefly list some of C's characteristics that define the language and also have lead to its popularity as a programming language. Naturally we will be studying many of these aspects throughout the course.
 

• Small size.
• Extensive use of function calls.
• Loose typing unlike PASCAL.
• Structured language.
• Low level (BitWise) programming readily available.
• Pointer implementation - extensive use of pointers for memory, array, structures and

  functions.
 

C has now become a widely used professional language for various reasons.
 

• It has high-level constructs.
• It can handle low-level activities.
• It produces efficient programs.
It can be compiled on a variety of computers.

What is a Computer Program?

A program is a set of step-by-step
instructions to the computer telling it to
carry out the tasks that you want it to do
to produce the results you want.

What is Programming?

• Programming consists of two distinct
  steps:
• algorithmic design (the problem solving
  stage, analogous to the work of an
  architect designing a building)
• coding (the construction phase)

Levels of Programming Languages

• Machine language
• Assembly Language
• High Level Languages

Machine Language

• Actual binary code that gives basic
  instructions to the computer.
• These are usually simple commands
  like adding two numbers or moving
  data from one memory location to
  another.
• Different for each computer processor

Assembly Language

• A way for humans to program computers
  directly without memorizing strings of binary
  numbers.
• There is a one-to-one correspondence with
  machine code.For example ADD and MOV are mnemonics for
  addition and move operations that can be specified
  in single machine language instructions.
  Different for each computer processor

High-level language
 

• Permits humans to write complex
  programs without going step-by step.
• High-level languages include Pascal,
  FORTRAN, Java, Visual Basic, and
  many more.
• One command in a high-level
  language may translate to tens of
  machine language instructions.

Translation


Computers can only run machine language
programs directly.
Assembly language programs are assembled, or
translated into machine language.
Likewise, programs written in high-level languages,
like Java, must also be translated into machine
language before they can be run. To do this
translation compile a program.



Structured Programming

Structured Programming is a technique for organizing 

and coding computer programs according to the hierarchy of modules is
used, each having a single entry and a single exit point, 

and in which control is passed downward through the structure.

Programming language C
 

• C is a general purpose programming language.
• C is a middle level language.
• C is a structured language

Why C is called “a middle level language”?
 

C contains the features of high level language
portability ,it is easy to adapt software written
for one type of computer to another type. 

the and also the functionality of low level language.
for i.e operators such as &, |,>,< etc. simulate to low level instruction codes.
in term of direct manipulation of bits, bytes and addresse 

Writing C Programs 

• A programmer uses a text editor to create or modify files containing C code. 
• Code is also known as source code. 
• A file containing source code is called a source file. 
• After a C source file has been created, the programmer must 
  invoke the C compiler before the program can be executed (run). 

Invoking the turbo c Compiler 

At the prompt, type tcc pgm.c where pgm.c is the C program source file. 

There is a better way use IDE instead of command for creating programs.

The Result : 

pgm.c
pgm.exe 
•pgm.bak
•pgm.obj

pgm.c- it is the source code file of the program.it is generally present in bin 
             directory of the turbo c compiler.if we save our program to other 
             directory then the .c file will be present in that directory rather than bin 
             directory. 

pgm.exe-If there are no errors in pgm.c, then at the time of execution 
              of program it will produces an executable file, which can be      
              executed when needed.

pgm.bak-When a program is about to overwrite an existing file 
               the program may first make a copy of the existing file, 
               with .bak appended to the filename. 
               This common .bak naming scheme makes it possible 
               to retrieve the original contents of the file.

pgm.obj-the obj file contains the machine level code. 

Although we call this process “compiling a program,” what actually happens is more complicated. 

3 Stages of Compilation Stage 

Stage 1: Preprocessing – Performed by a program called the preprocessor
                                    Modifies the source code (in RAM) according to preprocessor directives (preprocessor commands) embedded in the source code – Strips comments and white space from the code – The source code as stored on disk is not modified. 

Stage 2: Compilation Performed by a program called the compiler
                                  It Translates the preprocessor-modified source code into object code (machine code) then Checks for syntax errors and warnings and Saves the object code to a disk file, if instructed to do so (we will not do this). If any compiler errors are received, no object code file will be generated.but An object code file will be generated if only warnings, not errors, are received. 

Stage 3: Linking Combines the program object code with other object code to 
                           produce the executable file. The other object code can come from the Run- Time Library, other libraries, or object files that you have created. and Saves the executable code to a disk file. On the Linux system, that file is called a.out.If any linker errors are received, no executable file will be generated.





Monday, 25 July 2011

[chapter 4]let us c [SOLVED]



[D]Write a program which to find the grace marks for a student using switch. The user should enter the class obtained by the student and the number of subjects he has failed in.
− If the student gets first class and the number of subjects he failed in is greater than 3, then he does not get any grace. If the number of subjects he failed in is less than or equal to 3 then the grace is of 5 marks per subject.
− If the student gets second class and the number of subjects he failed in is greater than 2, then he does not get any grace. If the number of subjects he failed in is less than or equal to 2 then the grace is of 4 marks per subject.
− If the student gets third class and the number of subjects he failed in is greater than 1, then he does not get any grace. If the number of subjects he failed in is equal to 1 then the grace is of 5 marks per subject

}

click here for Answer!!!

[chapter 3 part 2]let us c [SOLVED]



[E] Attempt the following:
(a)Write a program to print all prime numbers from 1 to 300. (Hint: Use nested loops, break and continue)


click here for Answer!!!



(b)Write a program to fill the entire screen with a smiling face. The smiling face has an ASCII value 1.


click here for Answer!!!


(c)Write a program to add first seven terms of the following series using a for loop: 1/1! + 2/2! + 3/3! + .........

click here for Answer!!!



(d)Write a program to generate all combinations of 1, 2 and 3 using for loop.

click here for Answer!!!


(e) According to a study, the approximate level of intelligence of a person can be calculated using the following formula: i = 2 + ( y + 0.5 x ) Write a program, which will produce a table of values of i, y and x, where y varies from 1 to 6, and, for each value of y, x varies from 5.5 to 12.5 in steps of 0.5.


click here for Answer!!!


(f)Write a program to produce the following output:
       A B C D E F G F E D C B A
       A B C D E F   F E D C B A
       A B C D E       E D C B A
      A B C D           D C B A
       A B C               C B A
       A B                   B A
       A                       A 
click here for Answer!!!


[7]int i=10;
(g)Write a program to fill the entire screen with diamond and heart alternatively. The ASCII value for heart is 3 and that of diamond is 4.

click here for Answer!!!


(h)Write a program to print the multiplication table of the number entered by the user. The table should get displayed in the following form. 29 * 1 = 29 29 * 2 =58 ....


click here for Answer!!!


(i) Write a program to produce the following output:

                1
               2 3
              4 5 6
             7 8 9 10 



click here for Answer!!!


(j)Write a program to produce the following output:
        

                1
               1 1
              1 2 1
             1 3 3 1
            1 4 6 4 1




click here for Answer!!!


(k)A machine is purchased which will produce earning of Rs. 1000 per year while it lasts. The machine costs Rs. 6000 and will have a salvage of Rs. 2000 when it is condemned. If 12 percent per annum can be earned on alternate investments what would be the minimum life of the machine to make it a more attractive investment compared to alternative investment?

click here for Answer!!!


(l) When interest compounds q times per year at an annual rate of r % for n years, the principle p compounds to an amount a as per the following formula
a = p ( 1 + r / q ) ^ nq
Write a program to read 10 sets of p, r, n & q and calculate the corresponding as.



click here for Answer!!!





(m)The natural logarithm can be approximated by the following series.
(x-1)/x + 1/2((x-1)/2)^2 + 1/2((x-1)/2)^3 + ...
If x is input through the keyboard, write a program to calculate the sum of first seven terms of this series.


click here for Answer!!!

[chapter 3 part 1]let us c [SOLVED]


[B] Attempt the following:
(a)Write a program to calculate overtime pay of 10 employees. Overtime is paid at the rate of Rs. 12.00 per hour for every hour worked above 40 hours. Assume that employees do not work for fractional part of an hour.

click here for Answer!!!


(b)Write a program to find the factorial value of any number entered through the keyboard.

click here for Answer!!!


(c)Two numbers are entered through the keyboard. Write a program to find the value of one number raised to the power of another.

click here for Answer!!!


(d)Write a program to print all the ASCII values and their equivalent characters using a while loop. The ASCII values vary from 0 to 255.

click here for Answer!!!


(e)Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number. For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 )

click here for Answer!!!


(f)Write a program for a matchstick game being played between the computer and a user. Your program should ensure that the computer always wins. Rules for the game are as follows: ? There are 21 matchsticks. ? The computer asks the player to pick 1, 2, 3, or 4 matchsticks. ? After the person picks, the computer does its picking. ? Whoever is forced to pick up the last matchstick loses the game.
click here for Answer!!!


(g)Write a program to enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros entered.

click here for Answer!!!


(h)Write a program to find the octal equivalent of the entered number.

click here for Answer!!!



(i)Write a program to find the range of a set of numbers. Range is the difference between the smallest and biggest number in the list.

click here for Answer!!!

Sunday, 24 July 2011

[chapter 2 part 3]let us c [SOLVED]



[J]([k]in 4th edition) Attempt the following:
(a)Using conditional operators determine:
(1) Whether the character entered through the keyboard is a lower case alphabet or not.
(2) Whether a character entered through the keyboard is a special symbol or not.

click here for Answer!!!


(b) Write a program using conditional operators to determine whether a year entered through the keyboard is a leap year or not.

click here for Answer!!!



(c) Write a program to find the greatest of the three numbers entered through the keyboard using conditional operators.

click here for Answer!!!

[chapter 2 part 2]let us c [SOLVED]


[F]([G] in 4th edition ) Attempt the following:
(a) Any year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators && and ||.

click here for Answer!!!



(b) Any character is entered through the keyboard, write a program to determine whether the character entered is a capital letter, a small case letter, a digit or a special symbol. The following table shows the range of ASCII values for various characters.
characters ascii values
A-Z 65 – 90
a-z 97 – 122
0-9 48 – 57
special symbols 0 - 47, 58 - 64, 91 - 96, 123 - 127

click here for Answer!!!


(c) An Insurance company follows following rules to calculate premium.
(1) If a person’s health is excellent and the person is between 25 and 35 years of age and lives in a city and is a male then the premium is Rs. 4 per thousand and his policy amount cannot exceed Rs. 2 lakhs.
(2) If a person satisfies all the above conditions except that the sex is female then the premium is Rs. 3 per thousand and her policy amount cannot exceed Rs. 1 lakh.
(3) If a person’s health is poor and the person is between 25 and 35 years of age and lives in a village and is a male then the premium is Rs. 6 per thousand and his policy cannot exceed Rs. 10,000.
(4) In all other cases the person is not insured.
Write a program to output whether the person should be insured or not, his/her premium rate and maximum amount for which he/she can be insured.



click here for Answer!!!


(d) A certain grade of steel is graded according to the following conditions:
(i) Hardness must be greater than 50
(ii) Carbon content must be less than 0.7
(iii) Tensile strength must be greater than 5600
The grades are as follows:
Grade is 10 if all three conditions are met
Grade is 9 if conditions (i) and (ii) are met
Grade is 8 if conditions (ii) and (iii) are met
Grade is 7 if conditions (i) and (iii) are met
Grade is 6 if only one condition is met
Grade is 5 if none of the conditions are met
Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and output the grade of the steel.


click here for Answer!!!


(e)A library charges a fine for every book returned late. For first 5 days the fine is 50 paise, for 6-10 days fine is one rupee and above 10 days fine is 5 rupees. If you return the book after 30 days your membership will be cancelled. Write a program to accept the number of days the member is late to return the book and display the fine or the appropriate message.

click here for Answer!!!


(f)If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.

click here for Answer!!!


(g)If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.

click here for Answer!!!


(h) In a company, worker efficiency is determined on the basis of the time required for a worker to complete a particular job. If the time taken by the worker is between 2 – 3 hours, then the worker is said to be highly efficient. If the time required by the worker is between 3 – 4 hours, then the worker is ordered to improve speed. If the time taken is between 4 – 5 hours, the worker is given training to improve his speed, and if the time taken by the worker is more than 5 hours, then the worker has to leave the company. If the time taken by the worker is input through the keyboard, find the efficiency of the worker.

click here for Answer!!!


(i) A university has the following rules for a student to qualify for a degree with A as the main subject and B as the subsidiary subject:

(a) He should get 55 percent or more in A and 45 percent or more in B.
(b) If he gets less than 55 percent in A he should get 55 percent or more in B. However, he should get at least 45 percent in A.
(c) If he gets less than 45 percent in B and 65 percent or more in A he is allowed to reappear in an examination in B to qualify.
(d) In all other cases he is declared to have failed.
Write a program to receive marks in A and B and Output whether the student has passed, failed or is allowed to reappear in B.



click here for Answer!!!


(j) The policy followed by a company to process customer orders is given by the following rules:
(a) If a customer order is less than or equal to that in stock and has credit is OK, supply has requirement.
(b) If has credit is not OK do not supply. Send him intimation.
(c) If has credit is Ok but the item in stock is less than has order, supply what is in stock. Intimate to him data the balance will be shipped.

Write a C program to implement the company policy


click here for Answer!!!

[chapter 2 part 1]let us c [SOLVED]


[C]ATTEMPT THE FOLLOWING

(a) If cost price and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss he incurred.


click here for Answer!!!



(b) Any integer is input through the keyboard. Write a program to find out whether it is an odd number or even number.

click here for Answer!!!


(c)Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not.
(Hint: Use the % (modulus) operator)

click here for Answer!!!


(d)According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input through the keyboard write a program to find out what is the day on 1st January of this year.

click here for Answer!!!


(e)A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.


click here for Answer!!!


(f)If the ages of Ram, Shyam and Ajay are input through the keyboard, write a program to determine the youngest of the three.

click here for Answer!!!


(g)Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.

click here for Answer!!!


(h) Find the absolute value of a number entered through the
keyboard.


click here for Answer!!!


(i)Given the length and breadth of a rectangle, write a program to find whether the area of the rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and breadth = 4 is greater than its perimeter.

click here for Answer!!!


(j)Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.

click here for Answer!!!


(k) Given the coordinates (x, y) of a center of a circle and it’s radius, write a program which will determine whether a point lies inside the circle, on the circle or outside the circle. (Hint: Use sqrt( ) and pow( ) functions)


click here for Answer!!!


(l) Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis or at the origin, viz. (0, 0).


click here for Answer!!!