Final Notes C Programming
Final Notes C Programming
C PROGRAMMING
1201
1 C PROGRAMMING (1201)
AIM:
To provide the student with a comprehensive understanding of basic
programming skills.
MODULE OBJECTIVES
By the end of the course students should be able to:
TOPICS TO BE COVERED
3 C PROGRAMMING (1201)
Contents
AIM: ............................................................................................................................................................... 1
MODULE OBJECTIVES .................................................................................................................................... 1
TOPICS TO BE COVERED ................................................................................................................................ 2
1. CHAPTER ONE ........................................................................................................................................7
1.1 OBJECTIVES ....................................................................................................................................8
1.2 C PROGRAMMING ......................................................................................................................... 9
1.2.0 C BASICS ........................................................................................................................................9
1.2.1 WHY C? ......................................................................................................................................... 9
1.2.2 Applications of C Programming ....................................................................................................9
1.2.4 Programming languages .............................................................................................................10
1.2.5 LANGUAGES ................................................................................................................................10
1.2.6 COMPILER ...................................................................................................................................11
1.3 WHAT IS C PROGRAMMING? ............................................................................................................ 12
1.3.1 C PROGRAM ................................................................................................................................12
1.3.2 Developing a C program ............................................................................................................. 12
1.3.3 Basics of C programming ............................................................................................................13
1.4.1 C PROGRAMMING BASICS ..........................................................................................................14
1.4.2 C BASICS CODING GROUND ........................................................................................................14
1.4.5 C program ................................................................................................................................... 15
1.5 CONSTANTS ....................................................................................................................................... 16
1.5.1 Syntax to show the use of constants. .........................................................................................17
1.6 Files in C language ............................................................................................................................. 18
1.6.1 Header file .................................................................................................................................. 18
1.7 BASIC FUNCTIONS IN C PROGRAMMING ...................................................................................... 19
1.7.1 DESIGNING YOUR FIRST PROGRAM ........................................................................................... 23
1.8 DATA TYPES AND VARIABLES ........................................................................................................ 25
1.8.1 INPUT AND OUTPUT FUNCTIONS ...............................................................................................28
1.8.2 Keywords .................................................................................................................................... 30
1.8.3 Variable name ............................................................................................................................ 31
1.8.4 Rules for constructing variable names .......................................................................................32
1.9 GETCHAR () FUNCTION ...................................................................................................................... 33
4 C PROGRAMMING (1201)
[Link] ONE
INTRODUCTION TO:
8 C PROGRAMMING (1201)
1.1 OBJECTIVES
1.2 C PROGRAMMING
C is a programming language.
Designed and written by a man named Dennis Ritchie.
It replaced languages like FOTRAN, PASCAL etc.
Became popular because it is reliable, simple and easy to use.
Program –any piece of code written to perform a specific task.
1.2.0 C BASICS
1.2.1 WHY C?
Easy to learn
Structured language
It produces efficient programs
Can handle low level activities
Can be compiled on a variety of computer platforms
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
C
C++
Java
C#
Python
Visual basic
Html
Pearl etc.
1.2.4 LANGUAGES
11 C PROGRAMMING (1201)
1.2.6 COMPILER
• It is a software which is used to convert a high level language into a machine level
language.
• Examples of C compilers
-code blocks
-visual studio
-dev cpp
-turbo cpp etc.
12 C PROGRAMMING (1201)
1.3.1 C PROGRAM
1. add.c –this stage is called pre-processing
2. [Link]-assembly file
3. [Link]-machine language file
4. [Link]-executable file
It is case sensitive.
White space not important.
End statement with a;
A block of code defined with { }
A C program basically consists of the following parts −
-Pre-processor Commands
-Functions
-Variables
-Statements & Expressions
-Comments
14 C PROGRAMMING (1201)
1.4 C BASICS
• The first line of the program #include <stdio.h> is a pre-processor command, which tells
a C compiler to include stdio.h file before going to actual compilation.
• The next line int main () is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the program.
• The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
• The next line return 0; terminates the main () function and returns the value 0.
[Link]
15 C PROGRAMMING (1201)
1.4.5 C PROGRAM
1.5 CONSTANTS
Constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are enumeration constants as
well.
Constants are treated just like regular variables except that their values cannot be
modified after their definition.
\n Newline. This will place a cursor on the beginning of the second line.
\a Alert. This will signify alert sign or sound without changing the position of cursor
17 C PROGRAMMING (1201)
OUTPUT
18 C PROGRAMMING (1201)
Main.c – c files
Add.h –header files
[Link]-assembly files
Main Function
main () signifies the entry point of our program.
C is case sensitive i.e. it requires small letters.
In c programming any word which is followed by ( ) or (…) is a function.
Main is a keyword.
Output function
• printf is an output function.
Syntax:
printf(“ my first program in C);
Input functions
scanf is used to get input data from the keyboard.
It is an input function
scanf (“%d”, &data)
%c –specifies data type to be captured.
&-specifies that the captured data is to be stored in memory.
Data-is the memory location to store captured letter or character.
1. Creating a program
2. Preprocessing and Compiling
3. Linking
4. Loading
5. Execution
20 C PROGRAMMING (1201)
1. CREATING A PROGRAM
This is the first step involved in writing a C program which is accomplished with an editor
program such as code blocks. C program file names have .c extension.
When your program is ready it needs to be compiled with the help of a compiler. The compiler
translates the C program into machine language code.
Before compiling a program preprocessor program executes automatically obeying the special
commands from preprocessor directives
3. LINKING.
In this step, linker links the code to missing functions. For example, your program may contain
standard library functions that are defined elsewhere.
4. LOADING
The next step of program development is called loading. In this step, loader loads the compiled
program into computer memory for execution.
5. EXECUTION
Finally, the computer executes the program that is loaded in computer’s memory.
21 C PROGRAMMING (1201)
22 C PROGRAMMING (1201)
Line 1:
The first line of the program begins with /* and ends with */ which represents that any text
written between these two symbols is a comment.
Comments do not affect program while running because C compiler ignores the comments and
programmers use these comments for the documentation of the program.
Line 2:
#include <stdio.h>
This is the directive to the C Preprocessor (You might wonder what these words like
preprocessor and directives are but don’t worry these things will be crystal clear after going
through next chapters).
Lines beginning with # are called preprocessor directives and this specific line tells
preprocessor to include the contents of standard input/output header file (stdio.h) in the
program while the program is being compiled.
Line 3:
int main ( )
This is the main functions of the program which is part of every C program.
23 C PROGRAMMING (1201)
C programs can have multiple functions which are also called the building blocks, however, one
of the function should be main.
The code of the function is written between the curly braces and in this program also the body
of the function is enclosed by the braces in line 4 and 7.
Line 5:
This is the standard output functions which instruct the computer to print anything written
between the quotes (” ..text..”).
This entire line including the printf, its arguments within the parenthesis and the semicolon is
called a statement.
Line 6:
return 0;
Moreover, it signifies the termination of the function main returning the integer value 0.
24 C PROGRAMMING (1201)
Let’s do it!
25 C PROGRAMMING (1201)
Data type
Reserved words which tells us about:
-the size of data
-type of data
-range of values which can be acceptable to data item
Data types are names or labels which are used to define the kind of data being stored or
manipulated. In any programming language, data type specifies the range of values that
a variable can hold and how this information is stored in the memory heap.
integer type
Character type
Function
Pointer
Structure
• %c-character
• %d-integer(whole number + or -)
• %f-float(decimal)
• %s-string(collection of characters)
Let’s do it!
29 C PROGRAMMING (1201)
•
30 C PROGRAMMING (1201)
1.8.2 KEYWORDS
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names.
SimpleTip:
Variable initializing
Initialization is assigning a value to a variable.
Since C is case sensitive language variable name written in uppercase will differ from
lowercase.
Syntax
int y=15; value is 15
y is the variable name
Data type
15 is a value to be stored in y.
33 C PROGRAMMING (1201)
Putchar ()
• Displays a character to the output.
35 C PROGRAMMING (1201)
1.12.2 ALGORITHM
a) Design eco cash page 3 using the output functions and constants you have learnt.[10]
b) Write a program that prompts a user to enter character, integer, float.[10]
c) Write a C program to accept 2 integer values from the keyboard then calculate the
product of these 2 integers and display the output. [10]
Output of the form:
Enter first number y
Enter second number x
Product is z
41 C PROGRAMMING (1201)
2.1 OBJECTIVES
2.1.1 OPERATORS
Arithmetic operators
Assignment operators
Relational operators
Logical operators
Advanced logical operators
Bitwise operators
Increment or decrement operators
Ternary operators
45 C PROGRAMMING (1201)
Addition operator +
• Used for the addition of operands to give the sum.
a + b =sum;
If a=3 and b=4 and the sum is 7
Subtraction operator -
• Used to find the difference between operands
a –b=difference;
46 C PROGRAMMING (1201)
OR |
Will return a high or a one when one of the inputs is a one.
a | b =z;
If a =10 b=7 then z= 15
10 = 1 0 1 0
7= 0 1 1 1
1 11 1
z=15
48 C PROGRAMMING (1201)
NOT!
Inverts the input
a=1 then the output z is 0
EX OR ^
Will give a one when both inputs are the same
a ^ b =z;
If a =10 b=3 then z= 5
10 = 1 0 1 0
7= 0 0 1 1
0110
49 C PROGRAMMING (1201)
Example
a=2;
b=3;
if (a>b) // condition
{
printf (“open door”);
}
x= x+y
Two operators
Two machine cycles
Consumes more time
Example
x= x+y
If x=5 y=3
Then x on the left side is 8
x= x-y
Then x on the left side is 2
SUMMARY
2.7 INCREMENTAL/DECREMENTAL
Example 1
int x;
x=5;
x++;
After operation x=6
Example 2
int x;
x=5;
x--;
After operation x=4
• Pre increment ++x
Will increment after operation
• Post increment x++
Will increment before operation
• Pre decrement --x
Will decrement after operation
• Post decrement x--
Will decrement before operation
55 C PROGRAMMING (1201)
• | OR
• ! NOT
• ^ Ex OR
• << logical left shift
• >> logical right shift
• ~ compliment
56 C PROGRAMMING (1201)
Syntax
x = exp1? a: b
Here, if exp1 is non zero i.e. TRUE then the value of a will be assigned to x and if exp1 is zero
i.e. FALSE then the value of b is assigned to x.
a) operator
b) Operand [4]
2. Outline the use of each of the seven operators you have learnt. [8]
3. Design seven programs to show the functionality of the seven operators you have learnt. [40]
59 C PROGRAMMING (1201)
[Link] THREE
CONTROL STATEMENTS
60 C PROGRAMMING (1201)
3.1 OBJECTIVES
Conditional statements
If
If else
else if
switch
62 C PROGRAMMING (1201)
3.2.1 IF STATEMENT
Syntax
If (…….)
{
Statement;
}
If the condition is true it will execute the block of code.
If the condition is false the program goes to the end of the block.
63 C PROGRAMMING (1201)
OUTPUT
64 C PROGRAMMING (1201)
3.2.2 IF ELSE
Syntax
If (condition)
{
Statement 1….condition is true the if block is executed
}
else
{
Statement 2…. condition is false the else block is executed
}
65 C PROGRAMMING (1201)
IF ELSE
OUTPUT
66 C PROGRAMMING (1201)
3.3.3 ELSE IF
The if (condition) // will be executed if the condition is true it will execute the block of code
and ignore all the else if blocks and the else
{
Statement 1
}
else if (condition) // the else if block is executed if all the above conditions are false
{
Statement 2
}
else if (condition)
{
Statement 3
}
67 C PROGRAMMING (1201)
Let’s do it!
Question
Given a table below design a suitable program
TEMPERATURE CONDITION
SOLUTION
69 C PROGRAMMING (1201)
3.2.4 SWITCH
Used when we have multiple options and we need to perform a different task for each
option.
It is faster than if else but slower than a loop.
Syntax
switch (n)
{
case constant 1:
//code to be executed if n is equal to constant
break;
case constant 2:
//code to be executed if n is equal to constant
break;
case constant n:
//code to be executed if n is equal to constant
break;
default:
//code to executed if it does not match any constant
• The break statement is used to prevent the code running into the next case.
70 C PROGRAMMING (1201)
Question
Write a program to display a number entered from keyboard using switch statement.
The number should be in range 1-5.
71 C PROGRAMMING (1201)
SOLUTION
72 C PROGRAMMING (1201)
Let’s do it!
73 C PROGRAMMING (1201)
CONDITIONAL SUMMARY
74 C PROGRAMMING (1201)
Looping statements
While
Do while
for
75 C PROGRAMMING (1201)
3.3.2 Do while
It is more like a while statement except that it test the condition at the end of the loop
body.
The first execution of the loop is done without checking the body.
Syntax
do
{
………..
Increment/decrement;
}
while (condition);
77 C PROGRAMMING (1201)
Let’s do it!
78 C PROGRAMMING (1201)
Syntax
for (initial value; condition; increment/decrement)
{
…….
}
79 C PROGRAMMING (1201)
In the above example, counter is the control variable and counter = 1 is the first statement
which initializes counter to 1.
The second expression, counter <= 5 is the loop continuation condition which repeats the loop
till the value of counter exceeds 5.
LOOP PROGRAMS
While program
OUTPUT
82 C PROGRAMMING (1201)
Do while program
83 C PROGRAMMING (1201)
Lets do it!
85 C PROGRAMMING (1201)
In while loop
87 C PROGRAMMING (1201)
In do while loop
In for loop
88 C PROGRAMMING (1201)
3.4.2 CONTINUE
Unlike the break statement, with continue the program will not move out of current
running loops.
Program will skip all statements below continue inside a loop.
In while loop
89 C PROGRAMMING (1201)
In do while loop
In for loop
90 C PROGRAMMING (1201)
91 C PROGRAMMING (1201)
16-30 C
31-45 B
46 and above A
92 C PROGRAMMING (1201)
[Link] FOUR
94 C PROGRAMMING (1201)
4.1 OBJECTIVES
4.2 FUNCTIONS
A function is an independent block of code which can exist outside the main function.
Used to manage our code
This is done by allocating specific tasks to modules outside the main
Functions enable us to put a specific code inside more than one .c file
Comprise of three stages
i) Function prototype
ii) Function call
ii) Function definition
Declare variables if any
Variables declared inside a function are called local variables.
Thus local variables are invisible to other functions.
Variables visible to more than one function are called global variables
96 C PROGRAMMING (1201)
Syntax
return type function name (arguments/parameters)
{
…..
}
Example
void add (int x , int y)
{
…..
}
Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
Function Name − this is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
Function Body − the function body contains a collection of statements that define what
the function does.
97 C PROGRAMMING (1201)
CODING GROUND
Use the link below to enhance your understanding on functions.
[Link]
FUNCTION CALL
Here, int before function name indicates that this function returns integer value to the caller
while int inside parentheses indicates that this function will receive an integer value from caller.
FUNCTION DEFINITION
A function definition provides the actual body of the function.
100 C PROGRAMMING (1201)
RETURN STATEMENT
Return statement returns the value and transfer control to the caller.
101 C PROGRAMMING (1201)
Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of code.
Local variables are not known to functions outside their own. The following example
shows how local variables are used. Here all the variables a, b, and c are local to main ()
function.
CODING GROUND
Use the link below.
[Link]
Global variables are defined outside a function, usually on top of the program.
Global variables hold their values throughout the lifetime of your program and they can
be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration. The following program
show how global variables are used in a program.
CODING GROUND
Function with return with no arguments Function with return with arguments
103 C PROGRAMMING (1201)
Let’s do it!
• Using the same concept design a program with no return with arguments.
104 C PROGRAMMING (1201)
[Link] FIVE
106 C PROGRAMMING (1201)
5.1 OBJECTIVES
5.3 ARRAYS
Let’s do it!
A program to display all even numbers
110 C PROGRAMMING (1201)
Practice question
Consider array marks with the following elements 60, 70,76,56,89
Write a program to display the marks.
Solution
111 C PROGRAMMING (1201)
Let’s do it!
[Link] SIX
116 C PROGRAMMING (1201)
6.1 OBJECTIVES
6.2 POINTERS
Let’s do it!
119 C PROGRAMMING (1201)
[Link] SEVEN
125 C PROGRAMMING (1201)
7.1 OBJECTIVES
By the end of the chapter students should be able to:
Define, declare and initialize a string.
Print strings to output.
Capture a string from keyboard.
Discuss standard library functions.
Design programs using all listed standard library functions.
126 C PROGRAMMING (1201)
7.2 STRINGS
It is a collection of characters
A string is an array but with characters
String declaration:
char string name [string size];
char name [15];
The string size should be at least one greater than the maximum string size so as to
accommodate a null character.
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
The null character signifies the end of the string.
Scanf will not accept two worded strings e.g. Luke Mahomed
Thus can be eliminated by using gets and puts
Gets() reads characters from the standard input and stores them as a string
Puts () prints characters from the standard output just like printf statement.
129 C PROGRAMMING (1201)
Let’s do it!
CODING GROUND
Standard Library String Functions live demo
[Link]
131 C PROGRAMMING (1201)
8. CHAPTER EIGHT
133 C PROGRAMMING (1201)
8.1 OBJECTIVES
8.2 STRUCTURES
Here the keyword struct declares a structure that will hold the data fields named members. ‘tag
name’ is a name of the structure that we have declared. Inside the structure, we can use any
kind of datatypes like int, float, char and others.
135 C PROGRAMMING (1201)
Example
struct books
{
char name[20];
float price;
int pages;
};
Once a structure has been defined one or more variables can be declared.
A structure is usually defined outside the main function.
Declaration and initialization of a structure
Struct books B1={”cprog ”,300.00,67};
Struct books B2={”c fundamental ”,250.00,67};
Here product1 and product2 are variable which will hold members product name and product
number.
NOTE: Remember that members inside the structure are not variables and they do not occupy
memory until they are associated with structure variables such as product1 and product2.
137 C PROGRAMMING (1201)
Let’s do it!
[Link]
138 C PROGRAMMING (1201)
Let’s do it!
139 C PROGRAMMING (1201)
8.3 UNIONS
Defining a Union
To define a union, you must use the union statement in the same way as you did while
defining a structure.
The union statement defines a new data type with more than one member for your
program.
141 C PROGRAMMING (1201)
Let’s do it!
142 C PROGRAMMING (1201)
1. As a C programmer design a working program that you think would be useful to TCFL.
Your program must include almost everything you have learnt in C programming
including comments.[100]
2. A group of innovators are working towards the designing of a gate monitoring system.
As a C programmer design a program that you think these innovators would use on the
gate monitoring system.[100]
3. The TCFL librarian has launched a library system programming competition. Assuming
that you are one of the competitors design a program that you think would benefit the
library.[100]
4. Design a covid-19 body temperature detector. [ 15]
144 C PROGRAMMING (1201)
a) Program
b) Get(char)
c) Printf
d) Compiler
e) Array [10]
Question 2
Question 4
Design a program that displays at least 6 assignment operators you have learnt one at time
using switch statements. [10]
Question 5
Outline the differences between each of the following using suitable programs
Question 6
a) As a c programmer who has been tasked to design an online library system at TCFL.
Design a suitable program that performs the following to access the library:
i) Enter password student6229 to be granted access.
ii) If the password is wrong it must deny access. [9]
b) Show the syntax of writing the following
i) The for loop statement
ii) Pointers
iii) Structures
iv) while
v) do while [10]
Question 7
Mrs. Rose owns a bookshop. Design a program that you think she must use in order for her to
sell her books. The program must include the following:
a) Book price
b) Book title
c) Number of pages in the book
d) Book Author [10]
Question 8
a) Write a program to display all the even numbers inside the following array
x = {7, 4, 2, 13, 6, 14, 23};
b) For the above array x, write a program to find the sum of all the elements of this array
7+4+2+13+………23.
c) Write a program to display the smallest number in the array x. [10]
146 C PROGRAMMING (1201)
Question 9
A function is an independent block of code which can exist outside the main function. They are
used to manage our code. Show how functions can be used to calculate the area and perimeter
of a rectangle on a single program. Use a function type of your choice.
[10]
*************************************************************************************