Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

C Language

c programming

Uploaded by

Nerd Pixels
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

C Language

c programming

Uploaded by

Nerd Pixels
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

C language

C is a structured programming language that is used to develop applications that are modular in
nature. It is a high-level language that can be used to develop simple applications. It is a case
sensitive language in which most of the commands are written in lower case. Statements in C must
be terminated with a semicolon, white spaces with space bar or enter key are ignored in C.

Elements of a C program

A C program is made up of the following components;


1. Identifiers – These are names used to recognize a variable, constant, function, or any other user
defined item. The name of an identifier must follow the rules below;
i) The name must start with an alphabet or underscore.
ii) Reserved word should never be used as an identifier name.
iii) Special characters should not be used on the name e.g.? /, \, . etc.
iv) Spaces are not allowed in the identifier name.

2. Key words/Reserved words – These are phrases that have special meaning within the C language.
They must be used for the intended function.

3. Comments - These are explanatory statements that are not executed but are used by anyone
reading the source code. There are 2 ways of creating comments in C; Single line comment (// only
at the beginning of the comment) and block of line comments (/* and closes with */)

• Every programming assignment should have the first 2 lines as comments and have
admission number in the comment.

4. Data type – Determine the nature of values to be held or returned by an identifier. Once a data
type is set, the values entered must conform to the set type. C uses the following primitive data
types;
i) Integer – int (whole numbers without decimals)
ii) Character – char (single letter or character)
iii) Floating point number – float (numbers with decimals)
iv) Double precision – double (large data)
v) Boolean – bool (data types that are only true or false)
vi) Valueless – void (when no data type is specified)

The basic data types have modifiers that control the amount of data they can hold. The modifiers
include signed (both positive and negative values), unsigned (only positive numbers), short (data
limited to 2 bytes) and long (data uses 4 bytes).

5. Operators – this is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. The operators include the following;

i) Arithmetic – These are symbols that perform mathematical calculations. They include +
(addition), - (subtraction), *(multiplication), / (division), % (modulus/remainder), ++ (increment/add
one to the item), -- (decrement/ subtract 1 from the item).

NB; Increment and Decrement are not binary but are unary.

ii) Relational/Comparison operators – these are Boolean operators that return true or false
whenever items are compared. The operators include; == (equal), > (greater than), >= (Greater or
equal), < (less than), <= (less than or equal to), !=(not equal)

iii) Logical operators – these operators are used when building compound conditions. They
include && (and), ll (or), ! (not).

iv) Assignment operators – used to initialize values to an identifier. They include; =(assign),
+= (add and assign), -=(subtract and assign), *= (multiply and assign), /= (divide and assign), %=
(modulus and assign).

C program Structure
A C program has a standard organization for every element that makes up the program. A C program
must have the following structure;

• Pre-processor directives – the C language is made up of library files that provide different
functions required by a program. These files are placed at the top of a C program and they
are called preprocessor directives. They must be processed before compilation begins. These
files are placed on a program using #include/libraryfile.h (header files). The most commonly
used library file is stdio.h (standard input output)

• Functions – A C program is made up several functions but there is one mandatory function
called main function.

• Statements – these are expressions that makes up the program instructions that enables a C
program to perform its tasks.

Input and Output in C

The C language uses the header file stdio.h to enable a program to produce an output and receive
input. stdio.h uses 2 main functions, one for input and anther for output. For output, the function
printf() is commonly used. While for input te function scanf() is used.

Canonical first program


#include<stdio.h>

int main ()
{

printf(“welcome to programming class!!”)

return 0;

Variables

A variable is a named storage location on memory with the ability to store a particular type of data
whose value can change during program execution. They enable the programmer to manipulate data

Variable scope: This is the region or extent to which a variable can be accessed and used. The scope
of a variable can either be local or global. A local variable is declared within a function and can only
be accessed and used within that function. If the function ends then the variable ceases to exist.
Global variable is declared outside of all the functions usually above main function. Such a variable
can be accessed by all the functions throughout the program.

Variable declaration: In C, all the variables must be declared before use. It is declared by specifying
the data type and variable name i.e. datatype variablename e.g. int age;

Variable initialization: Initialization is the assignment of value to a variable. This is done using the
assignment operator. Initialization can be done at declaration or after.

-Ex. Write a program that allows 3 integer data items to be entered from the keyboard and the
program find the sum and the product.
*You must know;
i) Items (identifiers) to declare - num1, num2, num3, sum, and product
ii) Input - num1, num2, num3
iii) Processes (calculations) - sum, product
iv) Output - sum, product

