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

LP 2

This document provides an introduction to basic C programming concepts such as variables, data types, and input/output functions. It explains that variables store and manipulate data during program execution, and each has a specific data type that determines the size and type of data it can hold. Common C data types include integers, floating-point numbers, and characters. The printf and scanf functions allow output and input of data to/from the user.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

LP 2

This document provides an introduction to basic C programming concepts such as variables, data types, and input/output functions. It explains that variables store and manipulate data during program execution, and each has a specific data type that determines the size and type of data it can hold. Common C data types include integers, floating-point numbers, and characters. The printf and scanf functions allow output and input of data to/from the user.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

1 | Computer Programming 1 7

UNIT II: C Programming Basics


2.0 Learning Outcomes
After completing this module, you will be able to:
a. Create basic C programming codes

2.1 Introduction
In this module, we will delve into the fundamentals of C programming and equip
you with the necessary knowledge to create basic C programs.

2.2 Topics/Discussion
This module covers the following topics:

2.2.1 Variables
In C programming, a variable is a named storage location in the computer's memory
that is used to hold a value. Variables allow programmers to store and manipulate data
during the execution of a program. Each variable has a specific data type, which determines
the size and type of data it can hold (e.g., integer, character, floating-point number, etc.).

Let's consider a real-world example of a variable in the context of everyday life:

Bank Account Balance


Imagine you have a bank account, and the amount of money you have in that account can
be seen as a variable. Let's call it accountBalance. The accountBalance variable represents
the current amount of money you have in your bank account.
Throughout the month, you receive income (e.g., salary, payments, etc.) that increases your
accountBalance, and you also make expenses (e.g., bills, purchases, etc.) that decrease your
accountBalance.
For instance:
 At the beginning of the month, you might start with an accountBalance of $1000.
 When you receive your salary, you add $2000 to your accountBalance.
 After paying rent and utility bills, you subtract $800 from your accountBalance.
 You go shopping and spend $150 on groceries, further reducing your
accountBalance.
 You get a gift of $50 from a friend, adding to your accountBalance.
At any given point in time, your accountBalance reflects the total amount of money you
currently have available in your bank account. It changes dynamically as you receive
income or make expenses, just like a variable in programming changes its value during the
program's execution.

To use a variable in C, you must first declare it, specifying its data type and giving it a
name. The general syntax for declaring a variable is:
data_type variable_name;
1 | Computer Programming 1 8

Variable name may be consist of letter, digits and under line(_) with following the below
rules - 1) They must begin with a letter. 2) Upper case & lower case are significant mean
total is differ. 3) Variable name should not be a keyword.
In some languages, you can create variables as you go along and put whatever data you
want into them. C isn’t like that: to use a variable in C, you need to have created it first, and
at the time you create it, you have to set what type of value it’s going to store. By doing
this, a block of memory of the correct size can be allocated by the compiler to hold the
variable. This process of creating a variable is known as declaration.

The top three lines inside the main function here are declarations. They tell the
compiler that we would like to use variables called a, b, and c respectively, and that each
one is of type int, i.e. an integer.
In the second line, we see an example of an initialization at the same time as a
declaration:
This stores an initial value of 3 in the variable b. Note that the values of a and c at this point
are undefined; you might assume that a variable which hasn’t had a value stored in it is
always 0, but that isn’t the case in C. Before reading the value from a variable or using it in
a calculation, you must store a value in it; reading a variable before initializing it is a
common error in C.
The next two lines do some actual work with the variables we have declared.
a = 2;
This stores a value of 2 in the variable a, which will now have this value until it’s changed.
The reason a is called a variable is that it can vary: you can change its value as often as you
like, but only to another integer. The value of a variable can change, but its type is fixed
when it is declared.
c = a + b;
This line adds a to b, and stores the result in c.

printf ("The sum of adding %d and %d is %d\n", a, b, c);


This is another use of the formatted print function we saw in the previous chapter. Note the
three %d symbols inside the string: these are format specifiers, and they are how you
output numbers in C. When the printf function is executed, each %d is replaced by a
decimal representation (d for decimal integer) of the variable in the corresponding position
in the list after the string. So the first %d will be replaced by the value of a, the second with
the value of b, and the third with the value of c.
Compile the program above and then run it. You should see this in the terminal:
1 | Computer Programming 1 9

The sum of adding 2 and 3 is 5

