0% found this document useful (0 votes)
17 views

Cprogramming Notes

Floc

Uploaded by

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

Cprogramming Notes

Floc

Uploaded by

yakubusman840
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

C Programming Basics

What is C as a Programming Language?

C is a programming language which born at “AT & T‟s Bell Laboratories” of USA in 1972. It
was written by Dennis Ritchie. This language was created for a specific purpose: to design the
UNIX operating system (which is used on many computers). From the beginning, C was
intended to be useful--to allow busy programmers to get things done. Because C is such a
powerful, dominant and supple language, its use quickly spread beyond Bell Labs. In the late
70‟s C began to replace widespread well-known languages of that time like PL/I, ALGOL etc.
Programmers everywhere began using it to write all sorts of programs. Soon, however, different
organizations began applying their own versions of C with a subtle difference. This posed a
serious problem for system developers. To solve this problem, the American National Standards
Institute (ANSI) formed a committee in 1983 to establish a standard definition of C. This
committee approved a version of C in 1989 which is known as ANSI C. With few exceptions,
every modern C compiler has the ability to adhere to this standard. ANSI C was then approved
by the International Standards Organization (ISO) in 1990. Now, what about the name? Why it
was named C, why not something else. The C language is so named because its predecessor was
called B. The B language was developed by Ken Thompson of Bell Labs.

Why C?

In today's world of computer programming, there are many high-level languages to choose from,
such as Pascal, BASIC, and Java. But C stands apart from all these languages. This is due to its
many desirable qualities. It is a robust language whose rich set of built-in functions and operators
can be used to write any complex logic program. The C language compiler combines the
capabilities of a low level language with the features of a high level language. Therefore the
language is suitable for writing both system software as well as business packages & other
software. You will see many compilers available in the market written in C.

Features of C

• C is a powerful and flexible language which helps system developers to deliver various
complex tasks with ease. C is used for diverse projects as operating systems, word processors,
graphics, spreadsheets, and even compilers for other languages.

• C is popular among professional programmers for programming, as a result, a wide variety of C


compilers and helpful accessories are available.

• C is highly portable language. This means that a C program written for one computer system
(an IBM PC, for example) can be run on another system (a DEC VAX system, perhaps) with
little or no modification. Portability is enhanced by the ANSI standard for C, the set of rules for
C compilers.

1
C Programming Basics

• C‟s another striking feature is its ability to extend itself. A C program is basically a collection
of various function supported by C library (also known as header files). We can also add our own
functions to the C library. These functions can be reused in other applications or programs by
passing pieces of information to the functions, you can create useful, reusable code. • Writing C
program with user-defined functions makes program more simple and easy to understand.
Breaking a problem in terms of functions makes program debugging, maintenance and testing
easier.

Getting Started with C

Communicating with a computer involves speaking the language the computer understands,
which immediately rules out English as the language of communication with computer.
However, there is a close analogy between learning English language and learning C language.
The classical method of learning English is to first learn the alphabets used in the language, then
learn to combine these alphabets to form words, which in turn are combined to form sentences
and sentences are combined to form paragraphs. Learning C is similar and easier. Instead of
straight-away learning how to write programs, we must first know what alphabets, numbers and
special symbols are used in C, then how using them constants, variables and keywords are
constructed, and finally how are these combined to form an instruction. A group of instructions
would be combined later on to form a program. This is illustrated in the Figure 1.

Figure 1

2
C Programming Basics

The C Character Set

A character denotes any alphabet, digit or special symbol used to represent information. Figure 2
shows the valid alphabets, numbers and special symbols allowed in C.

Figure 2

Constants, Variables and Keywords

The alphabets, numbers and special symbols when properly combined form constants, variables
and keywords. Let us see what are „constants‟ and „variables‟ in C. A constant is an entity that
doesn‟t change whereas a variable is an entity that may change.

