C Programming
C Programming
Day 1
Programming in C
Content
•Variables
•Operators in C
•Summary
•You learned about algorithms is csc207. We now consider how to translate an algorithm into
programs using a high-level programming language.
•Programming is a skill like playing a musical instrument or playing a sport. The more you practice,
the better you will become. Use the worked examples in this course and try out the constructs by
building by building them into an application. You can use your imagination and expand the
examples. You will learn a lot by making small changes and seeing their effect.
Variables
•When you solve a problem, you identify the inputs and outputs and determine the variables. You
can imagine a variable as a box. Each box can usually store one value. Naming a variable is like
labeling the box. When you label a box you write on the outside of the box a description of what you
store in the box. When you name a variable, you should choose a meaningful name that describes
what the variable is going to be used for. This variable name is known as the variable’s identifier.
•Programming languages have rules about what is a valid identifier. They usually allow combination
of alphanumeric characters (letters, numerals, and the underscore character) but no spaces or other
symbols. Usually, identifiers must start with a letter. Some languages are case sensitive e.g. C.
•You should follow generally accepted naming conventions for choosing identifiers so that your
program code can be easily understood by other programmers. Avoid using keywords as identifiers.
Concatenate – join them together – to describe the purpose of a variable and use casing to indicate
the meaning of each word. For example, numberOfEntries (Camel case). There are two type of camel
case: upper and lower camel case in upper camel case, the letter of each word start with a capital
letter while in lower camel case the letter of first word start with a small letter and the following
words start with capital letters.
•Don’t use single letter variable identifiers unless this is really appropriate, but there is no need to
have a variable identifier of more than 20 characters. Choose sensible that will read easily in your
program code.
Operators in C
•To assign a value to a variable, we use an assignment statement. Here is an example to assign the
value 7 to a variable with identifier number1.
number1 = 7;
•The value on the right of the assignment operator (=) is stored in the variable named on the left of
the assignment operator. You should read this as ‘number1 becomes equal to 7’.
•Although it is possible to write more than one statement on one line, this is not recommended, as it
makes your program more difficult to understand and maintain.
•Assignment can consist of an expression, a formula, to the right of the assignment operator. This
expression is evaluated when the statement is executed and the value is then stored in the variable
named on the left of the assignment operator.
•If number1 contains the value 7 and number2 contains the value 12, when the following statements
are executed, sum will contain the value 19:
•Suppose count contains the value 5, then after this statement has been executed, count will contain
the value 6. You can read this statement as ‘increment count by 1’.
count = count + 1;
Arithmetic operators:
•In C we can perform arithmetic operations by combining the following operators
Operation
Addition
Arithmetic operator ; +
Example
number1 + number2;
Subtraction
Arithmetic operator ; -
Example
number1 - number2;
Multiplication
Arithmetic operator; *
Example
number1 * number2;
Division
Arithmetic operator; /
Example
number1 / number2;
Modular arithematics:
• Normal division returns a result that might not be a whole number, but sometimes we are
interested in the whole number part only. This is known as integer division. Integer division of 17 by
5 gives the result 3.
• The modulo operation gives the remainder after a division. For example the remainder of 17
divided by 5 is 2.
int wholeNumberPartnumber1;
x = x * 5;
OR
x *= 5;
•This trick works with all the five basic arithmetic operators. C provides a further shorthand for
incrementing or decrementing a variable by 1.
x++;
x--;
Comments
•It is good programming practice to add comments to source code that explains the purpose of a
statement or set of statements. These comments are ignored by the compiler. Symbols used to
enclose comments which may go over several lines
/* comments go
Here */
// comments go here
// and again
Using the C programming language and sensible variable identifiers, write assignment statements to
calculate the following values:
3.The percentage of questions attempted out of the total number of questions in the quiz.
4.How many 5000 FCFA notes you will get for an amount of money in FCFA stored in a variable
amount.
Proposed Solutions
q4 numberOf5ThousandsNotes = Amount / 5;
int numberOf5ThousandsNotes;
•When you first start a console application, the programming environment provides you with a
framework where you type your program statements.
•A console application is a program that runs in a text based window into which the user types and
which displays text output from the computer.
scanf("%d", &number1);
When the above statement is executed, the program will pause and wait for input from the
keyboard until the enter key is pressed.
•Other examples:
1) int x,y,z;
2) float y;
Int x;
Scanf(("%f%d",&y, &x);
printf("hello, world!");
printf("%d", number1);
3-To display a string and then move the output stream to the next line Example
printf("hello, world!\n");
OR
puts("hello, world!");
4-To display the content of a variable and then move the output stream to the next line Example
printf("%d\", number1);
printf("\n"); OR
puts("");
#include <stdio.h>
printf("hello, world\n");
return 0;
•In C, the function to print something to the screen is printf, where f stands for “format”, meaning
we can format the string in different ways. Then, we use parentheses to pass in what we want to
print. We use double quotes to surround our text, or string, and add a \n which indicates a new line
on the screen. (Then, the next time we call printf, our text will be on a new line. Finally, we add a
semicolon ; to end this line of code in C.
•Here is how to combine strings and contents of variables into one output stream.
7 + 12 = 19
•C is a strongly typed language i.e. it requires that the datatype of a variable should be declared
before it can be assigned values or before they can be used. This is a desirable feature of a language
as the compiler will check that the operations are performed on correct variable type. In C variables
are declared as follows: type variable identifier
•Example
int max = 5;
•The datatype is followed by a list of variable identifiers. You can assign an initial value at declaration
time.
#include <stdio.h>
int main(void)
scanf("%f", &number1);
scanf("%f", &number2);
average = sum / 2;
return 0;
• The number %4.2f formats the real numbers to be displayed using digits with two digits after
the decimal point. If you don’t include this a real number will be displayed in scientific format.
Sequencing instructions
•The calculation 4 * 7 + 3 gives a different result to the calculation 4 *(7 + 3), because the brackets
change the order of evaluation. Similarly, the order in which program statements are executed
affects the outcome. When programming with imperative languages, the statements are executed in
the sequence the programmer determines. Values need to be assigned to variables before the can be
used in calculations, and calculations need to be done before results can be displayed.
•How to write the code to read input from the keyboard and produce output to the screen.
Assignment: Questions
2.Display two messages of your choice on the screen, separated by an empty line.
3.Display the sum and average of three numbers entered at the keyboard.
4.Read in two integers and display how many times the first integer divides the second integer.
Display the remainder from this division.
5.The user enters an amount of money as a whole number. The program should calculate and display
how many 2000frs, 1000frs and 500frs notes and 100frs and 50frs are needed to make up this
amount of money. For example 3750frs would give 1x2000frs, 1x1000frs, 1x500frs and 2x100frs,
0x50frs.
• Variable declarations
• Constant definitions
• Summary
All data is stored and process as a sequence of bit patterns. We need to declare the type of the data
values we want to use so that the processor operates on them correctly. For example, we may wish
to store whole numbers (integers), text (strings) or numbers with fractional parts (real numbers). The
compiler allocates memory space according to the data we want to store. For example, integers may
be stored using four consecutive bytes. Programming languages have common data types build in.
You may wish to declare your own data types.
#include<stdio.h>
int main(){
scanf("%d",&number1);
scanf("%d",&number2);
return 0;
Variable declaration
Global variable
•These are variables declared at the public section of a program and accessible from everywhere in
the program. It is not always desirable to use a global variable as its values may get changed
accidentally.
Local variable
•A variable declared in a program block and accessible only within the program block.
•Rather than declaring variables globally, it is good programming style to declare variables locally
within the block where the variable is going to be used.
•When you start writing programs with routines – procedures or functions – you should declare local
variables within the routines. Any variable value that is required by another routine should be passed
as a parameter. A routine or subroutine is a subprogram.
Constant definition
•A constant is a value that does not change throughout the program. It is good programming style to
declare named constants. Don’t use variables because you might change their value by accident. If
you choose a meaningful identifier to label a constant value then your program will be much easier
to understand and maintain.
•Imagine you are writing a mathematical program where you require the value of pi. You know that
pi is approximately equal to 3.1416. If you use wherever required in your program, but later want to
calculate it with more accuracy, then you need to change the value throughout. If you declare pi as a
named constant and initialize its value at the beginning of your program, you only need to change it
in the one place where it is declared.
NB: define can be placed anywhere in your program but it is good programming practice to place
them before your main function.
Remark: If your program tries to modify a constant variable, the compiler will generate an error.
Worked Example
Problem: Write a program that inputs the radius of a circle and outputs its diameter, circumference
and area. pi should be declared as a constant variable with the value 3.14159
Solution:
#include <stdio.h>
int main(void)
{
float radius, diameter, circumference, area;
scanf(("%f", &radius);
diameter = 2*radius;
circumference = 2*pi*radius;
area = pi*radius*radius;
return 0;
1) Whole numbers
Description: The int data type is used for variables that will store integers i.e. signed 32 bits integers
Conversion Specifier: %d
NB: The conversion specifier is used in scanf and printf when outputting or inputting values of this
type
Description: Unsigned is a qualifier that you can be applied to certain types (including int), which
effectively doubles the positive range of variables of that type, at the cost of disallowing any negative
values
Conversion Specifier: %d
Range: 0 to 2^32-1
Remark: Unsigned is not the only qualifier that we might see for variable data types. There are also
short and long and const.
Build-in data types:
2) Real numbers
Description: Real numbers are numbers with a decimal point and a fractional part, such as
19.124578654. C supports a variety of real number types
Description: The float data type is used for variables that will store floating-point values also known
as $real numbers$.
Conversion Specifier: %f
Description: The float data type is used for variables that will store floating-point values also known
as real numbers. The difference is that doubles are double precision. They always take up 8 bytes of
memory.
Conversion Specifier: %f
Remark: With an additional 32 bits of precision relative to a float, doubles allow us to specify much
more precise real numbers.
Question from student in worked out example: Pls sir why %.2f not%4.2f
Answer from teacher: %.2f means we want to represent the results with any number of digits, but
with just 2 digits after the decimal point. %4.2f means we want the results to have 4 digits with 2
after the decimal point.
Description: A variable of this type stores a single ASCII character e.g. symbol = '&';
Conversion Specifier: %c
Remark:
•The string data type is used for a variable that will store a series of characters, which programmers
typically call string.
•Strings include things such as words, sentences, paragraphs, and the likes.
•There is no string data type in C, but arrays of characters of characters can be used as a
replacement.
Worked Example:
#include <stdio.h>
int main(void)
char name[20];
return 0;
•The Boolean data type is used for variables that will store a Boolean value. More precisely, they are
capable only of storing one of two values: true or false.
•There is no build in Boolean data type in C, but 0 is false and any other integer value is true.
#include <stdio.h>
int main(void)
int value;
scanf("%f", &value);
if(value){
} else {
printf("The number inputted is zero ");
return 0;
•Functions can have a void which just mean they don’t return a value.
•The parameter list of a function can also be void. It simply means the function takes no parameter.
1-in what variable type will you best store the following values?
f.The name of a country.( hint: the name of a country is a sequence of characters, hence string.
Which is an array of characters in C)?
Sometimes we want to work with types that are not build into the programming language we are
using. We can declare our own types. A type needs to be defined before we can declare variables of
that type.
Question; Ok sir in naming the variable s types is the range considered somehow? Ok sir in naming
the variable s types is the range considered somehow?
Answer; Yeah It really depends on the problem you are solving. If you will store very large values,
then using a type or a qualifier that can enable you do that will be good.
User-defined data types
1) Records
•A record is a data structure that groups together a number of variables, which need not be of the
same type and have no associated ordering. The variables of a record are called fields.
•To use a records, we declare the structure as a type, then we declare variables of that type.
•To work with individual fields of a record, we use the dot notation: recordVariableName.fieldName
Worked Example:
#include <stdio.h>
typedef struct
char name[20];
char gender;
int level;
float height;
} tstudent;
int main(void)
tstudent aboutStudent;
gets(aboutStudent.name);
scanf("%c", &aboutStudent.gender);
scanf("%d", &aboutStudent.level);
scanf("%d", &aboutStudent.height);
return 0; }
Remark:
•name , gender, level and height are the fields of the record type tstudent
2) Enumerated types
•An enumerated type defines an ordered set of values. Each value is given an ordinal value, starting
from zero. Members of an enumerated type can be used as loop control variables, in case statements
and as array subscripts.
Worked Example 1:
#include <stdio.h>
int main(void)
day1 = wed;
day2 = sun;
return 0;
Worked Example 2:
#include <stdio.h>
int main(void)
bool finished;
finished = true;
return 0;
Remark: enumerated types can be used in a loop (to be seen in another lesson)
•Sometimes we may want to manipulate individual bits in a bit pattern. In the following examples, a
contains 13(00001101 in binary) and b contains 17 (00010001 in binary).s
Operator: NOT a
Operator in c: ~a
*Result: 11110010
Explanation: The not operator inverts each bit of a, so each 0 becomes 1 and 1 becomes 0
Operator: a AND b
Operator in c: a & b
*Result: 00000001
Explanation: The operator sets a bit to 1 if the corresponding bit in a and b are both 1, otherwise it
sets it to 0.
Operator: a OR b
Operator in c: a | b
*Result: 00011101
Explanation: The or operator sets a bit to 1 if either of the corresponding bits in a and b are 1,
otherwise it is set to 0
Operator: a XOR b
Operator in c: a ^ b
*Result: 00011100
Explanation: The xor operator sets a bit to 1 if only one of the corresponding bits in a and b is 1
otherwise it is set to 0.
Summary:
•Build-in data types: integer, byte, real, Boolean, character and string.
Question: sir, at one point you used scanf and at another you used gets. Are they exactly the same
when applied?
Answer: gets and puts are good when you are dealing with strings, especially when you suspect
user input will have spaces. printf doesn't work well with spaces in data of type string.
#include<stdio.h>
int main(){
scanf("%d",&amount);
return 0;
Lecture 3: Selection
•Boolean Expressions
•Simple if statements
•if-then-else statement
•Nested if statement
•Switch statement
•Summary
Conditional expressions allow your program to make decisions and take different forks (paths) in the
road, depending on the values of variables or user input. C provides a few different ways to
implement conditional expressions (also known as branches) in your program.
Boolean Expressions
1) Relational operators
•Expressions with relational (comparison) operators are known as Boolean expressions. When a
Boolean expression is evaluated, it returns a Boolean value, True or False.
In C
Equal to ==
2) Boolean operators
•More complex Boolean expressions can be formed using Boolean operators, or logical operators:
NOT, AND, OR.
Mathematics: Number = 1
In C: Number == 1
Mathematics: Number ≠ 1
In C: Number != 1
Mathematics: Age ≤ 17
In C: Age <= 17
Note: | and & are bitwise or and and respectively (check the last lesson on datatypes), while ||
and && are logical or and and respectively. In other words | and & operate on the bits 1 and 0,
while || and && operate on the Boolean values true and false.
Simple if statement
if (boolean-expression)
•If boolean-expression evaluates to true, all lines of code between the curly braces will execute in
order from top-to-bottom.
•If *boolean-expression evaluates to false, those lines of code will not execute.
•The simple if statement is used when we want to execute a statement or group of statements only
if a certain condition is met.
/**
* age.c
* Tell you things that you are old enough to do depending on your age
*/
#include <stdio.h>
int main(){
int age;
printf("How old are you? ");
scanf("%d",&age);
if(age >= 3)
system("pause");
return 0;
Activity:
1. Compile the code and run it. The code asks for your age. Depending on how old you are, it will
tell you things that you are old enough to do.Currently, it only does the first message. Your task is to
make the code
Note the solution of Activity was given by teacher and titled ageSolution.c
Questions 1.11
1-Display a message if two numbers read from the keyboard are the same.
2-Display a message if the first of two numbers read from the keyboard is greater than the second.
If-then-else statement
if (boolean-expression)
else
•If boolean-expression evaluates to true, all lines of code between the first set of curly braces will
execute in order from top-to-bottom.
•If boolean-expression evaluates to false, all lines of code between the second set of curly braces will
execute in order from top-to-bottom.
•When we want to execute a statement or group of statements if a certain condition is met, but
another group of statements if the condition is not met, we can use the if-then-else statement.
•In the example below, we want to decide whether to turn on the airconditioner or turn it off,
according to the entered room temperature:
#include <stdio.h>
int main(void)
int temp;
scanf("%d", &temp);
else
return 0;
Question(1.11) 2 is different from question 1 i.e. I expected two programs from you.
•In this example: if the temperature is greater than 22, then display the first sentence: Please turn
on air-conditioner
•else, if the condition is not met (less than or equal to 22) , then display this line: Please turn off air-
conditioner
Nested if statements
•A statement in the in the then part or the else part of an if statement may also be an if statement. It
is possible to extern the if statement to handle multiple conditions.
if (boolean-expr1)
// first branch
else if(boolean-expr2)
// second branch
else if(boolean-expr3)
{
// third branch
else
// fourth branch
•As you would expect, each branch is mutually exclusive i.e. you can only ever go down one of the
branch.
#include <stdio.h>
int main(void)
int temp;
scanf("%d", &temp);
}
else
printf("Do nothing\n");
return 0;
Questions:
Write a program that ask for three numbers to be typed in at the keyboard, then display the largest
one.
Switch statement
•C’s switch() is a conditional statement that permits enumeration of discrete cases, instead of relying
on Boolean expressions.
•Nested if statements can get very cumbersome and sometimes a switch() is preferable. a switch()
statement presents a list of options that the variable may match. As long as there is no match,
control skips to the next option. When a match is found, the associated statements are executed.
•The Restaurant program will illustrate the use of the switch of statement:
#include <stdio.h>
int main(void)
int meal;
scanf("%d", &meal);
switch (meal)
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
default:
printf("Wrong Entry\n");
}
return 0;
Note: It’s important to break; between each case, or you will “fall through” each case unless that is
desired behavior.
?: statement
int x;
if (expr)
x = 5;
else
x = 6;
int x;
x = (expr) ? 5 : 6;
•The tenary operator (?: ) is mostly a cute trick, but is useful for writing trivially short conditional
branches. Be familiar with it, but know that you won’t need to write it if you don’t want to.
Summary
Questions
1-Ask the user for a month number, then display the name of the month; for example, the input 9
should produce a display of September.
2-Ask the user for a year, then display whether that year is a leap year. Hint: use the modulo
operator.
3-Ask the user for a month number, then display the number of days in that month. For example, the
input 9 should display 30.
4-Ask the user for a month number and a year then display the number of days in that month, taking
into account leap years.
Lecture 4
The lecture was given by lecturer and titled Lecture 4 Repetition.pdf and it also had source code file
titled src4.rar.
Lecture 5
The lecture was given by lecturer and titled Lecture 5 procedures and functions.pdf and it also had
source code file titled src5.rar.
Lecture6
The lecture was given by lecturer and titled Lecture 6 Arrays.pdf and it also had source code file
titled src6.rar.
Lecture7
The lecture was given by lecturer and titled Lecture 7 Text files and files of records.pdf and it also
had source code file titled src7.rar.