Naming variables
Every variable has an identifier or a name. A variable name is an identifier; function
names are identifiers. We will encounter other kinds of identifiers that are used in many
different contexts. An identifier, or name, in C is a sequence of capital letters (A..Z) and
small letters (a..z), digits (0..9), and the underscore (_) character. An identifier may not
begin with a digit. Upper and lowercase letters are different from each other, so achar,
aChar, AChar, and ACHAR would identify different variables. An identifier may not have
the same spelling as a C keyword.

As with function identifiers, relying on the casing of letters to differentiate variables


is not good programming practice. The most essential guideline is that variable names
should closely match the kinds of values they hold. Use variables names that reflect their
purpose – for example, inch, foot, yard, and mile. There are many conventions for naming
variables. Two common methods for making variable names descriptive yet easy to read
are camel case and underscore-separated, also known as snake case. Camel case names
have the beginning characters of words within the name capitalized. In underscore-
separated names, _ is used between words:

• All lowercase: inchesperminute, feetpersecond, and milesperhour


• Camel case: inchesPerMinute, feetPerSecond, and milesPerHour
• Snake case (or underscore-separated): inches_per_minute, feet_per_second,
and miles_per_hour

As you can see, all lowercase names are somewhat difficult to read. However, these
are not nearly as difficult to read as all-uppercase names. The other two ways are quite a bit
easier to read. Therefore, we prefer to use either of the last two. If you choose one identifier
naming convention, stick to it throughout your program. Do not mix different identifier
naming schemes as this makes remembering the exact name of a thing, function identifiers,
and other identifiers much more difficult and error-prone.

2.2.2 Basic Datatypes


In C programming, there are several basic data types that represent the fundamental
building blocks for storing different kinds of data. The basic data types in C can be broadly
categorized into the following groups:
1. Integer Types:
o int: Represents signed integers, typically ranging from -2147483648 to
2147483647 on most systems (32-bit).
o short: Represents shorter signed integers, usually ranging from -32768 to
32767 (16-bit).
o long: Represents longer signed integers, with a wider range than int, typically
-2147483648 to 2147483647 on most systems (32-bit).
o long long: Represents very long signed integers, with an even wider range,
often -9223372036854775808 to 9223372036854775807 on most systems (64-bit).
1 | Computer Programming 1 10

2. Floating-Point Types:
o float: Represents single-precision floating-point numbers, typically 32 bits in
size.
o double: Represents double-precision floating-point numbers, usually 64 bits
in size.
o long double: Represents extended-precision floating-point numbers,
implementation-specific, and larger than double.
3. Character Type:
o char: Represents a single character, such as 'A', 'b', or '$'. It has a size of 1 byte.

Please note that there is not a Boolean data type. C does not have the traditional
view of logical comparison. Actually, data types in C are listed under three main
categories:
(a) Primary data type (b) Derived data type (c) User-defined data type

In C, the unsigned keyword is used to declare unsigned integer types. Unsigned


integers are non-negative integers, meaning they can only represent positive numbers
or zero. They cannot store negative values. The unsigned keyword is typically used with
integer data types such as int, short, long, and char, to specify that the variable should only
hold positive values.
For example, you can declare unsigned variables as follows:
1 | Computer Programming 1 11

Unsigned integers have a larger positive range than their signed counterparts
because they do not need to reserve one bit for representing the sign. For example, an
unsigned int can represent values from 0 to UINT_MAX, where UINT_MAX is the maximum
value that can be represented by an unsigned int.
The exact range of values that can be represented by each unsigned integer type
depends on the platform and the compiler. However, the standard guarantees certain
minimum ranges:

2.2.3 printf() and scanf()


In C, printf is a standard library function used for formatted output. It stands for
"print formatted" and is part of the stdio.h header file, which provides functions for input
and output operations.

The printf function allows you to display text and values on the screen or write them
to a file. It uses a format string that specifies the layout of the output and includes optional
format specifiers to indicate how to display variables of different data types.

 The format parameter is a string that contains the text to be printed, along with
format specifiers (%) that define the output format for variables.
 After the format parameter, you can pass additional arguments that correspond to
the format specifiers in the format string. These arguments will be displayed
according to their respective format specifiers.
Format specifiers are placeholders in the format string that determine how different data
types should be printed. For example, %d is a format specifier for an integer, %f for a
floating-point number, %s for a string, etc.