In any program we typically do lots of calculations. The results of these calculations are stored in
computers memory. Like human memory the computer memory also consists of millions of
cells. The calculated values are stored in these memory cells. To make the retrieval and usage of
these values easy these memory cells (also called memory locations) are given names. Since the
value stored in each location may change the names given to these locations are called variable
names. Consider the following example.

Here 3 is stored in a memory location and a name x is given to it. Then we are assigning a new
value 5 to the same memory location x. This would overwrite the earlier value 3, since a memory
location can hold only one value at a time. This is shown in Figure 3.

3
C Programming Basics

Figure 3

Since the location whose name is x can hold different values at different times x is known as a
variable. As against this, 3 or 5 do not change, hence are known as constants.

Types of C Constants

C constants can be divided into two major categories:

(a) Primary Constants (b) Secondary Constants

These constants are further categorized as shown in Figure 4.

Figure 4

4
C Programming Basics

At this stage we would restrict our discussion to only Primary Constants, namely, Integer, Real
and Character constants. Let us see the details of each of these constants. For constructing these
different types of constants certain rules have been laid down. These rules are as under:

Rules for Constructing Integer Constants

(a) An integer constant must have at least one digit.


(b) It must not have a decimal point.
(c) It can be either positive or negative
(d) If no sign precedes an integer constant it is assumed to be positive.
(e) No commas or blanks are allowed within an integer constant.
(f) The allowable range for integer constants is -32768 to 32767.

Truly speaking the range of an Integer constant depends upon the compiler. For a 16-bit compiler
like Turbo C or Turbo C++ the range is –32768 to 32767. For a 32-bit compiler the range would
be even greater. Question like what exactly do you mean by a 16- bit or a 32-bit compiler, what
range of an Integer constant has to do with the type of compiler and such questions are discussed
in detail in Chapter 16. Till that time it would be assumed that we are working with a 16-bit
compiler. Example: 426, +782, -8000, -7605

Rules for Constructing Character Constants

1) A character constant is a single alphabet, a single digit or a single special symbol


enclosed within single inverted commas. Both the inverted commas should point to the
left. For example, ‟A‟ is a valid character constant whereas „A‟ is not.
2) The maximum length of a character constant can be 1 character. Eaxample: 'A' 'I' '5' '='

Variable in C

Variable represent some segment of memory location in a computer. Different values placed in
the storage depend on the value type. Variable should be declared prior to storage of any values.
When declaring variable in C rules must be followed. Such as:

1) A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some


compilers allow variable names whose length could be up to 247 characters. Still, it
would be safer to stick to the rule of 31 characters. Do not create unnecessarily long
variable names as it adds to your typing effort.
2) The first character in the variable name must be an alphabet or underscore
3) No commas or blanks are allowed within a variable name.
4) No special symbol other than an underscore (as in gross_sal) can be used in a variable
name. Ex.: si_int, m_hra, pop_e_89
5) C is case sensitive. Upper and lower characters are not treated the same
6) Reserve words are not allowed as shown in Figure 5.

5
C Programming Basics

Figure 5

Example of variable declaration:

Create a variable called myNum of type int and assign the value 15 to it:

int myNum = 15;

You can also declare a variable without assigning the value, and assign the value later:

// Declare a variable
int myNum;

// Assign a value to the variable


myNum = 15;

Data Types and Declarations

Data type is some reserve words used to specify the values whether they are integral, real,
character, etc. Different storage space would be allocated depends on the data type.

Declaration is the process of reserving storage area in order to store different values temporary.

Whenever we use a value or variable, we will declare it and its data type. Variables must be
explicitly declared before they are used. Each declaration statement in C language must be end
with semicolon. There are various ways of declaring a variables, and following are some variable
declaration.

int GrossPay;
6
C Programming Basics

int NetPay = 0;

int Value1, Value2, Value3;

int Range1 = 1, Range2 = 100;

Writing a C Program

1) A programmer uses a text editor to create or modify files containing C code.


