Unit 2
Unit 2
Structure of a C program 51
Variables 59
Data Types 64
UNIT –I
47
C PROGRAMMING BASICS
INTRODUCTION TO C
The UNIX operating system, the C compiler, and essentially all UNIX
applications programs have been written in C. C has now become a widely used
professional language for various reasons.
Easy to learn
Structured language
Facts about C
C was invented to write an operating system called UNIX.
48
Most of the state-of-the-art softwares have been implemented using C.
Today's most popular Linux OS and RBDMS MySQL have been written
in C.
Types of Language:
Below are the steps to be followed for any C program to create and get the
output. This is common to all C program and there is no exception whether its a
very small C program or very large C program.
50
If you want to create, compile and execute C programs by your own, you
have to install C compiler in your machine. Then, you can start to execute
your own C programs in your machine.
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section
52
BASIC C PROGRAM
#include <stdio.h>
int main()
{
/* Our first simple C basic program */
printf(“Hello World! “);
getch();
return 0;
}.
Output:
Hello World! .
Basic commands in C programming to write basic C Program:
Below are few commands and syntax used in C programming to write a simple C program
PROGRAMMING RULES:
While writing a program, a programmer should follow the following rules.
53
1. All statements should be written in lowercase letters.
2. Uppercase letters are only used for symbolic constants.
3. Blank space may be inserted between words. But blank space is not used
while declaring a variable, keyword, constant and function.
4. The programmers can write the statement anywhere between the two braces.
5. We can write one or more statements in a same line by separating each
statement in a same line by separating each statement with semicolon (:)
6. The opening and closing braces should be balanced.
C CHARACTER SET
Character set are the 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:
0 1 2 3 4 5 6 8 9
White space Characters:
blank space, new line, horizontal tab, carriage return and form feed
Special Characters in C language
< > { } ( [
* ^ | \ ) *
C TOKENS
54
C tokens are of six types. They are,
int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
Printf (“Total = %d \n”, total);
}.
where,
main – identifier
{,}, (,) – delimiter
int – keyword
x, y, total – identifier
main, {, }, (, ), int, x, y, total – tokens
2. Identifiers in C language:
3. Keywords in C language:
55
Since keywords are referred names for compiler, they can’t be used as
variable name.
C language supports 32 keywords which are given below.
C CONSTANT:
But, only difference is, their values can not be modified by the program
once they are defined.
Constants refer to fixed values. They are also called as literals.
Constants may be belonging to any of the data type.
TYPES OF C CONSTANT
1. Integer constants
2. Real or Floating point constants
3. Octal constants
4. Hexadecimal constants
5. Character constants
6. String constants
56
3 Octal constant int 013 /* starts with 0 */
4 Hexadecimal constant int 0×90 /* starts with 0x */
5 character constants char ‘A’ , ‘B’, ‘C’
6 string constants char “ABCD” , “Hai”
1. Integer Constants in C:
2. Real constants in C:
Backslash_character Meaning
57
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)
1. By “const” keyword
2. By “#define” preprocessor directive
Please note that when you try to change constant values after defining in
C program, it will through error.
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = ‘A’; /*char constant*/
const char letter_sequence[10] = “ABC”; /*string constant*/
58
const char backslash_char = ‘\?’; /*special char cnst*/
printf(“value of height :%d \n”, height );
printf(“value of number : %f \n”, number );
printf(“value of letter : %c \n”, letter );
printf(“value of letter_sequence : %s \n”, letter_sequence);
printf(“value of backslash_char : %c \n”, backslash_char);
}
Output:
variable
C variable is a named location in a memory where a program can
manipulate the data. This location is used to hold the value of the
variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char
etc.
59
Variable data_type variable_name int x = 50, y = 30; char flag
2
initialization = value; = ‘x’, ch=’l’;
1. Local variable
2. Global variable
3. Environment variable
Local variable:
The local variable are defined within the body of the function.these
variables are defined local to that function only or block only,other
function cannot access these variables.
Eg:
Value(int a,int b)
{
int e,f;
}
#include<stdio.h>
void test();
int main()
{
int m = 22, n = 44;
printf(“\nvalues : m = %d and n = %d”, m, n);
test();
}
void test()
{
int a = 50, b = 80;
// a, b are local variables of test function
/*a and b variables are having scope
within this test function only.
These are not visible to main function.*/
/* If you try to access m and n in this function,
you will get ‘m’ undeclared and ‘n’ undeclared
error */printf(“\nvalues : a = %d and b = %d”, a, b);
}
60
The scope of local variables will be within the function only.
These variables are declared within the function and can’t be accessed
outside the function.
In the below example, m and n variables are having scope within the
main function only. These are not visible to test function.
Like wise, a and b variables are having scope within the test function
only. These are not visible to main function.
Global variables
are defined outside the main() function.multiple function can use these
variables.
Eg:
int m=5,n=10;
main()
{
int a,b;
}
m and n are global variables.
#include<stdio.h>
void test();
int m = 22, n = 44;
int a = 50, b = 80;
int main()
{
printf(“All variables are accessed from main function”);
printf(“\nvalues: m=%d:n=%d:a=%d:b=%d”, m,n,a,b);
test();
}
void test()
{
printf(“\n\nAll variables are accessed from” \
” test function”);
printf(“\nvalues: m=%d:n=%d:a=%d:b=%d”, m,n,a,b);
}
61
Output:
3. Environment variables in C:
There are 3 functions which are used to access, modify and assign an
environment variable in C. They are,
1. setenv()
2. getenv()
3. putenv()
Difference between variable declaration & definition in C:
QUALIFIERS:
C – type qualifiers : The keywords which are used to modify the properties
of a variable are called type qualifiers.
1. const
2. volatile
1. const keyword:
62
Constants are also like normal variables. But, only difference is, their
values can’t be modified by the program once they are defined.
They refer to fixed values. They are also called as literals.
They may be belonging to any of the data type.
Syntax:
2. volatile keyword:
When a variable is defined as volatile, the program may not change the
value of the variable explicitly.
But, these variable values might keep on changing without any explicit
assignment by the program. These types of qualifiers are called volatile.
For example, if global variable’s address is passed to clock routine of the
operating system to store the system time, the value in this address keep
on changing without any assignment by the program. These variables are
named as volatile variable.
Syntax:
C – DATA TYPES:
63
2 Enumeration data type enum
3 Derived data type pointer, array, structure, union
4 Void data type void
Note:
FLOAT:
DOUBLE:
Double data type is also same as float data type which allows up-to 10
digits after decimal.
The range for double datatype is from 1E–37 to 1E+37.
sizeof() function in C:
sizeof() function is used to find the memory space allocated for each C data
types.
#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf(“Storage size for int data type:%d \n”,sizeof(a));
printf(“Storage size for char data type:%d \n”,sizeof(b));
printf(“Storage size for float data type:%d \n”,sizeof(c));
printf(“Storage size for double data type:%d\n”,sizeof(d));
return 0;
}.
Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8 .
65
Modifiers in C:
1. short
2. long
3. signed
4. unsigned
5. long long
Below table gives the detail about the storage size of each C basic data
type in 16 bit processor.Please keep in mind that storage size and range
for int and float datatype will vary depend on the CPU processor (8,16,
32 and 64 bit)
storage
S.No C Data types Range
Size
1 char 1 –127 to 127
2 int 2 –32,767 to 32,767
1E–37 to 1E+37 with six digits of
3 float 4
precision
1E–37 to 1E+37 with ten digits of
4 double 8
precision
1E–37 to 1E+37 with ten digits of
5 long double 10
precision
6 long int 4 –2,147,483,647 to 2,147,483,647
7 short int 2 –32,767 to 32,767
8 unsigned short int 2 0 to 65,535
9 signed short int 2 –32,767 to 32,767
10 long long int 8 –(2power(63) –1) to 2(power)63 –1
11 signed long int 4 –2,147,483,647 to 2,147,483,647
12 unsigned long int 4 0 to 4,294,967,295
13 unsigned long long 8 2(power)64 –1
66
int
Enum example in C:
enum month { Jan, Feb, Mar }; Jan, Feb and
Mar variables
will be assigned
to 0,1,2
respectively
default
enum month { Jan = 1, Feb, Mar }; Feb and Mar
variables will be
assigned to 2 and
3 respectively by
default
enum month { Jan = 20, Feb, Mar }; Jan is assigned to
20. Feb and Mar
variables will be
assigned to 21
and 22
respectively by
default
67
C – enum example program:
#include <stdio.h>
int main()
{
enum MONTH { Jan = 0, Feb, Mar };
enum MONTH month = Mar;
if(month == 0)
printf(“Value of Jan”);
else if(month == 1)
printf(“Month is Feb”);
if(month == 2)
printf(“Month is Mar”);
}.
Output:
Month is Mar .
Array, pointer, structure and union are called derived data type in C
language.
To know more about derived data types, please visit “C – Array“ , “C –
Pointer” , “C – Structure” and “C – Union” topics in upcoming chapters.
A + B * 5 is an expression.
a+b
x=y
t=u+v
x <= y++j
The first expression, which employs the addition operator (+), represents the
sum of the values assigned to variables a and b.
The second expression involves the assignment operator (=), and causes the
value represented by y to be assigned to x.
In the third expression, the value of the expression (u + v) is assigned to t.
The increment (by unity) operator ++ is called a unary operator, because it only
possesses one operand.
A statement causes the computer to carry out some definite action. There are
three different classes of statements in C: expression statements, compound
statements, and control statements.
For example:
a = 6;
c = a + b;
++j;
The first two expression statements both cause the value of the expression on
the right of the equal sign to be assigned to the variable on the left. The third
expression statement causes the value of j to be incremented by 1. Again, there
is no restriction on the length of an expression statement: such a statement can
even be split over many lines, so long as its end is signaled by a semicolon.
69
A compound statement consists of several individual statements enclosed within
a pair of braces { }. The individual statements may themselves be expression
statements, compound statements, or control statements. Unlike expression
statements, compound statements do not end with semicolons. A typical
compound statement is shown below:
{
pi = 3.141593;
circumference = 2. * pi * radius;
area = pi * radius * radius;
}
This particular compound statement consists of three expression statements, but
acts like a single entity in the program in which it appears.
Types of C operators:
70
C language offers many types of operators. They are,
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
Arithmetic Operators in C:
C Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs.
In this example program, two values “40″ and “20″ are used to perform
arithmetic operations such as addition, subtraction, multiplication,
division, modulus and output is displayed for each operation.
#include <stdio.h>
int main()
{
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf(“Addition of a, b is : %d\n”, add);
printf(“Subtraction of a, b is : %d\n”, sub);
72
printf(“Multiplication of a, b is : %d\n”, mul);
printf(“Division of a, b is : %d\n”, div);
printf(“Modulus of a, b is : %d\n”, mod);
}
Output:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
Assignment operators in C:
# include <stdio.h>
int main()
{
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total = Toatal+i
}
printf(“Total = %d”, Total);
}
Output:
Total = 45
RELATIONAL OPERATORS IN C:
Relational operators are used to find the relation between two variables. i.e. to compare the values of
two variables in a C program.
#include <stdio.h>
int main()
{
74
int m=40,n=20;
if (m == n)
{
printf(“m and n are equal”);
}
else
{
printf(“m and n are not equal”);
}
}
Output:
LOGICAL OPERATORS IN C:
#include <stdio.h>
int main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n && m !=0)
{
printf(“&& Operator : Both conditions are true\n”);
75
}
if (o>p || p!=20)
{
printf(“|| Operator : Only one condition is true\n”);
}
if (!(m>n && m !=0))
{
printf(“! Operator : Both conditions are true\n”);
}
else
{
printf(“! Operator : Both conditions are true. ” \
“But, status is inverted as false\n”);
}
} output:
&& Operator : Both conditions are true
|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false
In this program, operators (&&, || and !) are used to perform logical
operations on the given expressions.
&& operator – “if clause” becomes true only when both conditions
(m>n and m! =0) is true. Else, it becomes false.
|| Operator – “if clause” becomes true when any one of the condition
(o>p || p!=20) is true. It becomes false when none of the condition is true.
! Operator – It is used to reverses the state of the operand.
If the conditions (m>n && m!=0) is true, true (1) is returned. This value
is inverted by “!” operator.
So, “! (m>n and m! =0)” returns false (0).
These operators are used to perform bit operations. Decimal values are
converted into binary values which are the sequence of bits and bit wise
operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~
(bitwise OR), ^ (XOR), << (left shift) and >> (right shift).
Truth table for bit wise operation Bit wise operators
#include <stdio.h>
int main()
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf(“AND_opr value = %d\n”,AND_opr );
printf(“OR_opr value = %d\n”,OR_opr );
printf(“NOT_opr value = %d\n”,NOT_opr );
printf(“XOR_opr value = %d\n”,XOR_opr );
printf(“left_shift value = %d\n”, m << 1);
printf(“right_shift value = %d\n”, m >> 1);
}
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
77
.
In above example, if A is greater than 100, 0 is returned else 1 is returned.
This is equal to if else conditional statements.
#include <stdio.h>
int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf(“x value is %d\n”, x);
printf(“y value is %d”, y);
}
Output:
x value is 1
y value is 2
#include <stdio.h>
int main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
1234
Step 1 : In above program, value of “i” is incremented from 0 to 1 using
pre-increment operator.
Step 2 : This incremented value “1″ is compared with 5 in while
expression.
Step 3 : Then, this incremented value “1″ is assigned to the variable “i”.
78
Above 3 steps are continued until while expression becomes false and
output is displayed as “1 2 3 4″.
#include <stdio.h>
int main()
{
int i=0;
while(i++ < 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
12345
Step 1 : In this program, value of i ”0″ is compared with 5 in while
expression.
Step 2 : Then, value of “i” is incremented from 0 to 1 using post-
increment operator.
Step 3 : Then, this incremented value “1″ is assigned to the variable “i”.
Above 3 steps are continued until while expression becomes false and
output is displayed as “1 2 3 4 5″.
#include <stdio.h>
int main()
{
int i=10;
while(--i > 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
9876
Step 1 : In above program, value of “i” is decremented from 10 to 9 using
pre-decrement operator.
79
Step 2 : This decremented value “9″ is compared with 5 in while
expression.
Step 3 : Then, this decremented value “9″ is assigned to the variable “i”.
Above 3 steps are continued until while expression becomes false and
output is displayed as “9 8 7 6″.
#include <stdio.h>
int main()
{
int i=10;
while(i-- > 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
98765
Step 1 : In this program, value of i ”10″ is compared with 5 in while
expression.
Step 2 : Then, value of “i” is decremented from 10 to 9 using post-
decrement operator.
Step 3 : Then, this decremented value “9″ is assigned to the variable “i”.
Above 3 steps are continued until while expression becomes false and
output is displayed as “9 8 7 6 5″.
Special Operators in C:
80
In this program, “&” symbol is used to get the address of the variable and
“*” symbol is used to get the value of the variable that the pointer is
pointing to. Please refer C – pointer topic to know more about pointers.
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q’s value using ptr variable */
printf(“%d”, *ptr);
return 0;
}
Output:
50
sizeof() operator is used to find the memory space allocated for each C
data types.
#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf(“Storage size for int data type:%d \n”,sizeof(a));
printf(“Storage size for char data type:%d \n”,sizeof(b));
printf(“Storage size for float data type:%d \n”,sizeof(c));
printf(“Storage size for double data type:%d\n”,sizeof(d));
return 0;
}
Output:
81
Storage size for double data type:8
Data input and output operations in C are carried out by the standard
input/output library (header file: stdio.h) via the functions scanf, printf, fscanf,
and fprintf, which read and write data from/to the terminal, and from/to a data
file, respectively.
Input : In any programming language input means to feed some data into
program. This can be given in the form of file or from command line. C
programming language provides a set of built-in functions to read given input
and feed it to the program as per requirement.
Here we will discuss only one input function and one putput function just to
understand the meaning of input and output. Rest of the functions are given into
C - Built-in Functions
printf() function
#include <stdio.h>
main()
{
int dec = 5;
char str[] = "abc";
char ch = 's';
float pi = 3.14;
scanf() function
This is the function which can be used to to read an input from the command
line.
#include <stdio.h>
main()
{
int x;
int args;
Here %d is being used to read an integer value and we are passing &x to store
the vale read input. Here &indicates the address of variavle x.
This program will prompt you to enter a value. Whatever value you will enter at
command prompt that will be output at the screen using printf() function. If you
eneter a non-integer value then it will display an error message.
Enter an integer: 20
Read in 20
83
Example program for C printf() function:
#include <stdio.h>
int main()
{
char ch = ‘A’;
char str[20] = “fresh2refresh.com”;
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf(“Character is %c \n”, ch);
printf(“String is %s \n” , str);
printf(“Float value is %f \n”, flt);
printf(“Integer value is %d\n” , no);
printf(“Double value is %lf \n”, dbl);
printf(“Octal value is %o \n”, no);
printf(“Hexadecimal value is %x \n”, no);
return 0;
}.
Output:
Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96 .
You can see the output with the same data which are placed within the double
quotes of printf statement in the program except
84
%o got replaced by a octal value corresponding to integer variable (no),
2. C scanf() function:
Then, user enters a string and this value is assigned to the variable ”str”
and then displayed.
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf(“Enter any character \n”);
scanf(“%c”, &ch);
printf(“Entered character is %c \n”, ch);
printf(“Enter any string ( upto 100 character ) \n”);
scanf(“%s”, &str);
printf(“Entered string is %s \n”, str);
}.
Output:
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai
85
C – Decision Control statement
In decision control statements (C if else and nested if), group of
statements are executed when condition is true. If condition is false, then
else part statements are executed.
There are 3 types of decision making control statements in C language.
They are,
1. if statements
2. if else statements
3. nested if statements
Syntax for each C decision control statements are given in below table
with description.
Decision
control Syntax Description
statements
In these type of statements, if
if (condition)
if condition is true, then respective block
{ Statements; }
of code is executed.
if (condition)
{ Statement1; In these type of statements, group of
Statement2; } statements are executed when
if…else
else condition is true. If condition is false,
{ Statement3; then else part statements are executed.
Statement4; }
if (condition1)
If condition 1 is false, then condition 2
{ Statement1; }
is checked and statements are executed
nested if else_if(condition2)
if it is true. If condition 2 also gets
{ Statement2; }
failure, then else part is executed.
else Statement 3;
86
In “if” control statement, respective block of code is executed when condition is
true.
int main()
{
int m=40,n=40;
if (m == n)
{
printf("m and n are equal");
}
}
Output:
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
Output:
87
In “nested if” control statement, if condition 1 is false, then condition 2 is
checked and statements are executed if it is true.
If condition 2 also gets failure, then else part is executed.
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}
}
Output:
m is greater than n
Loop control statements in C are used to perform looping operations until the
given condition is true. Control comes out of the loop statements once condition
becomes false.
1. for
2. while
3. do-while
Syntax for each C loop control statements are given in below table with description.
Loop
S.no Syntax Description
Name
1 for for (exp1; exp2; Where,
expr3) exp1 – variable
{ statements; } initialization
88
( Example: i=0, j=2, k=3 )
exp2 – condition checking
( Example: i>5, j<3, k=3 )
exp3 –
increment/decrement
( Example: ++i, j–, ++k )
where,
while (condition)
2 while condition might be a>5,
{ statements; }
i<10
where,
do { statements; }
3 do while condition might be a>5,
while (condition);
i<10
In for loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}
Output:
0123456789
In while loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i=3;
89
while(i<10)
{
printf("%d\n",i);
i++;
}
}
Output:
3456789
#include <stdio.h>
int main()
{
int i=1;
do
{
printf("Value of i is %d\n",i);
i++;
}while(i<=4 && i>=2);
}
Output:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
1. switch
2. break
3. continue
4. goto
Switch case statements are used to execute only specific case statements
based on the switch expression.
Below is the syntax for switch case statement.
switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
default: statements;
break;
}
#include <stdio.h>
int main ()
{
int value = 3;
switch(value)
{
case 1:
printf(“Value is 1 \n” );
break;
91
case 2:
printf(“Value is 2 \n” );
break;
case 3:
printf(“Value is 3 \n” );
break;
case 4:
printf(“Value is 4 \n” );
break;
default :
printf(“Value is other than 1,2,3,4 \n” );
}
return 0;
}
Output:
Value is 3
2. break statement in C:
Break statement is used to terminate the while loops, switch case loops
and for loops from the subsequent execution.
Syntax: break;
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf(“\nComing out of for loop when i = 5″);
break;
}
printf(“%d “,i);
92
}
}
Output:
01234
Coming out of for loop when i = 5
3. Continue statement in C:
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
printf(“\nSkipping %d from display using ” \
“continue statement \n”,i);
continue;
}
printf(“%d “,i);
}
}
Output:
01234
Skipping 5 from display using continue statement
Skipping 6 from display using continue statement
789
4. goto statement in C:
93
{
…….
go to label;
…….
…….
LABEL:
statements;
}
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf(“\nWe are using goto statement when i = 5″);
goto HAI;
}
printf(“%d “,i);
}
HAI : printf(“\nNow, we are inside label name \”hai\” \n”);
}
Output:
01234
We are using goto statement when i = 5
Now, we are inside label name “hai”
Random numbers
94
srand() with the same seed value. If no seed value is provided, the rand()
function is automatically seeded with the value 1. It is common practice in C
programming to seed the random number generator with the number of seconds
elapsed since 00:00:00 UTC, January 1st, 1970. This number is returned, as an
integer, via a call to the time (NULL) function (header file: <time.h>). Seeding
the generator in this manner ensures that a different set of random numbers is
generated automatically each time the program is run.
The program listed below illustrates the use of the rand() function to construct a
pseudo-random variable, x, which is uniformly distributed in the range 0 to 1.
The program calculates 107values of x, and then evaluates the mean and
variance of these values.
/* random.c */
/*
Program to test operation of rand() function
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define N_MAX 10000000
int main()
{
int i, seed;
double sum_0, sum_1, mean, var, x;
sum_0 += x;
sum_1 += (x - 0.5) * (x - 0.5);
}
mean = sum_0 / (double) N_MAX;
var = sum_1 / (double) N_MAX;
95
printf("mean(x) = %12.10f var(x) = %12.10f\n", mean, var);
return 0;
}
The typical output from this program is as follows:
, respectively. It can be seen that the values returned by the program agree
with these theoretical values to five decimal places, which is all that can be
expected with only 107calls.
Timing
The header file time.h defines a number of library functions which can be used
to assess how much CPU time a C program consumes during execution. The
simplest such function is called clock(). A call to this function, with no
argument, will return the amount of CPU time used so far by the calling
program. The time is returned in a special data type, clock_t, defined in time.h.
This time must be divided by CLOCKS_PER_SEC, also defined in time.h, in
order to covert it into seconds. The ability to measure how much CPU time a
given code consumes is useful in scientific programming: e.g., because it allows
the effectiveness of the various available compiler optimization flags to be
determined. Optimization usually (but not always!) speeds up the execution of a
program. However, over aggressive optimization can often slow a program
down again.
The program listed below illustrates the simple use of the clock() function. The
program compares the CPU time required to raise a double to the fourth power
via a direct calculation and via a call to the pow() function. Actually, both
operations are performed a million times and the elapsed CPU time is then
divided by a million.
96
/* timing.c */
/*
Program to test operation of clock() function
*/
#include <time.h>
#include <math.h>
#define N_LOOP 1000000
int main()
{
int i;
double a = 11234567890123456.0, b;
clock_t time_1, time_2;
time_1 = clock();
for (i = 0; i < N_LOOP; i++) b = a * a * a * a;
time_2 = clock();
printf ("CPU time needed to evaluate a*a*a*a: %f microsecs\n",
(double) (time_2 - time_1) / (double) CLOCKS_PER_SEC);
time_1 = clock();
for (i = 0; i < N_LOOP; i++) b = pow(a, 4.);
time_2 = clock();
printf ("CPU time needed to evaluate pow(a, 4.): %f microsecs\n",
(double) (time_2 - time_1) / (double) CLOCKS_PER_SEC);
return 0;
}
The typical output from this program is as follows:
Complex numbers
97
concept which crops up very often in systems programming! Fortunately, this
rather serious deficiency--at least, as far as the scientific programmer is
concerned--is remedied in C++. The program listed below illustrates the use of
the C++ complex class (header file complex.h) to perform complex arithmetic
using doubles:
/* complex.cpp */
/*
Program to test out C++ complex class
*/
#include <complex.h>
#include <stdio.h>
int main()
{
dcomp i, a, b, c, d, e, p, q, r; // Declare complex double variables
double x, y;
return 0;
}
The typical output from this program is as follows:
i = (0.0000, 1.0000)
99
void subtraction();
void multiplication();
void division();
void modulus();
void power();
int factorial();
void calculator_operations();
// Function call
calculator_operations();
while(X)
{
printf("\n");
printf("%s : ", KEY);
Calc_oprn=getche();
switch(Calc_oprn)
{
case '+': addition();
break;
100
case '^': power();
break;
case 'H':
case 'h': calculator_operations();
break;
case 'Q':
case 'q': exit(0);
break;
case 'c':
case 'C': system("cls");
calculator_operations();
break;
default : system("cls");
//Function Definitions
void calculator_operations()
{
//system("cls"); use system function to clear
//screen instead of clrscr();
printf("\n Welcome to C calculator \n\n");
void addition()
{
int n, total=0, k=0, number;
printf("\nEnter the number of elements you want to add:");
scanf("%d",&n);
printf("Please enter %d numbers one by one: \n",n);
while(k<n)
{
scanf("%d",&number);
total=total+number;
k=k+1;
}
printf("Sum of %d numbers = %d \n",n,total);
}
void subtraction()
{
int a, b, c = 0;
printf("\nPlease enter first number : ");
scanf("%d", &a);
printf("Please enter second number : ");
scanf("%d", &b);
c = a - b;
printf("\n%d - %d = %d\n", a, b, c);
}
void multiplication()
{
int a, b, mul=0;
printf("\nPlease enter first numb : ");
scanf("%d", &a);
printf("Please enter second number: ");
scanf("%d", &b);
mul=a*b;
printf("\nMultiplication of entered numbers = %d\n",mul);
}
void division()
102
{
int a, b, d=0;
printf("\nPlease enter first number : ");
scanf("%d", &a);
printf("Please enter second number : ");
scanf("%d", &b);
d=a/b;
printf("\nDivision of entered numbers=%d\n",d);
}
void modulus()
{
int a, b, d=0;
printf("\nPlease enter first number : ");
scanf("%d", &a);
printf("Please enter second number : ");
scanf("%d", &b);
d=a%b;
printf("\nModulus of entered numbers = %d\n",d);
}
void power()
{
double a,num, p;
printf("\nEnter two numbers to find the power \n");
printf("number: ");
scanf("%lf",&a);
printf("power : ");
scanf("%lf",&num);
p=pow(a,num);
int factorial()
{
int i,fact=1,num;
if (num<0)
103
{
printf("\nPlease enter a positive number to");
printf(" find factorial and try again. \n");
printf("\nFactorial can't be found for negative");
printf(" values. It can be only positive or 0 \n");
return 1;
}
for(i=1;i<=num;i++)
fact=fact*i;
printf("\n");
printf("Factorial of entered number %d is:%d\n",num,fact);
return 0;
}
104
2 marks question
1.what are steps to write c program and get output.
105
2. what is the basic structure of c program:
Documentation section
Link Section
Definition Section
Global declaration section
Function prototype declaration section
Main function
User defined function definition section
106
We can define constants in a C program in the following ways.
By “const” keyword
By “#define” preprocessor directive
Local variable
Global variable
Environment variable
Arithmetic operators
Assignment operators
Relational operators
Logical operators
Bit wise operators
Conditional operators (ternary operators)
Increment/decrement operators
Special operators
107
Below are some of special operators that C language offers.
sizeof() operator is used to find the memory space allocated for each
C data types.
#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf(“Storage size for int data type:%d \n”,sizeof(a));
printf(“Storage size for char data type:%d \n”,sizeof(b));
printf(“Storage size for float data type:%d \n”,sizeof(c));
printf(“Storage size for double data type:%d\n”,sizeof(d));
return 0;
}
Output:
11.Define QUALIFIERS:
108
C – type qualifiers : The keywords which are used to modify the properties
of a variable are called type qualifiers.
const
volatile
109
Example : while (i=7) is an infinite loop because it is a non zero value and
while (i==7) is
true only when i=7.
17. What is type casting?
Type casting is the process of converting the value of an expression to a
particular data type.
Example: int x, y; c = (float) x/y; where a and y are defined as integers.
Then The result of x/y is converted into float.
110
The loop is defined as the block of statements which are repeatedly
executed for certain number of times.
enum month {jan= 1,feb,mar, apr, may, jun,jul,aug, sep, oct,nov, dec };
If while
It is a conditional statement It is a loop control statement
If the condition is true, it executes Executes the statements within the
some statements. while block if the condition istrue.
(iii) If the condition is false then it (iii) If the condition is false the control
stops is
the execution the statements. transferred to the next statement of the
loop.
WHILE DO WHILE
This is the top tested loop This is the bottom tested
The condition is first tested, if the It executes the body once after it
condition is true, then the block is checks the condition, if it is true the
executed until the condition becomes body is executed until the condition
false. become false.
PART A
115