Here's an example of using printf to display text and the value of a variable:

In this example, the format string contains the text "The value of num is " along with
the format specifier %d, which indicates that an integer value will be printed at that
position. The actual value of num is passed as an argument to printf to be displayed in the
output.
The printf function is a powerful tool for formatting output, and you can customize
the display in various ways using different format specifiers and additional options.
However, be cautious when using it with user-supplied data to avoid security
1 | Computer Programming 1 12

vulnerabilities such as format string vulnerabilities. Always validate and sanitize user input
to ensure the safe use of printf and other similar functions.

In C, scanf is a standard library function used for formatted input. It stands for "scan
formatted" and is part of the stdio.h header file, which provides functions for input and
output operations.

The scanf function allows you to read data from the user or a file based on a
specified format. It uses a format string that contains format specifiers (%) to indicate how
to read data of different types.

 The format parameter is a string that contains format specifiers for the data you
want to read.
 After the format parameter, you can pass pointers to variables where the read data
will be stored. The scanf function will attempt to parse the input according to the
format specifiers and store the values in the provided variables.
Format specifiers are placeholders in the format string that determine how different data
types should be read. For example, %d is a format specifier for an integer, %f for a floating-
point number, %s for a string, etc.

Here's an example of using scanf to read an integer from the user:

In this example, the format specifier %d in the scanf function indicates that an
integer should be read from the user's input. The address of the variable num is passed as
an argument to scanf, allowing it to store the user's input in that variable.

It's important to be careful when using scanf, as it can be prone to input errors or
buffer overflow issues. Always ensure that the input matches the specified format and
consider using safer input functions like fgets for reading strings. Additionally, when using
scanf, be mindful of how it handles characters such as spaces and newline characters,
which can affect the reading of input.
In C, "formats" typically refer to format specifiers used in formatted input and output
functions like printf and scanf. Format specifiers are placeholders in the format strings that
determine how different data types are displayed (in the case of printf) or read (in the case
of scanf).

Here are some commonly used format specifiers in C:


1 | Computer Programming 1 13

2.2.4 Operators
In addition to variable and types, all programming languages support the concept of
operators. C has over 40 different operators, but hardly all of them are used. There are eight
C operators that turn up in almost every program. Right now the concentration will be on
following operators.

 Arithmetic operators.
 Assignment operators
 Modulus operators
 Increment and decrement operators.
 Relational operator
 Logical Operator
 Conditional Operator
 Bitwise Operator
 Special Operator

Before, we discuss about operators, let us discuss about expression. An expression consists
of references to previously defined values such as identifiers and constants. Expression
1 | Computer Programming 1 14

usually contain one or more operators. These operators and expressions are evaluated,
according to the standard C language rules. An operator may take one or more operands
and operands in turn can consist of previously declared identifiers, constants, functions etc.

The statement has two operators, Arithmetic operators + and assignment operator =,
and three operands a, 1 and 2. The effect of this statement is to add the constants 1 and 2
together and assign the result to the variable a, which must have declared as int in the
beginning of program. Thus, the assignment operator = in C is not used like the equal sign
of algebra. Following are the selected standard mathematical functions. Here, while
describing the functions, it has been assumed that variable x and y are declared as double
except in trigonometric and hyperbolic functions, where they are defined as radians. All
these functions return a double value.
1 | Computer Programming 1 15

PRECEDENCE AND ASSOCIATIVITY


The example above contains the operators, which means it must be evaluated into
two steps.

We first add 1 to 2, then we assign the result to a. But how do we know that C will
carry out the operations in that exact order. It is because C has a built-in set of rules that
govern the order in which operations are evaluated. Also C provides the facility to assign a
value to a series of variables in the same statement. Consider the following example :
a = b = c = d = 1;
A series of assignment like this is always performed one at a time from right to left. Thus C
executes the statement as follows:

 assign the constant value 1 to d.


 assign the result of above assignment to c.
 assign the result of above assignment to b.
 assign the result of above assignment to a.
Thus in above case, the values were calculated from right to left. The following table
describes the associativity and precedence of operator being used in C.
1 | Computer Programming 1 16

2.2.5 Decision Making