2) Code is also known as source code.
3) A file containing source code is called a source file.
4) After a C source file has been created, the programmer must invoke the C compiler
before the program can be executed (run).

Stages of Compilation

1) Preprocessing
 Performed by a program called the preprocessor
 Modifies the source code (in RAM) according to preprocessor directives
(preprocessor commands) embedded in the source code
 Strips comments and white space from the code
 The source code as stored on disk is not modified.
2) Compilation
 Performed by a program called the compiler
 Translates the preprocessor-modified source code into object code (machine code)
 Checks for syntax errors and warnings
 Saves the object code to a disk file, if instructed to do so (we will not do this).
o If any compiler errors are received, no object code file will be generated
o An object code file will be generated if only warnings, not errors, are
received.
3) Linking
 Combines the program object code with other object code to produce the
executable file.
 The other object code can come from the Run-Time Library, other libraries, or
object files that you have created.
 Saves the executable code to a disk file. On the Linux system, that file is called
a.out.
o If any linker errors are received, no executable file will be
generated.

7
C Programming Basics

Simple C Program

#include <stdio.h>

int main ( void )

printf ( “Hello, World!\n” ) ;

return 0 ;

Anatomy of C language

program header comment

preprocessor directives (if any)

int main ( void )

statement(s)

return 0 ;

Program Header Comment

 A comment is descriptive text used to help a reader of the program understand its content
 All comments must begin with the characters /* and end with the characters */
 These are called comment delimiters
 The program header comment always comes first

Preprocessor Directives (Command)

 Lines that begin with a # are called preprocessor directives (commands)


 Example: the #include directive causes the preprocessor to include a copy of the standard
input/output header file stdio.h at this point in the code.
 This header file was included because it contains information about the printf ( ) function
that is used in this program.

8
C Programming Basics

Stdio.h

 When we write our programs, there are libraries of functions to help us so that we do
not have to write the same code over and over.
 Some of the functions are very complex and long. Not having to write them ourselves
make it easier and faster to write programs.
 Using the functions will also make it easier to learn to program!

Int main void

 Every program must have a function called main. This is where program execution
begins.
 main() is placed in the source code file as the first function for readability. There must be
a function with this name or the program can not successful compile.
 The reserved word “int” indicates that main() returns an integer value.
 The parentheses following the reserved word “main” indicate that it is a function
 The reserved word “void” means nothing is there.

The Function Body

 A left brace (curly bracket) -- { -- begins the body of every function. A corresponding
right brace -- } -- ends the function body
 The style is to place these braces on separate lines and to indent the entire function body.

printf (“Hello, World! \n”);

 This line is a C statement.


 It is a call to the function printf ( ) with a single argument (parameter), namely the string
“Hello, World!\n”.
 Even though a string may contain many characters, the string itself should be thought of
as a single quantity.
 Notice that this line ends with a semicolon. All statements in C end with a semicolon.

return 0;

 Because function main() returns an integer value, there must be a statement that indicates
what this value is.
 The statement
return o;
indicates that main() returns a value of zero to the operating system.
 A value of 0 indicates that the program successfully terminated execution.
 Do not worry about this concept now. Just remember to use the statement.

9
C Programming Basics

Input
The input in C enables users to enter values for e.g. data entry. The function enables programmer
to prompt for data entry during program execution. Appropriate Conversion Codes should be
specified in order to display the required value. You have already learned that printf() is used
to output values in C. To get user input, you can use the scanf() function:
#include <stdio.h>

int main() {
// Create an integer variable that will store the number we get from the user
int myNum;

// Ask the user to type a number


printf("Type a number and press enter: \n");

// Get and save the number the user types


scanf("%d", &myNum);

// Print the number the user typed


printf("Your number is: %d", myNum);

return 0;
}
The scanf() function takes two arguments: the format specifier of the variable (%d in the
example above) and the reference operator (&myNum), which stores the memory address of the
variable.

Multiple Inputs

The scanf() function also allow multiple inputs (an integer and a character in the following
example):

