Overview of C Programming Language
Overview of C Programming Language
Unit 1 Overview of C
Unit 2 C Program Design
Unit 3 Executing a C Program
UNIT 1 OVERVIEW OF C
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Contents
3.1 Brief History of C
3.2 Taxonomy of C Types
3.3 Why Study C?
3.4 Why is C Popular?
3.5 Characteristics of C program
3.6 Uses of C
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
31
CIT301 STRUCTURED PROGRAMMING
Scalar types
Arithmetic types
Integral types: char, short, int, long
Floating-point types: float, double, long double
Pointer types
Aggregate types
Array types
Structure types
Union types
Function types
Void types
32
CIT301 MODULE 4
3.6 Uses of C
Spreadsheets
Operating system development
Compilers and Assemblers
Network drivers and Interpreters
SELF-ASSESSMENT EXERCISE
34
CIT301 MODULE 4
4.0 CONCLUSION
5.0 SUMMARY
35
CIT301 STRUCTURED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes
3.0 Main Contents
3.1 C Program Structure
3.2 Files Used in A C Program
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
36
CIT301 MODULE 4
Explanation:
#include: The part of the compiler which actually gets your
program from the source file is called the preprocessor.
#include <stdio.h>:#include is a pre-processor directive. It is not
really part of our program, but instead it is an instruction to the
compiler to make it do something. It tells the C compiler to
include the contents of a file (in this case the system file called
stdio.h).
The compiler knows it is a system file, and therefore must be
looked for in a special place, by the fact that the filename is
enclosed in <> characters
<stdio.h>: stdio.h is the name of the standard library definition file for
all STanDard Input and Output functions.
The program will almost certainly want to send information to the
screen and read things from the keyboard, and stdio.h is the name
of the file in which the functions that we want to use are defined.
The function we want to use is called printf. The actual code of printf
will be tied in later by the linker.
The ".h" portion of the filename is the language extension, which
denotes an include file.
void:This literally means that this means nothing. In this case, it
is referring to the function whose name follows. Void tells C
compiler that a given entity has no meaning and produces no
error.
main:In this example, the only function in the program is called
main. A C program is typically made up of large number of
functions. Each of these is given a name by the programmer and
they refer to each other as the program runs. C regards the name
main as a special case and will run this function first i.e. the
program execution starts from main.
(void): This is a pair of brackets enclosing the keyword void.
It tells the compiler that the function main has no parameters.
A parameter to a function gives the function something to work on.
{ (Brace): This is a brace (or curly bracket). As the name implies,
braces come in packs of two - for every open brace there must be
a matching close one. Braces allow us to group pieces of program
together, often called a block.A block can contain the declaration
of variable used within it, followed by a sequence of program
statements.
In this case the braces enclose the working parts of the function main.
; (semicolon): The semicolon marks the end of the list of variable
names, and also the end of that declaration [Link]
statements in C programs are separated by ";" (semicolon)
characters. The ";" character is actually very important. It tells
the compiler where a given statement ends.
37
CIT301 STRUCTURED PROGRAMMING
Source File- This file contains the source code of the program.
The file extension of any c file is .c. The file contains C source
code that defines the main function & maybe other functions.
Header File- A header file is a file with extension .h which
contains the C function declarations and macro definitions and to
be shared between several source files.
Object File- An object file is a file containing object code, with
an extension .o, meaning relocatable format machine code that is
usually not directly executable. Object files are produced by an
assembler, compiler, or other language translator, and used as
input to the linker, which in turn typically generates an
executable or library by combining parts of object files.
Executable File- The binary executable file is generated by the
linker. The linker links the various object files to produce a
binary file that can be directly executed.
SELF-ASSESSMENT EXERCISE
Solution:
Explain all the reserved words used in the description of a C program
structure.
38
CIT301 MODULE 4
1. volatile
This keyword is needed so as to create volatile objects. These volatile
objects have the ability to get modified in the unknown or unmentioned
method through hardware.
2. auto
This keyword is used to declare the automatic variables.
3. char
char keyword is used to declare the character variable. Variables that are
of type char are of 1-byte length. They can get signed (it is by default
unless we use the compiler option ‘-funsigned-char’ or ‘unsigned’),
which implies they have got a range of -128 to 127 and 0 to 255,
respectively.
4. double and float
Both keywords double, as well as float, are needed for declaration of
floating type variables.
5. const
We can declare an identifier to be constant through the usage of the
const keyword.
6. if and else
We use if and else so as to make decisions in C programming.
7. break and continue
The break statement would make the program jump out of the most
inner and enclosing loop in an explicit manner. The continue is used for
statements skipping certain statements that are inside the loop.
8. enum
In C programming enumeration types get declared through keyword
enum.
9. extern
The extern keyword indicates that the identifier has benn defined
somewhere else. It also indicates that in fact storage as well as the initial
value, or function body has been defined somewhere else, mostly in the
10. return
Return is used for exiting the function. It would exit from the current
function that is executing immediately and return to the calling routine.
It can optionally return value too.
11. sizeof
sizeof is used for returning the size of expression or type of it. It is used
for returning the size in bytes.
13. int
int keyword is used for declaration of the integer type variable.
14. register
This keyword is used for the creation of the register variables that are
much faster as compared to the normal variables.
15. static
This keyword is used for the creation of a static variable. The static
variables’ values persist until the end of the program. It tells that the
39
CIT301 STRUCTURED PROGRAMMING
function or the element is only known inside the scope of the current
compilation. Also, if we use the static keyword along with the variable
which is local to the function, it would allow the last value of the
variable to get preserved in successive calls to that function.
16. struct
struct keyword is used for the declaration of the structure. The structure
is used for holding the variables of varied data types under one name.
Just like the union, it groups the variables into a single record. Also,
the struct-type-name is considered to be the optional tag name which
points to structure type. The variables of a structure are data definitions,
and they are optional. Although both are optional, one of the two must
appear.
17. union
Union keyword is needed for grouping the varied types of a variable
under one name.
18. void
This keyword denotes that the function won’t be returning any value.
19. typedef
This keyword is required so as to associate a type along with an
identifier in an explicit manner.
20. short, long, signed and unsigned
The short, long, signed as well as unsigned keywords are the type of
modifiers which alters the meaning of the base data type in order to
yield the new type.
21. for
In total, there exist 3 kinds of loops in C. The for loop in C is written
using the keyword for.
22. switch, case and default
We use switch as well as case statements whenever the block of
statements needs to be executed among various blocks.
23. do-while loop
do is used along with a while to make a different form of repetition of
the statement.
24. while
It is used for repeating the execution when the condition is true.
40
CIT301 MODULE 4
4.0 CONCLUSION
5.0 SUMMARY
In this unit you have been exposed to the structure of a C program and
some programming elements such #include, stdio.h, void, main, printf,
scanf, return etc. These elements are adequately explained in the unit.
Some of the files used in C program are also outlined.
41
CIT301 STRUCTURED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes
3.0 Main Contents
3.1 Compilation and Execution of a C Program
3.2 Commonly used Programs for execution on Linux System
3.3. Pictorial Diagram of C Compilation and Execution
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
42
CIT301 MODULE 4
43
CIT301 STRUCTURED PROGRAMMING
SELF-ASSESSMENT EXERCISE
44
CIT301 MODULE 4
4.0 CONCLUSION
After writing a C program, you will need to compile and execute it. This
involves some steps which has been heighted in this unit.
5.0 SUMMARY
In this unit, you have been taken through the compilation and execution
steps. These include preprocessing, compilation, assembly, linking and
loading. these steps are illustrated with a diagram for clearer
understanding.
45
CIT301 STRUCTURED PROGRAMMING
46
CIT301 MODULE 5
Unit 1 Element of C
Unit 2 Data Type
Unit 3 Variables, Statements, Expressions
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
3.1 Character Set
3.2 Keywords
3.3 Identifier
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
Every language has some basic elements and grammatical rules. Before
starting with programming, we should be acquainted with the basic
elements that build the language.
Elements of C
Every language has some basic elements and grammatical rules. Before
starting with programming, we should be acquainted with the basic
elements that build the language.
47
CIT301 STRUCTURED PROGRAMMING
3.2 Keywords
Keywords are the words whose meaning has already been explained to
the C compiler. The keywords cannot be used as variable names because
if we do so we are trying to assign a new meaning to the keyword,
which is not allowed by the computer. There are 32 keywords available
in C. The figure gives a list of these keywords for your ready reference.
3.3 Identifier:
48
CIT301 MODULE 5
SELF-ASSESSMENT EXERCISE
Solution
1. What are the character set used C programming language? Put
your response in a tabular format.
4.0 CONCLUSION
5.0 SUMMARY
49
CIT301 STRUCTURED PROGRAMMING
50
CIT301 MODULE 5
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
3.1 Data Types
3.2 Constants
3.3 Rules for Constructing Integer Constants
3.4 Rules for Constructing Real Constants
3.5 Rules for constructing real constants expressed in
exponential form
3.6 Rules for Constructing Character Constants
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
A data type defines a set of values and the operations that can be defined
on those values. Data types are especially important in C programming
language All operations are type checked by the compiler for type
compatibility. Illegal operations will not be compiled. Thus, strong type
checking helps prevent errors and enhances reliability.
51
CIT301 STRUCTURED PROGRAMMING
52
CIT301 MODULE 5
3.2 Constants
Primary Constants
Secondary Constants
53
CIT301 STRUCTURED PROGRAMMING
SELF-ASSESSMENT EXERCISE
Solution:
1. Differentiate between a variable and a constant in C programs
A variable is a programming element that can change during
program execution where as constant do not change.
54
CIT301 MODULE 5
4.0 CONCLUSION
5.0 SUMMARY
In this unit, you have learnt about C data types which include char, int,
float and double. You have also learnt about the various classifications
of these data types as well as constant and the rules for constructing the
various constants.
55
CIT301 STRUCTURED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
3.1 Variables and Variable Declaration
3.2 Initialization of Variables
3.3 Expressions
3.4 Statements
3.5 Compound Statements (Blocks)
3.6 Input-Output in C
3.7 Input-Output of integers in C
3.8 Input-Output of floats in C
3.9 Input-Output of characters and ASCII code
3.10 ASCII code
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
56
CIT301 MODULE 5
Variables are names that are used to store values. It can take different
values but one at a time. A data type is associated with each variable &
it decides what values the variable can take. When you decide your
program needs another variable, you simply declare (or define) a new
variable and C makes sure you get it. You declare all C variables at the
top of whatever blocks of code need them. Variable declaration requires
that you inform C of the variable's name and data type.
Syntax: datatype variablename;
Eg:
int page_no;
char grade;
float salary;
long y;
57
CIT301 STRUCTURED PROGRAMMING
3.3 Expressions
3.4 Statements
58
CIT301 MODULE 5
3.6 Input-Output in C
When we are saying Input that means we 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.
When we are saying Output that means to display some data on screen,
printer or in any file. C programming language provides a set of built-in
functions to output the data on the computer screen. Functions printf()
and scanf() are the most commonly used to display out and take input
respectively.
59
CIT301 STRUCTURED PROGRAMMING
Output:
C Programming
Explanation:
Every program starts from main() function.
printf() is a library function to display output which only works if
#include<stdio.h>is included at the beginning.
Here, stdio.h is a header file (standard input output header file)
and #include is command to paste the code from the header file
when necessary. When compiler encounters printf()function and
doesn't find stdio.h header file, compiler shows error.
return 0; indicates the successful execution of the program.
#include<stdio.h>
int main()
{
int c=5;
printf("Number=%d",c);
return 0;
}
Output:
Number=5
#include<stdio.h>
int main()
{
int c;
printf("Enter a number\n");
scanf("%d",&c);
printf("Number=%d",c);
60
CIT301 MODULE 5
return 0;
}
Output:
Enter a number
4
Number=4
The scanf() function is used to take input from user. In this program, the
user is asked an input and value is stored in variable c. Note the '&' sign
before c. &c denotes the address of c and value is stored in that address.
#include <stdio.h>
int main()
{
float a;
printf("Enter value: ");
scanf("%f",&a);
printf("Value=%f",a); //%f is used for floats instead of %d
return 0;
}
Output
Enter value:
23.45
Value=23.450000
Conversion format string "%f" is used for floats to take input and to
display floating value of a variable.
#include <stdio.h>
int main()
{
char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.",var1);
return 0;
}
Output
Enter character:
61
CIT301 STRUCTURED PROGRAMMING
g
You entered g.
Conversion format string "%c" is used in case of characters.
When character is typed in the above program, the character itself is not
recorded a numeric value (ASCII value) is stored. And when we
displayed that value by using "%c", that character is displayed.
#include <stdio.h>
int main()
{
char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.\n",var1);
/* \n prints the next line(performs work of enter). */
printf("ASCII value of %d",var1);
return 0;
}
Output:
Enter character:
g
103
When, 'g' is entered, ASCII value 103 is stored instead of g.
You can display character if you know ASCII code only. This is shown
by following example.
#include <stdio.h>
int main()
{
int var1=69;
printf("Character of ASCII value 69: %c",var1);
return 0;
}
Output
Character of ASCII value 69:
E
The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly,
ASCII value of 'a' is 97, 'b' is 98 and so on to 'z' is 122.
SELF-ASSESSMENT EXERCISE
62
CIT301 MODULE 5
i. What is a Variable?
ii. Declare a variable for each of the following C data type: integer,
float, double, and character and assign appropriate data value at
the pointer of declaration
iii. What is a statement? Give few examples.
iv. What is an Expression? Give few examples.
v. Write a program to display the upper- and lower-case letter “B”,
using two printf() function
Solution
1 What is a Variable? Give few meaningful examples
Variable is basically a name of a memory location that we use for
storing data. We can change the value of a variable in C or any
other language, and we can also reuse it multiple times.
Examples:
rate
salary
product
Examples:
area =length * breadth;
printf (“Structured Programming”);
scanf("%d",&c);
63
CIT301 STRUCTURED PROGRAMMING
5.0 SUMMARY
In this unit, you have learned about variables, statements and
expressions. You have also learnt how variables are declared and
initialized, how expressions are constructed, and what constitutes a
statement including compound statements. All these are well illustrated
with examples.
64
CIT301 MODULE 5
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
3.1 Formatted Input-Output
3.2 Variations in Output for integer and floats
3.3 Variations in Input for integer and floats
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
#include<stdio.h>
int main()
{
printf("Case 1:%6d\n",9876);
/* Prints the number right justified within 6 columns */
65
CIT301 STRUCTURED PROGRAMMING
printf("Case 2:%3d\n",9876);
/* Prints the number to be right justified to 3 columns but, there are 4
digits so number is not right justified */
printf("Case 3:%.2f\n",987.6543);
/* Prints the number rounded to two decimal places */
printf("Case 4:%.f\n",987.6543);
/* Prints the number rounded to 0 decimal place, i.e, rounded to integer
*/
printf("Case 5:%e\n",987.6543);
/* Prints the number in exponential notation (scientific notation) */
return 0;
}
Output
Case 1: 9876
Case 2:9876
Case 3:987.65
Case 4:988
Case 5:9.876543e+002
#include <stdio.h>
int main()
{
int a,b;
float c,d;
printf("Enter two intgers: ");
/*Two integers can be taken from user at once as below*/
scanf("%d%d",&a,&b);
printf("Enter integer and floating point numbers: ");
/*Integer and floating point number can be taken at once from user as
below*/
scanf("%d%f",&a,&c);
return 0;
}
Similarly, any number of inputs can be taken at once from user.
SELF-ASSESSMENT EXERCISE
66
CIT301 MODULE 5
67
CIT301 STRUCTURED PROGRAMMING
Solution
1. A and D
2. C and D
3. D
4. A
5. C
4.0 CONCLUSION
Using the printf() function you can output your result, display the output
in a desirable format. It therefore becomes imperative that the
programmer formats the output to his desired format. This is achieved
via some format specifications.
5.0 SUMMARY
In this unit, you have learnt how to format your output to your desired
format. You have also learnt the variations in output for integer and
floats as well as the variations in input for integer and floats.
68
CIT301 MODULE 6
Unit 1 Operators
Unit 2 Overview of Control Statements
UNIT 1 OPERATORS
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
3.1 Arithmetic Operators
3.2 Relational Operators
3.3 Logical Operators
3.4 Bitwise Operators
3.5 Assignment Operators
3.6 Increment and decrement operators
3.7 Conditional operators
3.8 Misc Operators
3.9 Operators Precedence in C
4.0 Conclusion
1.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Increment and decrement operators
Conditional operators
Misc Operators
Operators Precedence in C
69
CIT301 STRUCTURED PROGRAMMING
Define an operator
Use operators in expressions
Mention the various operators applicable to C programming
Describe each of the operators
70
CIT301 MODULE 6
These operators are used to perform logical operations on the given two
variables.
71
CIT301 STRUCTURED PROGRAMMING
Bit wise operators in C language are; & (bitwise AND), | (bitwise OR),
~ (bitwise OR), ^ (XOR), << (left shift) and >> (right shift).
72
CIT301 MODULE 6
73
CIT301 STRUCTURED PROGRAMMING
#include <stdio.h>
int main()
{
int c=2,d=2;
printf(“%d\n”,c++); //this statement displays 2 then, only c incremented
by 1 to 3.
Printf(“%d”,++c); //this statement increments 1 to c then, only c is
displayed.
Return 0;
}
Output
2
4
74
CIT301 MODULE 6
Here, operators with the highest precedence appear at the top of the
table, those with the lowest appear at the bottom. Within an expression,
higher precedence operators will be evaluated first.
SELF-ASSESSMENT EXERCISE
{int x, y;
scanf ( “%d”, &x ) ;
y = ( x> 5 ? 1 : 4 ) ; }
3. Given the mathematical expression: S + 3 x Y – 1, where S = 5 and
Y = 34. Reconstruct the expression in C format and evaluate it.
Reconstruct the express such that the result will be 271
75
CIT301 STRUCTURED PROGRAMMING
Solution
1. What are the operators used in C programming language?
4.0 CONCLUSION
5.0 SUMMARY
In this unit, you have been exposed to the operators used in C programs.
This includes mathematical, logical, relational, bitwise, assignment,
increment and decrement operators etc. These operators are used to
manipulate data. The details of these operators are adequately discussed
within the unit.
76
CIT301 MODULE 6
77
CIT301 STRUCTURED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
3.1 Selection Statements
3.1.1 if Statement
3.1.2 else-if Statement
3.1.3 Nested if-else
3.1.4 switch case
3.2 Iterative Statements
3.2.1 while statement
3.2.2 do-while Loop
3.2.3 for Loop
3.2.4 Nesting of Loops
3.3 Jump Statements
3.3.1 The break statement
3.3.2 The continue Statement
3.3.3 The goto statement
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
78
CIT301 MODULE 6
79
CIT301 STRUCTURED PROGRAMMING
3.1.1 If Statement
The keyword if tells the compiler that what follows is a decision control
instruction. The if statement allows us to put some decision -making into
our programs. A flowchart illustrating the general form of the if
statement is shown below:
Syntax of if statement:
if (condition )
{
Statement 1;
Statement 2;
…………..
…………..
…………..
Statement n;
}
//Rest of the code
80
CIT301 MODULE 6
if (total_purchase>=1000)
{
gift_count++;
printf("You are gifted a pen drive.\n");
}
Programs:
1. Write a program to print a message if negative no is entered.
#include<stdio.h>
int main()
{
int no;
printf("Enter a no : ");
scanf("%d", &no);
if(no<0)
{
printf("no entered is negative");
no = -no;
}
printf("value of no is %d \n",no);
return 0;
}
Output:
Enter a no: 6
value of no is 6
Output:
Enter a no: -2
value of no is 2
81
CIT301 STRUCTURED PROGRAMMING
Output:
Enter 2 nos:
62
quotient is 3
Output: Enter 2 nos:
60
Division is not possible
The group of statements after the if is called an ‘if block’. Similarly, the
statements after the else form the ‘else block’.
Programs:
3. Write a program to check whether the given no is even or odd
#include<stdio.h>
int main()
{
int n;
printf("Enter an integer\n");
scanf("%d",&n);
82
CIT301 MODULE 6
if ( n%2 == 0 )
printf("Even\n");
else
printf("Odd\n");
return 0;
}
Output: Enter an integer 3
Odd
Output: Enter an integer 4
Even
else-if Statement
This sequence of if statements is the most general way of writing a
multi−way decision. The expressions are evaluated in order; if an
expression is true, the statement associated with it is executed, and this
terminates the whole chain. As always, the code for each statement is
either a single statement, or a group of them in braces.
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
83
CIT301 STRUCTURED PROGRAMMING
The last else part handles the ``none of the above'' or default case where
none of the other conditions is satisfied. Sometimes there is no explicit
action for the default; in that case the trailing can be omitted, or it may
be used for error checking to catch an “impossible” condition.
Program
6. The above program can be used as an e.g., here.
#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");
}
}
An entire if-else construct can be written within either the body of the if
statement or the body of an else statement. This is called ‘nesting’ of ifs.
This is shown in the following structure.
if (n > 0)
{
if (a > b)
z = a;
}
else
z = b;
84
CIT301 MODULE 6
Program:
Output
40 is greater than 20
This structure helps to make a decision from the number of choices. The
switch statement is a multi−way decision that tests whether an
expression matches one of a number of constant integer values, and
branches accordingly.
switch( integer expression)
{
case constant 1 : do this;
case constant 2 : do this ;
case constant 3 : do this ;
default : do this ; }
85
CIT301 STRUCTURED PROGRAMMING
main( )
{
int i = 2;
switch ( i )
{
case 1:
printf ( "I am in case 1 \n" ) ;
case 2:
printf ( "I am in case 2 \n" ) ;
case 3:
printf ( "I am in case 3 \n" ) ;
default :
printf ( "I am in default \n" ) ;
}
}
The output of this program would be:
I am in case 2
I am in case 3
I am in default
Here the program prints case 2 and 3 and the default case. If you want
that only case 2 should get executed, it is up to you to get out of the
switch then and there by using a break statement.
main( )
{
int i = 2 ; switch ( i )
{
case 1:
printf ( "I am in case 1 \n" ) ;
break ;
case 2:
printf ( "I am in case 2 \n" ) ;
break ;
case 3:
printf ( "I am in case 3 \n" ) ;
break ;
default:
printf ( "I am in default \n" ) ;
}
}
86
CIT301 MODULE 6
Program
7. Write a program to enter a grade and check its corresponding
remarks.
#include <stdio.h>
int main ()
{
char grade;
printf(“Enter the grade”);
scanf(“%c”, &grade);
switch(grade)
{
case 'A' : printf("Outstanding!\n" );
break;
case 'B' :
printf("Excellent!\n" );
break;
case 'C' : printf("Well done\n" );
break;
case 'D' : printf("You passed\n" );
break;
case 'F' : printf("Better try again\n" );
break;
default : printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
Output
Enter the grade
B
Excellent
Your grade is B
87
CIT301 STRUCTURED PROGRAMMING
The program will repeatedly execute the statement inside the while until
the condition becomes false(0). (If the condition is initially false, the
statement will not be executed.)
The program executes all statements after the while 3 times. These
statements form what is called the ‘body’ of the while loop. The
parentheses after the while contain a condition. As long as this condition
remains true all statements within the body of the while loop keep
getting executed repeatedly.
88
CIT301 MODULE 6
Output:
Enter a number to check if it is a palindrome or not
12321
12321 is a palindrome
Enter a number to check if it is a palindrome or not
12000
12000 is not a palindrome
The body of the do-while executes at least once. The do-while structure
is similar to the while loop except the relational test occurs at the bottom
(rather than top) of the loop. This ensures that the body of the loop
executes at least once. The do-while tests for a positive relational test;
that is, as long as the test is True, the body of the loop continues to
execute.
The format of the do-while is
do
{
block of one or more C statements;
} while (test expression)
89
CIT301 STRUCTURED PROGRAMMING
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
} while(num!=0);
printf("sum=%d",sum);
return 0;
}
Output:
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
Output
Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1
Program
8. Program to count the no of digits in a number
#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
90
CIT301 MODULE 6
scanf("%d", &n);
do
{
n/=10;
/* n=n/10 */
count++;
} while(n!=0);
printf("Number of digits: %d",count);
}
Output
Enter an integer: 34523
Number of digits: 5
The for is the most popular looping instruction. The general form of for
statement is shown below:
for ( initialize counter ; test counter ; Updating counter )
{
do this;
and this;
and this;
}
91
CIT301 STRUCTURED PROGRAMMING
3 27
4 64
5 125
6 216
The first line of the for loop tells us immediately all the information
about the loop parameters: the starting value of num, the final value of
num, and the amount that num increases on each looping
Grammatically, the three components of a for loop are expressions. Any
of the three parts can be omitted, although the semicolons must remain.
Consider the following program:
main( )
{
int i ;
for ( i = 1 ; i<= 10 ; )
{
printf ( "%d\n", i ) ;
i=i+1;
}
}
Here, the increment is done within the body of the for loop and not in
the for statement. Note that in spite of this the semicolon after the
condition is necessary.
Programs:
9. Program to print the sum of the first N natural numbers.
#include <stdio.h>
int main()
{
int n, i, sum=0;
printf("Enter the limit: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
sum = sum +i;
}
printf("Sum of N natural numbers is: %d",sum);
}
Output
Enter the limit: 5 Sum of N natural numbers is 15.
10. Program to find the reverse of a number
#include<stdio.h>
int main()
{
92
CIT301 MODULE 6
int num,r,reverse=0;
printf("Enter any number: ");
scanf("%d",&num);
for(num!=0;num=num/10)
{
r=num%10;
reverse=reverse*10+r;
}
printf("Reversed of number: %d",reverse);
return 0;
}
Output:
Enter any number: 123
Reversed of number: 321
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
93
CIT301 STRUCTURED PROGRAMMING
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside
of any other type of loop. For example, a for loop can be inside a while
loop or vice versa.
Programs: 11. program using a nested for loop to find the prime
numbers from 2 to 20:
#include <stdio.h>
int main ()
{
/* local variable definition */
int i, j;
for(i=2; i<20; i++)
{
for(j=2; j <= (i/j); j++)
if(!(i%j))
break;
// if factor found, not prime
if(j > (i/j))
printf("%d is prime\n", i);
}
return 0; }
Output
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
Programs: 12. Using for loops reproduce the star triangle below
*
***
*****
*******
94
CIT301 MODULE 6
*********
#include <stdio.h>
int main()
{
int row, c, n,I, temp;
printf("Enter the number of rows in pyramid of stars you wish to see ");
scanf("%d",&n);
temp = n;
for ( row = 1 ; row <= n ; row++ )
{
for ( i= 1 ; i< temp ; i++ )
{
printf(" ");
temp--;
for ( c = 1 ; c <= 2*row - 1 ; c++ )
{
printf("*");
printf("\n");
}
}
}
return 0;
}
Output:
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
95
CIT301 STRUCTURED PROGRAMMING
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
10 9 8 7 5 4 3 2 1
The break statement provides an early exit from for, while, and do, just
as from switch. A break causes the innermost enclosing loop or switch
to be exited immediately. When break is encountered inside any loop,
control automatically passes to the first statement after the loop.
In this program when j equals 150, break takes the control outside the
inner while only, since it is placed inside the inner while.
The continue statement is related to break, but less often used; it causes
the next iteration of the enclosing for, while, or do loop to begin. In the
while and do, this means that the test part is executed immediately; in
the for, control passes to the increment step. The continue statement
applies only to loops, not to switch.
96
CIT301 MODULE 6
int i, j ;
for ( i = 1 ; i<= 2 ; i++ )
{
for ( j = 1 ; j <= 2 ; j++ )
{
if ( i == j)
continue ;
printf ( "\n%d %d\n", i, j ) ;
}
}
}
Note that when the value of I equals that of j, the continue statement
takes the control to the for loop (inner) by passing rest of the statements
pending execution in the for loop (inner).
97
CIT301 STRUCTURED PROGRAMMING
Solution
1 Differentiate between if and if else statements in C programming
language using diagram ONLY.
if statement
if else statement
98
CIT301 MODULE 6
Syntax of if statement:
if (condition )
{
Statement 1;
Statement 2;
…………..
…………..
…………..
Statement n;
}
//Rest of the code
4.0 CONCLUSION
C programming language has basically three control structures which
make C qualify as a structured programming language. These structures
include sequence, selection and repetition structure.
5.0 SUMMARY
In this unit, you have learnt Selection (if Statement, else-if Statement,
nested if-else and switch case), iterative (while statement, do-while loop,
for loop, and nesting of loops), jump statements (the break statement,
the continue statement, the goto statement). Details are discussed in the
unit
99
CIT301 STRUCTURED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
3.1 Monolithic Vs Modular Programming:
3.2 Function
3.2.1 Function Declaration OR Function Prototype:
3.2.2 Function Definition:
3.5 User Define Functions Vs Standard Function:
3.5.1 User Define Function:
3.5.2 Standard Function:
3.6 Function Categories
3.6.1 Function with no arguments and no return values:
3.6.2 Function with no arguments and a return value:
3.6.3 Function with arguments and return value:
3.7 Actual Arguments and Formal Arguments
3.7.1 Actual Arguments
3.7.2 Formal Arguments
3.7.3 Basic difference between formal and local
argument
3.7.4 Parameter Passing Techniques
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
100
CIT301 MODULE 7
that specifies the function's name and type signature (arity, data types of
parameters, and return type), but omits the function body.
101
CIT301 STRUCTURED PROGRAMMING
3.2 Function
102
CIT301 MODULE 7
5. Return type denote the type of value that function will return and
return type is optional if omitted it is assumed to be integer by
default.
A function that is declare, calling and define by the user is called user
defined function. Every user define function has three parts as:
1. Prototype or Declaration
2. Calling
3. Definition
There are four main categories of the functions these are as follows:
1. Function with no arguments and no return values.
2. Function with no arguments and a return value.
3. Function with arguments and no return values.
4. Function with arguments and return values.
103
CIT301 STRUCTURED PROGRAMMING
Example:
void link (void) ;
int main ()
{ link ();
}
void link ( void );
{
printf (“ link the file “)
}
Example:
void msg ( int , int );
int main ( )
{
int a,b;
a= 2;
104
CIT301 MODULE 7
b=3;
msg( a, b);
}
void msg ( int a , int b)
{
int s ;
sum = a+b;
printf (“sum = %d” , s ) ;
}
Here calling function of arguments that passed to the called function and
called function return value to calling function.
example:
int msg ( int , int ) ;
int main ( )
{
int a, b;
a= 2;
b=3;
int s = msg (a, b);
printf (“sum = %d” , s ) ;
}
int msg( int a , int b)
{
int sum ;
sum =a+b ;
return (sum);
}
105
CIT301 STRUCTURED PROGRAMMING
Note: Order, number and type of actual argument in the function call
should be matched with the order, number and type of formal arguments
in the function definition.
1. call by value
2. call by reference
Call by value:
Here value of actual arguments is passed to the formal arguments and
operation is done in the formal argument.
Since formal arguments are photo copy of actual argument, any change
of the formal arguments does not affect the actual arguments.
Changes made to the formal argument t are local to block of called
function, so when control back to calling function changes made vanish.
Example:
void swap (int a , int b) /* called function */
{
int t;
t = a;
a=b;
b = t;
}
106
CIT301 MODULE 7
main( )
{
int k = 50, m= 25;
swap( k, m) ; / * calling function */
print (k, m); / * calling function */
}
Output:
50, 25
Explanation:
int k= 50, m=25 ;
Means first two memory space are created k and m , store the values 50
and 25 respectively.
swap (k,m);
When this function is calling the control goes to the called function.
void swap (int a , int b),
k and m values are assigned to the ‘a’ and ‘b’.
then a= 50 and b= 25 ,
After that control enters into the function a temporary memory space ‘t’
is created when int t is executed.
t=a; Means the value of a is assigned to the t , then t= 50.
a=b; Here value of b is assigned to the a, then a= 25;
b=t; Again t value is assigned to the b, then b= 50;
after this control again enters into the main function and execute the
print function print (k,m). it returns the value 50, 25.
NOTE: Whatever change made in called function does not affect the
values in the calling function.
Call by reference:
Here instead of passing value, address or reference are passed. Function
operators or address rather than values. Here, formal arguments are the
pointers to the actual arguments.
Example:
#include<stdio.h>
void add(int *n);
int main()
{
int num=2;
printf(“\n The value of num before calling the function=%d”, num);
add(&num);
printf(“\n The value of num after calling the function = %d”, num);
return 0;
}
void add(int *n)
107
CIT301 STRUCTURED PROGRAMMING
{
*n=*n+10;
printf(“\n The value of num in the called function = %d”, n);
}
Output:
The value of num before calling the function=2
The value of num in the called function=20 The
value of num after calling the function=20
NOTE:
In call by address mechanism whatever change made in called function
affect the values in calling function.
EXAMPLES:
1: Write a function to return larger number between two numbers:
int fun(int p, int q)
{
int large;
if(p>q)
{
large = p;
}
else
{
large = q;
}
return large;
}
SELF-ASSESSMENT EXERCISE
Solution
1. What do you mean by function?
A function is a block of statements that performs a specific task.
Let's say you are writing a C program and you need to perform a
same task in that program more than once. In such case you have
two options:
a) Use the same set of statements every time you want to perform
the task.
b) Create a function to perform that task, and just call it every time
you need to perform that task.
2. Why is function used in a program?
It provides modularity to the program.
Easy code reusability. You just have to call the function by its
name to use it.
In case of large programs with thousands of code lines,
debugging and editing becomes easier if you use functions.
A function is independent:
It is “completely” self-contained.
It can be called at any place in the code and can be ported to
another program
Reusable: Use existing functions as building blocks for new
programs
Readable - more meaningful
procedural abstraction: hide internal details
factoring of code- divide and conquer
109
CIT301 STRUCTURED PROGRAMMING
WHILE
The call by Address method of passing arguments to a function copies
the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the
call.2. Why function is used in a program?
4.0 CONCLUSION
5.0 SUMMARY
In this unit, you have learnt about functions. The difference between
monolithic and modular programming has been highlighted. The
advantages of modular programming and disadvantages of monolithic
programming are also outlined. You have also learnt the difference
between user define function and standard function, function declaration
or function prototype, its syntax, function categories etc.
110
CIT301 MODULE 7
UNIT 2 ARRAYS
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
3.1 Arrays
3.1.1 One Dimensional Array
3.1.2 Declaration One Dimensional Array
3.1.3 Initialization of One-Dimensional Array
3.1.4 Array Processing
3.1.5 Two Dimensional Arrays
3.1.6 Declaration of Two-Dimensional Arrays
3.1.7 Initialization of one-Dimensional Array
3.1.8 Multidimensional Array
3.1.9 Arrays Using Functions
3.1.10 Passing Whole 1-D array to a Function
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
Describe an array
Differentiate between one-dimensional and a two-dimensional
array
Initialize one-dimensional, two-dimensional and multi-
dimensional arrays
State the syntax of array declaration
111
CIT301 STRUCTURED PROGRAMMING
3.1 Arrays
A data structure is the way data is stored in the machine and the
functions used to access that data. An easy way to think of a data
structure is a collection of related data items. An array is a data structure
that is a collection of variables of one type that are accessed through a
common name. Each element of an array is given a number by which we
can access that element which is called an index. It solves the problem
of storing a large number of values and manipulating them.
Syntax:
data_typearray_name[size];
Example:
int age[100];
float sal[15];
char grade[20];
Here age is an integer type array, which can store 100 elements of
integer type. The array sal is floating type array of size 15, can hold float
values. Grade is a character type array which holds 20 characters.
112
CIT301 MODULE 7
Syntax:
data_typearray_name[size]={value1, value2,……..valueN};
Example:
int marks[5]={10,2,0,23,4};
The values of the array elements after this initialization are:
marks[0]=10, marks[1]=2, marks[2]=0, marks[3]=23, marks[4]=4
Note:
1. In 1-D arrays it is optional to specify the size of the array. If size is
omitted during initialization, then the compiler assumes the size of array
equal to the number of initializers.
Example:
int marks[ ]={10,2,0,23,4};
Here the size of array marks is initialized to 5.
2. We can’t copy the elements of one array to another array by simply
assigning it.
Example:
int a[5]={9,8,7,6,5};
int b[5];
b=a; //not valid
we have to copy all the elements by using for loop.
For processing arrays, we mostly use for loop. The total no. of passes is
equal to the no. of elements present in the array and in each pass one
element is processed.
Example:
#include<stdio.h>
main()
{
113
CIT301 STRUCTURED PROGRAMMING
int a[3], i;
for(i=0;i<=2;i++) //Reading the array values
{
printf(“enter the elements”);
scanf(“%d”,&a[i]);
}
for(i=0;i<=2;i++) //display the array values
{
printf(“%d”,a[i]);
printf(“\n”);
}
}
{
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i< n; ++i)
scanf("%d", &number[i]); for (i = 0; i< n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a =number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i< n; ++i)
printf("%d\n", number[i]);
}
The syntax is same as for 1-D array but here 2 subscripts are used.
Syntax:
data_typearray_name[rowsize][columnsize];
Example:
int a[4][5];
This is a 2-D array of 4 rows and 5 columns. Here the first element of
the array is a[0][0] and last element of the array is a[3][4] and total [Link]
elements is 4*5=20.
115
CIT301 STRUCTURED PROGRAMMING
int m[4][3]={{11},{12,13},{14,15,16},{17}};
The values are assigned as:
Note:
In 2-D arrays it is optional to specify the first dimension but the second
dimension should always be present.
Example:
int m[][3]={
{1,10},
{2,20,200},
{3},
{4,40,400} };
116
CIT301 MODULE 7
Here the first dimension is taken 4 since there are 4 roes in the
initialization list. A 2-D array is known as matrix.
Processing:
For processing of 2-D arrays we need two nested for loops. The outer
loop indicates the rows and the inner loop indicates the columns.
b) Displaying values of a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
printf(“%d”,a[i][j]);
Example 1: Write a C program to find sum of two matrices
#include <stdio.h>
#include<conio.h>
void main()
{
float a[2][2], b[2][2], c[2][2];
int i,j;
clrscr();
printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If there
is an array of 'n' dimension, 'n' numbers of loops are needed for inserting
data to array.*/
for(i=0;i<2;I++)
for(j=0;j<2;j++)
{
scanf("%f",&a[i][j]);
}
printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
scanf("%f",&b[i][j]);
}
/* accessing corresponding elements of two arrays. */
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
/* Sum of corresponding elements of two arrays. */
}
117
CIT301 STRUCTURED PROGRAMMING
for(j=0;j<col2;j++)
scanf(“%d”,&mat2[i][j]);
}
for(i=0;i<row3;i++)
{
for(j=0;j<col3;j++)
{
mat3[i][j]=0;
for(k=0;k<col3;k++)
mat3[i][j] +=mat1[i][k]*mat2[k][j];
}
}
printf(“\n The elements of the product matrix are”):
for(i=0;i<row3;i++)
{
printf(“\n”);
for(j=0;j<col3;j++)
printf(“\t %d”, mat3[i][j]);
} return 0;
}
Output:
Enter the number of rows in the first matrix: 2
Enter the number of columns in the first matrix: 2
Enter the number of rows in the second matrix: 2
Enter the number of columns in the second matrix: 2
Enter the elements of the first matrix
1234
Enter the elements of the second matrix
5678
The elements of the product matrix are
19 22
43 50
119
CIT301 STRUCTURED PROGRAMMING
Output
Enter the rows and columns of matrix:
2 3
Enter the elements of matrix:
Enter elements a11: 1
Enter elements a12: 2
Enter elements a13: 9
Enter elements a21: 0
Enter elements a22: 4
Enter elements a23: 7
Entered matrix: 1 2 9 0 4 7
ranspose of matrix: 1 0 2 4 9 7
120
CIT301 MODULE 7
Example:
#include<stdio.h>
main()
{
int d[5];
121
CIT301 STRUCTURED PROGRAMMING
int i;
for(i=0;i<5;i++)
{
d[i]=i;
}
for(i=0;i<5;i++)
{
printf(“value in array %d\n”,a[i]);
}
}
Example:
#include<stdio.h>
void check(int);
void main()
{
int a[10],i;
clrscr();
printf(“\n enter the array elements:”);
for(i=0;i<10;i++)
{
scanf(“%d”,&a[i]);
check(a[i]);
}
void check(int num)
{
if(num%2==0)
printf(“%d is even\n”,num);
else
printf(“%d is odd\n”,num);
}
122
CIT301 MODULE 7
Example:
C program to pass a single element of an array to function
#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main()
{
int c[]={2,3,4};
display(c[2]); //Passing array element c[2] only.
return 0; }
Output
234
Example 1:
#include<stdio.h>
main()
{
int i, a[6]={1,2,3,4,5,6};
func(a);
printf(“contents of array:”);
for(i=0;i<6;i++) printf(“%d”,a[i]);
printf(”\n”);
}
func(int val[])
123
CIT301 STRUCTURED PROGRAMMING
{
int sum=0,i;
for(i=0;i<6;i++)
{
val[i]=val[i]*val[i]; sum+=val[i];
}
printf(“the sum of squares:%d”, sum);
}
Output
contents of array: 1 2 3 4 5 6
the sum of squares: 91
Example 2:
Write a C program to pass an array containing age of person to a
function. This function should find average age and display the average
age in main function.
#include <stdio.h>
float average(float a[]);
int main()
{
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
return 0;
}
float average(float a[])
{
int i;
float avg, sum=0.0;
for(i=0;i<6;++i)
{
sum+=a[i];
}
avg =(sum/6);
return avg;
}
Output
Average age= 27.08
Further Examples:
1. Write a program to find the largest of n numbers and its location in
an array.
#include <stdio.h>
124
CIT301 MODULE 7
#include<conio.h>
void main()
{
int array[100], maximum, size, c, location = 1;
clrscr();
printf("Enter the number of elements in array\n");
scanf("%d", &size);
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]); maximum = array[0];
for (c = 1; c < size; c++)
{
if (array[c] > maximum)
{
maximum = array[c];
location = c+1;
}
}
printf("Maximum element is present at location %d and it's value is
%d.\n", location, maximum);
getch();
}
Output:
Enter the number of elements in array 5
Enter 5 integers
2
4
7
9
1
Output:
Enter the number of digits:
3
Enter the 0th digit:
5
Enter the 1th digit:
4
Enter the 2th digit:
3
The number is: 543
3. Matrix addition:
#include <stdio.h> #include<conio.h>
void main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
clrscr();
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
scanf("%d", &second[c][d]);
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d];
printf("Sum of entered matrices:-\n");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
126
CIT301 MODULE 7
printf("%d\t", sum[c][d]);
printf("\n");
}
getch();
}
Output:
Enter the number of rows and columns of matrix
2 2
Enter the elements of first matrix
12 34
Enter the elements of second matrix
56 21
Sum of entered matrices:- 6 8 5 5
SELF-ASSESSMENT EXERCISE
Solution:
1. Compute sum of elements of an array in a C program?
//let's assume the maximum array size as 100.
//initialize sum as 0. Otherwise, it will take some garbage value.
int arr[100], size, i, sum = 0;
return 0;
}
127
CIT301 STRUCTURED PROGRAMMING
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
4.0 CONCLUSION
5.0 SUMMARY
129
CIT301 STRUCTURED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
3.1 String
3.2 Reading strings
3.3 Writing string
3.4 Common Functions in String
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
Define a string
Differentiate between a string and a character
Manipulate string
Mention some commonly used string input/output library
functions
Read and write string
Declare a string variable
130
CIT301 MODULE 7
3.1 String
character T w o \0
ASCII code 116 119 41 0
– ourstr[3] is ‘\0’
– ourstr[4] is ‘\0’
– ourstr[5] is ‘\0’
Example:
char str[10];
printf(“Enter a string\n”);
scanf(“%s”,str);
Example:
char str[10];
printf(“Enter a string\n”);
gets(str);
132
CIT301 MODULE 7
The string can also be read by calling the getchar() repeatedly to read a
sequence of single characters (unless a terminating character is
encountered) and simultaneously storing it in a character array as
follows:
int i=0;
char str[10],ch;
getchar(ch);
while(ch!=’\0’)
{
str[i]=ch; // store the read character in str
i++;
getch(ch); // get another character
}
str[i]=’\0’; // terminate str with null character
Example:
printf(“%5.3s”,str);
This statement would print only the first three characters in a total field
of five charaters; also these three characters are right justified in the
allocated width.
The next method of writing a string is by using the puts() function. The
string can be displayed by writing:
puts(str);
{
putchar(str[i]); // print the character on the screen
i++;
}
Example:
Read and display a string
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(“\n Enter a string:\n”);
gets(str);
scanf(“The string is:\n”);
puts(str);
getch(); }
Output:
Enter a string:
vssut burla
The string is:
vssut burla
Example:
char mystr[10];
mystr = “Hello”; // Error! Illegal!!! Because we are assigning the
value to mystr which is not possible in case of an string. We can only
use "=" at declarations of C-String.
strcpy(mystr, “Hello”);
It sets value of mystr equal to “Hello”.
strcmp():
It is used to compare the contents of the two strings. If any mismatch
occurs then it results the difference of ASCII values between the first
occurrence of 2 different characters.
Syntax:
int strcmp(string 1, string 2);
Example:
char mystr_a[10] = “Hello”;
char mystr_b[10] = “Goodbye”;
– mystr_a == mystr_b; // NOT allowed!
The correct way is
if (strcmp(mystr_a, mystr_b ))
printf ("Strings are NOT the same.");
else
printf( "Strings are the same.");
Here it will check the ASCII value of H and G i.e, 72 and 71 and return
the diference 1.
strcat():
It is used to concatenate i.e, combine the content of two strings.
Syntax:
strcat(string 1, string 2);
Example:
char fname[30]={“bob”};
char lname[]={“by”};
printf(“%s”, strcat(fname,lname));
Output:
bobby.
strlen():
It is used to return the length of a string.
135
CIT301 STRUCTURED PROGRAMMING
Syntax:
int strlen(string);
Example:
char fname[30]={“bob”};
int length=strlen(fname);
It will return 3
strchr():
It is used to find a character in the string and returns the index of
occurrence of the character for the first time in the string.
Syntax:
strchr(cstr);
Example:
char mystr[] = "This is a simple string";
char pch = strchr(mystr,‘s’);
The output of pch is mystr[3]
strstr():
It is used to return the existence of one string inside another string and it
results the starting index of the string.
Syntax:
strstr(cstr1, cstr2);
Example:
Char mystr[]="This is a simple string";
char pch = strstr(mystr, “simple”);
here pch will point to mystr[10]
136
CIT301 MODULE 7
NOTE:
Character arrays are known as strings.
SELF-ASSESSMENT EXERCISE
i. What is a string in c?
ii. Show 2 different methods of initializing character array vowel
with the string of vowels “AEIOU”.
iii. Outline the commonly used string functions in C. Put your
answer in tabular format indicating type, method and description.
Solution
1 What is a string in c?
The string in C programming language is actually a one-
dimensional array of characters which is terminated by a null
character '\0'. Thus, a null-terminated string contains the
characters that comprise the string followed by a null.
2 Show 2 different methods of initializing character array vowel
with the string of vowels “AEIOU”.
Method1: char vowels [6] = “AEIOU”
Method 2: char vowels [6] = {'A','E','I','O','U','N','\0'}; // NULL
character '\0' is required at end in this declaration
137
CIT301 STRUCTURED PROGRAMMING
4.0 CONCLUSION
5.0 SUMMARY
In this unit, you have learnt about string, how to declare a string, how to
read and write a string, how to manipulate a string, how to differentiate
between a string and a character, common function in string (such as
strcpy(s1, s2), strcmp(s1, s2), strlen(s) etc). Examples are given to
illustrate string manipulation and functions.
138
CIT301 MODULE 8
CONTENTS
1.0 Introduction
2.0 Intended Learning Outcomes (ILOs)
3.0 Main Content
3.1 Structure
3.2 Pointers
3.3 Pointers and Addresses
3.4 Pointers and Function Arguments
3.5 Pointers and Arrays
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
139
CIT301 STRUCTURED PROGRAMMING
3.1 Structure
A Structure is a user defined data type that can store related information
together. The variable within a structure is of different data types and
each has a name that is used to select it from the structure. C arrays
allow you to define type of variables that can hold several data items of
the same kind, but structure is another user defined data type available
in C programming, which allows you to combine data items of different
kinds.
Title
Author
Subject
Book ID
Structure Declaration:
It is declared using a keyword struct followed by the name of the
structure. The variables of the structure are declared within the structure.
Example:
Struct struct-name
{
data_type var-name;
data_type var-name;
};
Structure Initialization:
Assigning constants to the members of the structure is called initializing
of structure. Syntax:
struct struct_name
{
data _type member_name1;
data _type member_name2;
} struct_var={constant1,constant2};
Accessing the members of a structure
A structure member variable is generally accessed using a ‘.’ operator.
Syntax:
strcut_var.
member_name;
140
CIT301 MODULE 8
[Link]=01;
[Link]=”Rahul”;
To input values for data members of the structure variable stud, can be
written as,
scanf(“%d”,&[Link]);
scanf(‘’%s”,&[Link]);
3.2 Pointers
141
CIT301 STRUCTURED PROGRAMMING
The unary operator & gives the address of an object, so the statement
p = &c; assigns the address of c to the variable p, and p is said to ``point
to'' c. The &operator only applies to objects in memory: variables and
array elements. It cannot be applied to expressions, constants, or register
variables. The unary operator * is the indirection or dereferencing
operator; when applied to a pointer, it accesses the object the pointer
points to. Suppose that x and y are integers and ip is a pointer to int.
This artificial sequence shows how to declare a pointer and how to use
& and *:
int x = 1, y = 2, z[10];
int *ip;
ip = &x;
y = *ip;
*ip = 0;
ip = &z[0];
The declaration of x, y, and z are what we've seen all along. The
declaration of the pointer ip.
int *ip;
is intended as a mnemonic; it says that the expression *ip is an int. The
syntax of the declaration for a variable mimics the syntax of expressions
in which the variable might appear. This reasoning applies to function
declarations as well. For example,
double *dp, atof(char *);
says that in an expression *dp and atof(s) have values of double, and
that the argument of atof is a pointer to char. You should also note the
implication that a pointer is constrained to point to a particular kind of
object: every pointer points to a specific data type. If ip points to the
integer x, then *ip can occur in any context where x could, so
*ip = *ip + 10;
increments *ip by 10. The unary operators * and & bind more tightly
than arithmetic operators, so the assignment
y = *ip + 1
takes whatever ip points at, adds 1, and assigns the result to y, while
*ip += 1
increments what ip
points to, as do
++*ip and (*ip)++
The parentheses are necessary in this last example; without them, the
expression would increment ip instead of what it points to, because
142
CIT301 MODULE 8
Because of call by value, swap can't affect the arguments a and b in the
routine that called it. The function above swaps copies of a and b. The
way to obtain the desired effect is for the calling program to pass
pointers to the values to be changed:
swap(&a, &b);
Since the operator & produces the address of a variable, &a is a pointer
to a. In swap itself, the parameters are declared as pointers, and the
operands are accessed indirectly through them.
void swap(int *px, int *py) /* interchange *px and *py */
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
143
CIT301 STRUCTURED PROGRAMMING
Each call sets array[n] to the next integer found in the input and
increments n. Notice that it is essential to pass the address of array[n] to
getint. Otherwise there is no way for getint to communicate the
converted integer back to the caller. Our version of getint returns EOF
for end of file, zero if the next input is not a number, and a positive
value if the input contains a valid number.
#include <ctype.h>
int getch(void);
void ungetch(int);
int getint(int *pn)
{
int c, sign;
while (isspace(c = getch()));
if (!isdigit(c) && c != EOF&& c != '+' && c != '-')
{
ungetch(c);
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
c = getch();
for (*pn = 0; isdigit(c), c = getch())
*pn = 10 * *pn + (c - '0');
*pn *= sign;
if (c != EOF)
ungetch(c);
return c;
}
144
CIT301 MODULE 8
Rather more surprising, at first sight, is the fact that a reference to a[i]
can also be written as *(a+i). In evaluating a[i], C converts it to *(a+i)
immediately; the two forms are equivalent. Applying the operator & to
both parts of this equivalence, it follows that &a[i] and a+i are also
identical: a+i is the address of the i-th element beyond a. As the other
side of this coin, if pa is a pointer, expressions might use it with a
subscript; pa[i] is identical to *(pa+i). In short, an array-and-index
expression is equivalent to one written as a pointer and offset. There is
one difference between an array name and a pointer that must be kept in
mind. A pointer is a variable, so pa=a and pa++ are legal. But an array
145
CIT301 STRUCTURED PROGRAMMING
name is not a variable; constructions like a=pa and a++ are illegal.
When an array name is passed to a function, what is passed is the
location of the initial element. Within the called function, this argument
is a local variable, and so an array name parameter is a pointer, that is, a
variable containing an address. We can use this fact to write another
version of strlen, which computes the length of a string.
int strlen(char *s)
{
int n;
for (n = 0; *s != '\0', s++)
n++;
return n;
}
f(&a[2])and f(a+2)
both pass to the function f the address of the subarray that starts at a[2].
Within f, the parameter declaration can read
f(int arr[])
{ ... } or
f(int *arr) { ... }
146
CIT301 MODULE 8
SELF-ASSESSMENT EXERCISE
Solution
1. What is a structure in C programming language?
A structure is a key word that create user defined data type in C.
A structure in C Programming language is a group of variables of
different data types represented by a single name. It Allows us to
store a collection of different data types in one memory location
with one name. Each element of a structure is called a member.
1 Declare a structure in C with the flowing members: Employee
name, identification number, salary.
struct employee Name { char name[50];
int idNo;
float salary; };
3 Declare a pointer for each of the following integer, double, float
and character. Use comment to document your declarations.
4.0 CONCLUSION
5.0 SUMMARY
In this unit, you have learnt about structure and pointers. You have been
exposed to how to declare a structure, how to initialize a structure, how
to declare a pointer variable, how to dereference a pointer. You have
also learnt about pointers and addresses, pointers and functions
arguments, pointers and arrays etc.
147
CIT301 STRUCTURED PROGRAMMING
148