//Program to calulate sum and product.

#include <stdio.h>

int main()

{
//Declarations
int num1, num2, num3, sum, product;

printf ("Enter value for number 1:");


scanf("%d", &num1);
printf ("Enter the second value:");
scanf("%d", &num2);

printf ("Enter the third value:");


scanf("%d", &num3);

//Calculations
Sum=num1+num2+num3;
Product=num1*num2*num3;

//Output
printf ("The sum is: %d \n" , sum);
printf ("The product is: %d \n" , product);

return 0;

Constants

A constant is a named storage location with the ability to store a particular type of data whose value
does not change throughout program execution. They are used when dealing with data items that
are static such as rates etc.

The scope of a constant is identical to that of a variable i.e. local constants is declared within a
function and global constant is declared outside of all the functions.

Constant declaration
A local constant is declared using the key word "const" followed by the data type, constant name,
assignment operator and finally its value. const type constantname = Value;

e.g. const float Rate=0.12;

Global constants are declared outside all the functions using #define constantname Value

e.g. #define Rate 0.12

Ex. Write a program that calculates the area and circumference of a circle whose radius is entered by
the user.

i) Items (identifiers) to declare - radius, area, circumference (variables), Pi (constant)


ii) Input - Radius
iii) Processes (calculations) - area, circuference
iv) Output - area. circumference
//Program to calulate area and circumference.

#include <stdio.h>

int main()

{
//Declarations
int Radius;
float Area, Circum;
const float Pi=3.142;

//Input
printf ("Enter the Radius:");
scanf("%d", &Radius);

//Calculations
Area=Pi*Radius*Radius;
Circum=2*Pi*Radius;

//Output
printf ("The Area of the cirlce with a radius of %d is: %f \n" , Radius, Area);
printf ("The Circum is: %f \n" , Circum);

return 0;

Ex. Write a program that calculates simple intrest at the rate of 12% per annum. The principle and
duration in years is entered by the user.

//Program to calculate simple interest.

#include <stdio.h>

int main()

//Declarations

int Princ, Years;

float Interest;
const float Rate=0.12;

//Input

printf ("Enter the Principle:");

scanf("%d", &Princ);

printf ("Enter the Duration:");

scanf("%d", &Years);

//Calculations

Interest=Rate*Princ*Years;

//Output

printf("The Simple interest of %d is: %f \n", Princ, Interest);

return 0;

Control Structures
The control structures determine how the program statements are executed at run time. If left
unchecked, the program will execute sequesntially from left to right and top to bottom. With control
structures, we can create programs that can skip some statements or execute statements repeatedly
i.e., a program that can make some judgement.

The C language supports 2 categories of control structures, namely decision and loop control
structures.

Decision Structures
These are control structures that enables the programmer to set some condition and the statements
to be executed depending on the outcome of the conditional test. If the test evaluates to true, then
a block of statements is executed but if the test evaluates to false, then a different set of statements
are executed.

There are 2 categories of decision structures i.e. if and switch case statements.

The If statement: This statement is made up of 3 parts i.e. the conditional test, the true statements
and the false statements. The program will then decide which statements to execute depending on
the outcome of the conditional test.
if (condition)
{
Statements;
}
else
{
Statements
}

Ex. 2

if (condition1)
{
Statements;
}
else if (condition2)
{
Statements
}
else if (condition 3)
{
Statements;
}
else
{
Statements
}
Ex. Write a program that accepts the marks from 3 subjects and the program calculates the total,
average and it determines whether the student has passed or failed depending on the average. Pass
= 40.

//Program to determine pas or fail.

#include <stdio.h>

int main()

{
//Declarations
int mark1, mark2, mark3, total;
float Average;

//Input
printf ("Enter the 3 integer marks:");
scanf("%d", %d, %d" , &mark1, &mark2, &mark3 );

//Calculations
Total=mark1 + mark2 + mark3;
Average=Total/3;

printf ("Total: %d \n", Total);


printf(Average: %f \n" , Average);

//Check pass/fail
if (average>=40
{
printf(PASS \n")

}
else
{
printf(FAIL \n")
}

return 0;

Write a program that takes in the unit price and quantity of an item being bought, the program
then calculates the total cost of the item and awards a discount as follows :
unit price = 30,000
units=40

discounts
10,000< no discount
10,000 - 30,000 5%
30k -50,000 10&
50 - 75k 12%
75-100k 15%
100, 000> 20%

display total cost -


discount _
Amount payable_

You might also like