#include <stdio.h>

int main() {

// Create an int and a char variable

int myNum;

char myChar;

// Ask the user to type a number AND a character

printf("Type a number AND a character and press enter: \n");

10
C Programming Basics

// Get and save the number AND character the user types

scanf("%d %c", &myNum, &myChar);

// Print the number

printf("Your number is: %d\n", myNum);

// Print the character

printf("Your character is: %c\n", myChar);

return 0;

Taking String Input

You can also get a string entered by the user:

#include <stdio.h>

int main() {

// Create a string

char firstName[30];

// Ask the user to input some text (name)

printf("Enter your first name and press enter: \n");

// Get and save the text

scanf("%s", firstName);

// Output the text

printf("Hello %s", firstName);

return 0;

11
C Programming Basics

Note: When working with strings in scanf(), you must specify the size of the string/array (we
used a very high number, 30 in our example, but atleast then we are certain it will store enough
characters for the first name), and you don't have to use the reference operator (&).

However, the scanf() function has some limitations: it considers space (whitespace, tabs, etc) as a
terminating character, which means that it can only display a single word (even if you type many
words). For example:

char fullName[30];

printf("Type your full name: \n");

scanf("%s", &fullName);

printf("Hello %s", fullName);

// Type your full name: Usman idris

// Hello Usman

From the example above, you would expect the program to print "Usman Idris", but it only prints
"Usman".
That's why, when working with strings, we often use the fgets() function to read a line of text.
Note that you must include the follow arguments: the name of the string variable,

sizeof(string_name), and stdin:


char fullName[30];
printf("Type your full name: \n");
fgets(fullName, sizeof(fullName), stdin);
printf("Hello %s", fullName);
// Type your full name: Usman Idris
// Hello Usman Idris

Use the scanf() function to get a single word as input, and use fgets() for multiple words.

Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:

Example int myNum = 100 + 50;


#include <stdio.h>
int main() {
int myNum = 100 + 50;

12
C Programming Basics

printf("%d", myNum);
return 0;
}
Although the + operator is often used to add together two values, like in the example above, it
can also be used to add together a variable and a value, or a variable and another variable:

#include <stdio.h>

int main() {
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
printf("%d\n", sum1);
printf("%d\n", sum2);
printf("%d\n", sum3);
return 0;
}
C Divides the operators into the following groups:

 Arithmetic operators

 Assignment operators

 Comparison operators

 Logical operators

 Bitwise operators

Arithmetic operators are used to perform common mathematical operations.


Operator Name Description Example
+ Addition Adds together two values a+b
- Subtraction Subtracts one value from a-b
another
* Multiplication Multiplies two values a*b
/ Division Divides one value by another a/b
% Modulus Returns the division remainder a%b
++ Increment Increases the value of a ++a
variable by 1
-- Decrement Decreases the value of a --a
variable by 1

13
C Programming Basics

Example:

#include <stdio.h>
int main() {
int x = 5;
int y = 3;
printf("%d", x + y);
return 0;
}

Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
The addition assignment operator (+=) adds a value to a variable:
Example:
#include <stdio.h>
int main() {
int x = 10;
x += 5;
printf("%d", x);
return 0;
}
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.
The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values
are known as Boolean values, and you will learn more about them in
the Booleans and If..Else lectures
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

#include <stdio.h>

int main() {

int x = 5;

14
C Programming Basics

int y = 3;

printf("%d", x > y); // returns 1 (true) because 5 is greater than 3

return 0;

}
A list of all comparison operators:

Operator Name Example

== Equal x==y

!= Not equal to x !=y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x<=y

Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:

Operator Name Description


&& Logical and Returns true if both statements are true
|| Logical or Returns true if one of the statements is true
! Logical not Reverse the result, returns false if the result is true

Examples: Logical and

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

15
C Programming Basics

// Returns 1 (true) because 5 is greater than 3 AND 5 is less than 10

printf("%d", x > 3 && x < 10);

return 0;

Example: Logical or

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

// Returns 1 (true) because one of the conditions are true (5 is greater than 3, but 5 is not less
than 4)

printf("%d", x > 3 || x < 4);

return 0;

Example: Logical not

#include <stdio.h>

int main() {

int x = 5;

int y = 3;

// Returns false (0) because ! (not) is used to reverse the result

printf("%d", !(x > 3 && x < 10));

return 0;

16
C Programming Basics

Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:

 YES / NO
 ON / OFF
 TRUE / FALSE

Booleans represent values that are either true or false.

Booleans Variable:

In C, the bool type is not a built-in data type, like int or char.

It was introduced in C99, and you must import the following header file to use it:

#include <stdbool.h>

A boolean variable is declared with the bool keyword and can only take the values true or false:

Before trying to print the boolean variables, you should know that boolean values are returned as
integers:

1 (or any other number that is not 0) represents true

0 represents false

Example:

#include <stdio.h>

#include <stdbool.h> // Import the boolean header file

int main() {

bool isProgrammingFun = true;

bool isFishTasty = false;

printf("%d\n", isProgrammingFun); // Returns 1 (true)

printf("%d", isFishTasty); // Returns 0 (false)

return 0;

17
C Programming Basics

Conditions and If Statements


C has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of code to be executed if a condition is true.

Syntax

if (condition)

{
// block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is
true, print some text:

Example:

#include <stdio.h>

int main() {

if (20 > 18) {

printf("20 is greater than 18");

return 0;

Example:

#include <stdio.h>

int main() {

18
C Programming Basics

int x = 20;

int y = 18;

if (x > y) {

printf("x is greater than y");

return 0;

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example:

#include <stdio.h>

int main() {

int time = 20;

if (time < 18) {

printf("Good day.");

else {

printf("Good evening.");

19
C Programming Basics

return 0;

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Example:

#include <stdio.h>

int main() {

int time = 22;

if (time < 10) {

printf("Good morning.");

} else if (time < 20) {

printf("Good day.");

} else {

printf("Good evening.");

return 0;

20
C Programming Basics

Switch Statement

Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

Syntax

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

 The switch expression is evaluated once


 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break statement breaks out of the switch block and stops the execution
 The default statement is optional, and specifies some code to run if there is no case match

The example below uses the weekday number to calculate the weekday name:

Example:

#include <stdio.h>

int main() {

int day = 4;

switch (day) {

case 1:

printf("Monday");

break;

21
C Programming Basics

case 2:

printf("Tuesday");

break;

case 3:

printf("Wednesday");

break;

case 4:

printf("Thursday");

break;

case 5:

printf("Friday");

break;

case 6:

printf("Saturday");

break;

case 7:

printf("Sunday");

break;

return 0;

22
C Programming Basics

The break Keyword

When C reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more
testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

#include <stdio.h>

int main() {

int day = 4;

switch (day) {

case 6:

printf("Today is Saturday");

break;

case 7:

printf("Today is Sunday");

break;

default:

printf("Looking forward to the Weekend");

return 0;

23
C Programming Basics

Note: The default keyword must be used as the last statement in the switch, and it does not need
a break.

s
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
// code block to be executed
}

Example:
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Note: Do not forget to increase the variable used in the condition (i++), otherwise the loop will
never end!
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax

Do{
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested:

#include <stdio.h>
int main() {
int i = 0;
do {

24
C Programming Basics

printf("%d\n", i);
i++;
}
while (i < 5);
return 0;
}

For Loop

When you know exactly how many times you want to loop through a block of code, use the for
loop instead of a while loop:

Syntax:

for (statement 1; statement 2; statement 3) {


// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example:

#include <stdio.h>

int main() {

int i;

for (i = 0; i < 5; i++) {

printf("%d\n", i);

}
return 0;
}

Another example to print even numbers


25
C Programming Basics

#include <stdio.h>
int main() {
int i;
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
return 0;
}

26

You might also like