CP Unit 2
CP Unit 2
CP Unit 2
com
COMPUTER PROGRAMMING UNIT-2
UNIT-2
Program development steps:
C language:
C is case-sensitive language.
C is a structured programming language.
C is mother language.
Overview of “C”:
‗C‘ seems a strange name for programming language. For this strange sounding
language is one of the most popular words today.
‗C‘ was an off string of the ―Basic Command Programming Language (BCPL)‖ called
‗B‘, developed in the 1960 at Cambridge University. ‗B‘ language was modified by
Dennis ritchi and was implemented at bell laboratories in 1972. A new language was
named ‗C‘.
Since it was developed along with be UNIX OS, it is strongly associated with UNIX.
This OS, which was also developed at bell laboratory, was coded almost entirely in
‗C‘.
Advantages of C languages:
‗C‘ is portable, means you say program write in one computer may run on another
computer successfully.
‗C‘ is fast, means that the executable program obtained after compiling linking runs
very fast.
‗C‘ is compact, means that the statements written in ‗C‘ language or generally sharp
written on very powerful.
‗C‘ language is both simplicity of high level language, low level language, and middle
level language.
Structure of C:
Fig: Structure of C
Character set:
Character set is a set of alphabets, letters and some special characters that are valid in
C language.
Alphabets:
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
Digits:
0123456789
Special Characters:
, < > . _
( ) ; $ :
% [ ] # ?
‗ & { } ―
^ ! * / |
- / ~ +
White space Characters, blank space, new line, horizontal tab, carriage return and form feed
Keywords:
Keywords are predefined; reserved words used in programming that have special
meaning. Keywords are part of the syntax and they cannot be used as an identifier. For
example:
int money;
Here, int is a keyword that indicates 'money' is a variable of type integer.
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of
all keywords allowed in ANSI C.
Along with these keywords, C supports other numerous keywords depending upon the
compiler. All these keywords, their syntax and application will be discussed in their
respective topics
Identifiers:
Identifiers are the names you can give to entities such as variables, functions,
structures etc. identifier names must be unique. They are created to give unique name to a C
entity to identify it during the execution of a program. For example:
int money;
double balance;
Here, money and balance are identifiers.
Also remember, identifier names must be different from keywords. You cannot use int as an
identifier because int is a keyword.
Like all C language functions, first comes the function‘s name, main, then comes a set of
parentheses, and finally comes a set of braces, also called curly braces.
If your C program contains only this line of code, you can run it. It won‘t do anything,
but that‘s perfect because the program doesn‘t tell the computer to do anything. Even so, the
operating system found the main() function and was able to pass control to that function
which did nothing but immediately return control right back to the operating system. It‘s a
perfect, flawless program.
The set of parentheses after a C language function name is used to contain any
arguments for the function — stuff for the function to digest. For example, in
thesqrt() function, the parentheses hug a value; the function then discovers the square root of
that value.
The main ( ) function uses its parentheses to contain any information typed after the
program name at the command prompt. This is useful for more advanced programming.
Beginning programmers should keep in mind what those parentheses are there for, but you
should first build up your understanding of C before you dive into that quagmire.
The braces are used for organization. They contain programming instructions that
belong to the function. Those programming instructions are how the function carries out its
task or does its thing.
By not specifying any contents, as was done for the main() function earlier, you have
created what the C Lords call a dummy function — which is kind of appropriate, given that
you‘re reading this at Dummies.com.
Syntax:
The syntax for the printf function in the C Language is:
printf(―Control_String‖ , list_of_variables);
Ex:- printf(―Hello‖);
Escape sequence:
The \n (pronounced backslash n) in the string argument of the function printf().
printf(―Welcome\nComputer‖);
is an example of escape sequence.
It is used print the new line character. If the program is executed, the \n does not
appear in the output. Each \n in the string argument of a prinf() causes the cursor to be placed
at the beginning of the next line of output.
Sno Code meaning
1 \a Ring terminal bell (a is for alert)
2 \? Question mark
3 \b Backspace
4 \r Carriage return
5 \f Form feed
6 \t Horizontal tab
7 \v Vertical tab
8 \o ASCII null character
9 \\ Back slash
10 \‖ Double quote
11 \‘ Single quote
12 \n New line
13 \o Octal constant
14 \x Hexadecimal constant
Format Modifiers:
Describes the output as well as provides a placeholder to insert the formatted string.
Here are a few examples:
COMMENT:
A "comment" is a sequence of characters beginning with a forward slash/asterisk
combination (/*) that is treated as a single white-space character by the compiler and is
otherwise ignored. A comment can include any combination of characters from the represent
able character set, including newline characters, but excluding the "end comment" delimiter
(*/). Comments can occupy more than one line but cannot be nested.
Comments can appear anywhere a white-space character is allowed. Since the
compiler treats a comment as a single white-space character, you cannot include comments
within tokens. The compiler ignores the characters in the comment.
Use comments to document your code. This example is a comment accepted by the compiler:
/* Comments can contain keywords such as
for and while without generating errors. */
Data types of C:
Data types in c refer to an extensive system used for declaring variables or functions
of different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.
1. Type definition:
The users can define and identifies that represents an existing data types the users as type definition.
Ex: typedef int sno;
sno c1,c2;
OPERATORS:
An operator is a symbol which represents a particular operation that can be performed
on data.
The data itself (which can be either a variable or constant) is called operand.
Expressions made by combining operators and operands.
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Unary operators
5. Bitwise operators
6. Logical/Boolean operators
7. Conditional operators
8. Special operators
1. Arithmetic operations:
The arithmetic operators in ‗C‘ language are + (addition), - (subtraction), * (multiplication),
/ (division), % (modulus) these operators are called arithmetic/binary operators. Each
operand can be int, float, char.
Ex: x+y, x-y, x*y, x/y, x%y.
2. Assignment operators:
These are used to assign the result of the expression to a variable, assignment operator is ‗=‘
Syntax: V op= Exp
V- variable
op-arithmetic operator
Exp-Expression
+= add assignment
-= minus assignment
*= multiply assignment
/= divide assignment
%= Modulus assignment
3. Relational operators:
The relational operators are used to test or compare the values between two operands. The relational
or equality operators produce an integer value to express the condition of the comparison. If the condition is
false then the integer result is ‗0‘. Otherwise, the integer result is nonzero.
4. Unary operators:
The unary ‗++‘ and ‗- -‗operators increment or decrement the value in a variable by 1. There are ‗pre‘
and ‗post‘ variants for both operators that do slightly different things as explained below.
5. Bitwise operators:
A smallest element in the memory on which they are able to operator is a bit, C suppose several
bitwise operators.
& Bitwise AND
| Bitwise OR
>> Bitwise Right Shift
<< Bitwise Left Shift
^ Bitwise Exclusive OR
~ Bitwise Negation
6. Logical/Boolean operators:
These operators are used to compare two or more operands. The logical operator is also called unary
operators.
! Logical NOT
&& Logical AND
|| Logical OR
Example Result
! (5= =5) 0
(5<6) && (6<5) 0
(5<6) | | (6<5) 1
7. Conditional operators:
The conditional operator ? and : are sometimes called ternary operator since it operands on three
operands, and it is consider has IF-THEN-ELSE in C statement.
#include<stdio.h>
main ( )
{
int a=7,b=8;
printf ( (a<b) ? "a is big" : "b is big" );
}
8. Special operators:
Some commonly used special operators are comma operator ( , ), sizeof operator, address operator
(&) and value of address operator (*).
i) Comma operator:
The operator permits two different expressions, appears in a situation where only one expression
put ordinary be use. The expressions are separated by comma operator.
Ex: int a, b;
int c = ( a=10, b=20, a+b);
Ex:
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Variable:
A variable is an identifier for a memory location in which data can be stored and subsequently
recalled. All the variables have two important attributes.
A data type that is established when the variable is defined, e.g., integer, real, character. Once defined,
the type of a C variable cannot be changed.
A value can be changed by assigning a new value to the variable. The kind of values a variable can
assume depends on its type. For e.g., an integer variable can only take integer values, e.g., 2, 100, -12, -14, 0, 4.
Declaration of variables:
Any programming language any variable used in the program must be declared before it is used.
This declaration tells the compiler what the variable name and what type of data it is.
In C language a declaration of variable should be done in the declaration part of the program. A type
declaration statement is usually written at the beginning of the program.
Syntax: <data_type> <var1>,<var2>,<var3>,………,<var n>;
Ex: int i, count;
float price, area;
char c;
Assigning values:
Values can be assigned to variables by using the assignment operator. An assignment statement
employees that the value of the variable on the left of the equal to the value of quantity on the right.
Syntax: <data_type> variable_name = constant;
Ex: int i = 20;
Declaration of statements:
In computer programming, a declaration specifies properties of an identifier: it
declares what a word (identifier) means. Declarations are most commonly used
for functions, variables, constants and classes, but can also be used for other entities such as
enumerations and type definitions.
Here are some examples of declarations that are not definitions, in C:
Expression:
An expression is a combination of variables constants and operators written according
to the syntax of C language. In C every expression evaluates to a value i.e., every expression
results in some value of a certain type that can be assigned to a variable. Some examples of C
expressions are shown in the table given below.
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and then replaces the previous value of the variable on the left
hand side. All variables used in the expression must be assigned values before evaluation is
attempted.
Example of evaluation statements are
x=a*b–c
y=b/c*a
z = a – b / c + d;
The following program illustrates the effect of presence of parenthesis in expressions.
Ex:
main ()
{
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf (―x = %fn‖,x);
printf (―y = %fn‖,y);
printf (―z = %fn‖,z);
}
Output:
x = 10.00
y = 7.00
z = 4.00
Operator Precedence:
This page lists C operators in order of precedence (highest to lowest). Their
associativity indicates in what order operators of equal precedence in an expression are
applied.
Note 2:
Postfix increment/decrement have high precedence, but the actual increment or
decrement of the operand is delayed (to be accomplished sometime before the
statement completes execution). So in the statement y = x * z++; the current
value of z is used to evaluate the expression (i.e., z++ evaluates to z) and z only
incremented after all else is done.
Type Conversions:
There are two kinds of type conversion we need to talk about: automatic or implicit type
conversion and explicit type conversion.
This sort of implicit or automatic conversion can produce nasty bugs that are difficult
to find, especially for example when performing multiplication or division using mixed types,
e.g. integer and floating-point values. Here is some example code illustrating some of these
effects:
#include <stdio.h>
int main() {
int a = 2;
double b = 3.5;
double c = a * b;
double d = a / b;
int e = a * b;
int f = a / b;
printf("a=%d, b=%.3f, c=%.3f, d=%.3f, e=%d, f=%d\n",a, b, c, d, e, f);
return 0;
}
Output:
a=2, b=3.500, c=7.000, d=0.571, e=7, f=0
char_variable_name = getchar( );
Ex:
#include<stdio.h>
main()
{
char ch;
int a,b,c;
printf(―Would you like perform addition or subtraction\?\n‖);
printf(―Type A for addition and S for subtraction ‖);
ch = getchar( );
if(ch==‘A‘ || ch==‘a‘)
{
printf(―\nEnter a and b values: ‖);
scanf(―%d %d‖, &a, &b);
c = a+b;
printf(―\n Addition is %d‖,c);
}
else if(ch==‘A‘ || ch==‘a‘)
{
printf(―\nEnter a and b values: ‖);
scanf(―%d %d‖, &a, &b);
c = a-b;
printf(―\n Subtraction is %d‖,c);
}
else
{
Printf(―\nInvalid letter‖);
}
}
Output1:
Would you like perform addition or subtraction?
Type A for addition and S for subtraction A
Enter a and b values: 5 6
Addition is 11
Output2:
Would you like perform addition or subtraction?
Type A for addition and S for subtraction S
Enter a and b values: 8 3
Subtraction is 5
The putchar( ) function is identical in description to the getchar( ) function except the
following difference. putchar( ) writes a character to the stdout data stream.
putchar(char_variable_name);
When input and output is required in a specified format the standard library functions
scanf( ) and printf( ) are used. The scanf( ) function allows the user to input data in a
specified format. It can accept data in a specified format. It can accept data of different data
type. The printf( ) function allows the user to output data of different data types on the
console in a specified format.
a) Formatted input:
C using scanf function for formatted input. We shall explore all of the options
that are available for reading the formatted data with scanf function.
The general format is:
scnaf(―control_string‖, var1,var2,var3,…..,varn);
The control string specifies the field format in which the data is to be entered
and the variables var1, var2, var3,…..,varn specify the address of locations where the
data is Stored. Control string and variables separated by commas.
Ex:
#include<stdio.h>
main()
{
Int a, b, c;
printf(―\nEnter a and b values: ‖);
scanf(―%d %d‖, &a, &b);
c = a+b;
printf(―\n Addition is %d‖,c);
}
b) Formatted output:
The printf( ) function do differe from the sort of functions that are created by
the programmer as they can take a variable number of parameters.
The general format is:
printf(―control_string‖,variable1,variable2,…..,variable);
Ex:
printf(―welcome‖);
The above statement displays welcome only.
printf(―sum is %d‖, s);
The above format specifier %d means convert the next value to a
signed decimal integer, and hence will print sum = and then the value passed by the
variable named s as a decimal integer.