A language is incomplete if it doesn’t have decision making capabilities. These
decision making capabilities can be used to execute different set of instructions under
different conditions. e.g. a bank may decide on the interest to be given to customer on the
basis of the amount deposited in the bank. If amount exceeds a particular value, say x,
the interest paid will be 15% or else it will be 10%. Thus, here a decision is to be made -
whether the amount is greater than x or not. If amount is greater than x, calculate the
interest with 15% rate of interest or else calculate the interest with 10% rate of interest.
For such cases, C has various decision making tools, which helps in taking decision and
instructing computer to execute the right set of instructions. These are -
 if statement
 switch statement
 Conditional operator statement
 goto statement
 do....while statement

If Statement
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested.
 Simple if statement
 if........else statement.
 Nested if........ else statement.
 else if ladder.
1 | Computer Programming 1 17

Simple If Statement
The general form of a simple If statement is

The statement group could have a single statement or a group of statements. The
condition is defined as entity and it can have two values - true or false. If the test condition
is true, the statement group is executed, otherwise, the statement group is skipped and the
execution will jump to next statement. If the condition is true both statement group is
executed followed by the Next Statement. The following figure represent flow chart for the
If statement:

Consider the following segment of a program

The above part of the program test whether the deposited amount is greater than
4000 or not. If yes, the interest @ of 15% is calculated & then it is printed.

The if else statement


The if else statement is an extension of simple if statement. The general form is
1 | Computer Programming 1 18

Here the difference is that another set of instructions has been added for false
condition using else. If the test condition is true, the true statements are executed,
otherwise, the control moves to false statements. Thus here one of the two group of
statements are executed. In no case, both the sets of instructions can be executed
simultaneously. This flow chart is illustrated in the figure:

As you can see from the flow chart, only one set of instruction are being executed on
the basis of true or false condition. In both the cases, the control is transferred subsequently
to next statement.

Nested if else statement


The if statement is termed Nested if statement, if the true statements or the false statements
or both contains other if statements. This will happen, when a series of decisions are
involved:
1 | Computer Programming 1 19

The nesting of conditions may be sometimes confusing, it is recommended that nesting


conditions always be balanced by having each if clause paired with else, as shown above.
Now let us consider the results produced by the above nested If statement under different
conditions -
 If condition 1 is true, the control is transferred to the If condition 2 or else the control
is transferred to If-condition 3.
 Statement group 1 is executed when both the condition-1 and condition-2 are true.
 Statement group 2 is executed when condition 1 is true and condition 2 is false.
 Statement group 3 is executed when condition 1 is false and condition 3 is true.
 Statement group 4 is executed when both the condition 1 and condition 3 are false.

The switch Statement


Your program may need to make more than two or three decisions based on a single
response. A series of If-else statements could do the job, but, then there is an easier way: use
the switch statement. With the switch statement, the if-else tests are made into alternative
switches of one long conditional statement. Now, C chooses the first case, the second case,
or whichever other case matches the user’s response and executes the block of statement
associated with that case.

The general form of the switch statement is as shown:


1 | Computer Programming 1 20

Here each case is labeled by one or more integer-valued constant or constant expressions. If
a case matches the value, the statement group associated with the case is executed. The
break statement at the end of each statement group indicates the end of execution and
causes exit from the switch statement. At the bottom, the default switch is given which is
optional. If value of expression doesn’t matches with any of the case value, the default
statement is executed, if it is present, otherwise no action takes place and control goes to
next-statement.

goto Statement
The goto statement in C is used to transfer the control of the program to a labeled
statement within the same function. However, the use of goto is generally discouraged in
modern programming practices because it can lead to hard-to-read and hard-to-maintain
code. In most cases, structured control flow constructs like if, else, for, while, and switch
provide better alternatives.

Nevertheless, here is an example of how the goto statement can be used:


1 | Computer Programming 1 21

2.2.6 Looping
Looping consists of series of statements that are executed until some conditions for
termination of loop are satisfied. A program loop consist of normally two segments.
 body of the loop
 Control statement.
The control statement tests the conditions and then directs the repeated execution of the
series of statements contained in the body of the loop. Thus, a loop is defined as a block of
processing steps repeated a certain number of times. An endless loop repeats infinitely and
is always the result of an error. Looping can be classified into two categories; Entry-
controlled loop or Exit-controlled loop. Entry controlled loop first testify the condition and
then executes the series of statements whereas Exit controlled loop first executes the
statements and then testify the condition. Or in other words, Entry controlled loop starts
with the testing condition and Exit control loop ends with the testing condition.

The general method of looping is by using counters and then testing it using the if
statement. Every time the series of statement are executed, the counter increases or
decreases its value by a fixed number. And the value of this counter is tested after every
execution of series of statements. If the testified condition is not met, the series of
statements are executed again and this process continues till the condition is met.

e.g. Write a program for calculating the salary of 100 workers in a factory.

In figure given below, step 2 is for initialization of the value of COUNT where
COUNT is an active variable. Step 7 is the increment. Step 3 is for the EXIT test. Steps 4 to 6
are the repetitive steps in the loop to input the NAME, WAGE and HOURS and then
calculate the value of PAY in step 5 and print the name and pay in step 6. In step 7, the
value of COUNT is increased by 1 and the current value of COUNT is compared with 100
in step 3. If it is more than 100, the process is halted.
1 | Computer Programming 1 22

For Loop
In C programming, a for loop is a control flow statement used to repeatedly execute
a block of code based on a condition. The syntax of the for loop in C is as follows:

 initialization: This part is executed only once before the loop starts. It initializes
the loop control variable.
 condition: This is the condition that is evaluated before each iteration. If the
condition is true, the loop continues; otherwise, it terminates.
 update: This part is executed after each iteration and is usually used to modify
the loop control variable.

Here's a simple example to print the numbers from 1 to 5 using a for loop:
1 | Computer Programming 1 23

In this example, the loop control variable i is initialized to 1. The condition checks if i
is less than or equal to 5. If true, the loop body is executed, which prints the value of i. After
each iteration, the update i++ increments the value of i by 1, and the loop continues until
the condition becomes false.

While Loop
In C programming, a while loop is another type of control flow statement used to
repeatedly execute a block of code as long as a certain condition is true. The syntax of the
while loop in C is as follows:

 condition: This is the condition that is evaluated before each iteration. If the
condition is true, the loop continues; otherwise, it terminates.

Here's a simple example to print the numbers from 1 to 5 using a while loop:

In this example, the loop control variable i is initialized to 1. The while loop checks if
i is less than or equal to 5. If true, the loop body is executed, which prints the value of i.
After each iteration, the value of i is incremented by 1 using i++, and the loop continues
until the condition becomes false.

It's important to ensure that the loop control variable or the condition inside the while loop
is modified within the loop to avoid infinite loops, where the condition is always true, and
the loop never terminates.

Do While Loop
In C programming, a do-while loop is another type of control flow statement used to
repeatedly execute a block of code at least once, and then continue executing it as long as a
certain condition is true. The syntax of the do-while loop in C is as follows:

 condition: This is the condition that is evaluated after each iteration. If the
condition is true, the loop continues; otherwise, it terminates.
1 | Computer Programming 1 24

The key difference between a do-while loop and a regular while loop is that the do-while
loop guarantees that the code inside the loop will be executed at least once, regardless of
the initial condition.

Here's a simple example to print the numbers from 1 to 5 using a do-while loop:

In this example, the loop control variable i is initialized to 1. The do-while loop
executes the code inside the loop, which prints the value of i, and then increments i by 1
using i++. After each iteration, the do-while loop checks if i is less than or equal to 5. If true,
the loop continues; otherwise, it terminates.

Since the condition is evaluated after each iteration, the loop body is executed at
least once before the condition is checked. This makes the do-while loop useful in situations
where you want to ensure that a certain block of code runs at least once before the loop
condition is evaluated.

ASSESMENT

1. What is the purpose of variables in C programming?


2. Provide an example of a real-world variable and its analogy to C programming.
3. What is the syntax for declaring a variable in C?
4. Explain the concept of camel case and underscore-separated variable naming
conventions in C.
5. Name the basic data types in C and briefly describe each
6. What is the purpose of the scanf() function in C?
7. Explain the purpose of the if-else statement in C and provide a code example.
8. What is the purpose of the for loop in C, and provide a code example.
9. Describe the while loop in C and provide a code example.
10. What is the main difference between a for loop and a do-while loop in
11. What is the purpose of the switch statement in C, and provide a code example.
12. Explain the concept of entry-controlled and exit-controlled loops.
1 | Computer Programming 1 25

13. What is the purpose of the break statement in a loop?


14. Describe the use of the goto statement in C and why it is generally discouraged.
15. What are the common types of format specifiers used in printf() and scanf()
functions in C?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy