0% found this document useful (0 votes)
19 views24 pages

COSC 206 Lecture 1 and 2

The document provides an introduction to C programming, covering its history, features, structure, and syntax. C is a high-level, general-purpose language developed in the 1970s, known for its efficiency and portability, making it suitable for system and application programming. It also details the C compilation process and the essential components of a C program, including examples of basic C code.

Uploaded by

dlovefky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views24 pages

COSC 206 Lecture 1 and 2

The document provides an introduction to C programming, covering its history, features, structure, and syntax. C is a high-level, general-purpose language developed in the 1970s, known for its efficiency and portability, making it suitable for system and application programming. It also details the C compilation process and the essential components of a C program, including examples of basic C code.

Uploaded by

dlovefky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

COSC 206

Introduction to C programming

Lecture 1: Introduction

What is C Programming?
Brief History of C Programming
Features of C Programming
Structure of C program
First C Example
C compilation Process
C Syntax
C Tokens

What is C Programming?

C Programming is a high-level, general-purpose programming language that was developed in the 1970s
by Dennis Ritchie at Bell Labs. It is a compiled language that allows developers to create efficient, low-
level programs while also providing high-level abstractions that make it easy to write complex programs.
C is a popular language for system programming, including operating systems, device drivers, embedded
systems, and other low-level applications. It is also widely used in application programming, including
business applications, scientific applications, and games.
Overall, the C language has had a significant impact on the field of computer science and programming,
and it remains a popular choice for developers today due to its power, efficiency, and flexibility

Brief History of C Programming Language

C programming language was created by Dennis Ritchie at Bell Laboratories in 1972. However, its
development began in 1969 as an internal project at Bell Labs, with Ken Thompson as the lead developer.
The development of C language was initially intended to create a language for developing the Unix
operating system. It was designed to be a low-level language that provided direct access to the system
hardware, making it suitable for system programming.
C programming language was developed as a successor to the B programming language. B was developed
by Ken Thompson at Bell Labs in 1970, which was derived from the BCPL programming language
developed by Martin Richards.
B was an interpreted language, and its performance was poor. Ritchie then developed C programming
language, which was faster and more efficient than B.

1
The early versions of C were developed on the DEC PDP-11 computer using the Unix operating system. C
programming language became popular with the release of Unix Version 6 operating system in 1975. As
Unix became more popular, so did C programming language.
In 1978, the first edition of "The C Programming Language" book, also known as the K&R C book, was
published by Brian Kernighan and Dennis Ritchie. The book became very popular and played a significant
role in the widespread adoption of C programming language.
C programming language was standardized by the American National Standards Institute (ANSI) in 1989.
The ANSI C standard, also known as C89 or C90, provided a common specification for C programming
language, which helped in portability and interoperability of C programs.
In 1999, the ISO (International Organization for Standardization) released the C99 standard, which added
several new features to the language, such as inline functions, variable-length arrays, and support for IEEE
floating-point arithmetic.
Since then, there have been several revisions to the C programming language, including C11 and C18. The
latest version of the C standard, C2x, is currently under development and is expected to be released in the
coming years.
Despite being over 50 years old, C programming language is still widely used today for system
programming, embedded systems, and high-performance computing applications. It has influenced the
development of many other programming languages, including C++, Java, and Python, and has left a
significant impact on the field of computer science.

Features of C programming Language

C programming language has several features that make it a popular choice for developing a wide range of
applications. Some of the key features of C programming language are:

 Simple and Easy to Learn: C programming language is a simple language with a small number of
keywords and constructs, making it easy to learn for beginners. At the same time, it provides
powerful features for low-level programming, such as direct access to memory, efficient use of
resources, and precise control over program flow.

 Portable: C programs can be written and compiled on different platforms, including Windows, Mac,
and Linux, making it a portable language. This is due to the use of a standard set of libraries and
compilers, such as the GNU Compiler Collection (GCC), which are available on many platforms.

 High-level Language: C programming language is a high-level language that provides abstracted


programming concepts, allowing programmers to focus on the logic of the program rather than
machine-level details.

 Structured Programming: C programming language supports structured programming constructs


like loops, conditional statements, and functions, allowing developers to write structured, easy-to-
read code.

2
 Efficient Memory Management: C programming language provides manual memory management,
allowing developers to control the allocation and de-allocation of memory, resulting in efficient
memory utilization.

 Rich Library Support: C programming language has a rich set of libraries that provide access to a
wide range of functions, making it easy to implement complex functionality.

 Speed: C programming language is a compiled language, resulting in faster execution times


compared to interpreted languages.

 Low-level Language Features: C programming language provides low-level language features like
direct access to memory and pointers, making it possible to implement low-level functionality.

 Platform-Specific Programming: C programming language allows for platform specific


programming, making it possible to write code that interacts directly with the hardware.

 Overall, the combination of simplicity, portability, efficiency, and rich functionality makes C
programming language a powerful tool for developing a wide range of applications.

Why learn C programming?


• Compact, fast, and powerful

• “Mid-level” Language

• Standard for program development (wide acceptance)

• It is everywhere! (portable)

• Supports modular programming style

• Useful for all applications

• C is the native language of UNIX

• Easy to interface with system devices/assembly routines

• Mother language

3
Structure of C Program

Understanding the various part of C program Structure


1. Documentation section: The documentation section consists of a set of comment lines giving the
name of the program, the author and other details, which the programmer would like to use later.

2. Link section: The link section provides instructions to the compiler to link functions from the
system library such as using the #include directive.

3. Definition section: The definition section defines all symbolic constants such using the #define
directive.

4. Global declaration section: There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration section that is
outside of all the functions. This section also declares all the user-defined functions.

5. main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part.

4
a. Declaration part: The declaration part declares all the variables used in the executable part.
b. Executable part: There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces. The program execution
begins at the opening brace and ends at the closing brace. The closing brace of the main function
is the logical end of the program. All statements in the declaration and executable part end with a
semicolon.

6. Subprogram section: If the program is a multi-function program then the subprogram section
contains all the user-defined functions that are called in the main () function. User-defined functions
are generally placed immediately after the main () function, although they may appear in any order.
Although not all c programs will include all of the above sections, you may find them in a real
world C program. Hence, the need to understand the various sections. The figure below shows a
simple program that demonstrates the usage of the various sections of C program explained above.

5
Structure of C Program: An Example

6
Example 1: A program that welcome you to the course

//Our first C Program


#include <stdio.h> // include header files for io
// main function
int main() // entry point
{
//print message to the screen
printf("Welcome to C Programming \n");
return 0; // exit (0 => success)

The table below gives a description of the above program explaining the various part of the
program

Documentation Our first C program

Include header file for standard input-output. This is the preprocessor/link


#include<stdio.h> section.

int main() main is the first function that is executed in the program.

{… Opening curly brace mark the beginning of the main function.

printf() Print the string literal “welcome to c programming” on the Screen

…} Closing curly brace mark the end of the main function

return 0 Exit the main function, returning 0 to the caller

7
Example 2: A simple C program that adds two integers

/* Sum of two Integers */


#include<stdio.h>
int main()
{
int a, b, sum;
printf("Enter two numbers to be added "); // prompt user for input
scanf("%d %d", &a, &b); // takes input from user
sum = a + b; // calculating sum
printf("%d + %d = %d", a, b, sum);
return 0; // return the integer value in the sum and exit
}

Description and explanation of the various part of the above program is given in the table below

Documentation Tells us what the program is all about

Include header file for standard input-output. This is the preprocessor/link


#include<stdio.h> section.

main is the first function that is executed in the program. The int main is used in
order to return an integer value
int main()

{… Opening curly brace mark the beginning of the main function.

Prompt the user to enter some input by printing the string “Enter two numbers
printf() to be added”

Reads data from standard input streams and writes the results into the specified
scanf variables

Sum = a + b Sum the content of a and b and store the result in the sum variable for output

…} Closing curly brace mark the end of the main function

8
return 0 Exit the main function, returning 0 to the caller

A closer look at printf and scanf functions

In the above examples, we have used the printf and scanf functions for printing formatted output and input
respectively, even though we don’t know how they really work. In this section, we will have a closer look
at both functions.

printf() and scanf() in C

The printf() and scanf() functions are used for output and input in C language, repectively. Both
functions are inbuilt library functions, defined in stdio.h (header file). Each time we use the statement
#include<stdio.h> in the beginning of our program, we are informing the C preprocessor that it should
include those functions. Without including them, we won’t be able to read input or print output.

printf() function

The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

printf("format string",argument_list);
The function takes two arguments:

a. Format string: A string that specifies the format of the output to be printed. This string can
contain conversion specifiers that tell printf() what type of output to print and how to print it.
The format string can be %d (integer, as we have seen in the examples above), %c (character),
%s (string), %f (float) etc.
b. A variable-length argument list that contains the memory addresses of variables whose value
will be printed.

scanf() function

The scanf() function is used for input. It reads the input data from the console.

The syntax of scanf() function is given below:

scanf("format string",argument_list);

9
The function takes two arguments:

a. format: A string that specifies the format of the input to be read. This string can contain
conversion specifiers that tell scanf() what type of input to expect and how to read it.
The format string can be %d (integer, as we have seen in the examples above), %c (character),
%s (string), %f (float) etc.
b. A variable-length argument list that contains the memory addresses of variables where the input
values will be stored. These memory addresses must be passed as pointers.

Example 3: Program to print cube of given number

1. #include<stdio.h>
2. int main(){
3. int number;
4. printf("enter a number:");
5. scanf("%d",&number);
6. printf("cube of number is:%d ",number*number*number);
7. return 0;
8. }

The program above used both printf and scanf for output and input respectively.

In line 4, printf is used to prompt the user to enter a number.

In line 5, scanf is used to enter an integer specified by %d and the value is store in the variable number

In line 6, the printf is used to print the cube of the number in the specified format

Program Sample Output

enter a number:5
cube of number is:125

C Program Compilation Process


When you try to compile a C program, a series of steps are performed in order to generate an executable
from the text you entered as your C program. These steps are as follows:

10
C Compilation Process
1. The Preprocessor
The Preprocessor accepts source code as input and is responsible for:
• removing comments
• Interpreting special preprocessor directives denoted by #. For example
• #include -- includes contents of a named file. Files usually called header files.
e.g #include -- standard library maths file.
#include -- standard library I/O file
• #define -- defines a symbolic name or constant.
#define MAX_ARRAY_SIZE 100
2. C Compiler
Once the C preprocessor has stripped the source code of the comments and expanded the preprocessor
directives given by the lines that begin with #, the compiler translates the C code into assembly language,
which is a machine level code that contains instructions that manipulate the memory and processor directly,
in a layer beneath the operating system
3. Assembler
The assembly code is converted into object code by using an assembler. The name of the object file
generated by the assembler is the same as the source file. The extension of the object file in DOS is '.obj,'

11
and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the name of the object file
would be 'hello.obj'.
4. Link Editor
Mainly, all the programs written in C use library functions. These library functions are pre-compiled, and
the object code of these library files is stored with '.lib' (or '.a') extension. The main task of the linker is to
combine the object code of library files with the object code of our program. Sometimes the situation arises
when our program refers to the functions defined in other files; then linker plays a very important role in
this. It links the object code of these files to our program. Therefore, we conclude that the job of the linker
is to link the object code of our program with the object code of the library files and other files. The output
of the linker is the executable file.

Syntax of C language
The syntax of the C programming language is characterized by a set of rules that dictate how C programs
should be written. It specify which tokens are valid and indicate the expected order of token. Some key
elements of C syntax include:

1. Case Sensitivity:

• C is case-sensitive, meaning that uppercase and lowercase letters are treated as distinct.

2. Comments:

• Comments in C are written using /* */ for multiline comments and // for single-line
comments.

3. Semicolons:

• Statements in C are terminated by semicolons (;). Each executable statement must end
with a semicolon.

4. Variables:

• Variables must be declared before use, specifying their data type. For example, int x;
declares an integer variable named "x."

C Tokens
Tokens are the smallest individual unit of a C program.
They are the basic building blocks in C language which are constructed together to write a
program.
C Consist of the following types of tokens:
i. Identifier: x, y, …
ii. Keywords: printf, int, scanf, …
iii. Constants: 5, 5.0, …
iv. Strings: “Hello”
v. Special Symbols: { } ; < > # /* */ ….

12
vi. Operators: +, -, …

For example, the following C statement consists of five tokens:

printf("Hello, World! \n");


The individual tokens are:
1. printf
2. (
3. “Hello World!\n”
4. )
5. ;

i. Identifiers
Identifiers are Names used for data and objects in C. It is used as a general terminology for the
names of variables, functions, and arrays. Identifiers allow us to name data and other objects
in the program. Each identified object in the computer is stored at a unique address.
Rules for identifiers in C:
a. first character must be alphabetic [a-z,A-Z] character or underscore (_)
b. must consist of only alphabetic, digit, underscore characters
c. first 31/63 characters are significant
d. Must not duplicate a reserved word
e. case (upper/lower) matters

Examples of valid and invalid identifiers


Valid Invalid
Sum 7of9
c4_5 x-name
A_NUMBER name with spaces
Longnamewithmanychars 1234a
TRUE int
_split_name AXYZ&

ii. C Keywords/Reserved words


C keywords or reserved words are the words that convey a special meaning to the c compiler. The
keywords already have meaning in C and therefore cannot be used as identifiers names.

13
The table below gives a list of C keywords
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while

iii. C Constant
A constant refers to the data items that do not change their value during the program execution.
C support the following types of constants:
Integer Constants
Integer constants are whole numbers without any fractional part. It must have at least one digit
and may contain either + or – sign. A number with no sign is assumed to be positive.
There are three types of integer constants:
Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or + sign.
Example of valid decimal integer constants: 341, -341, 0,8972
Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is said
to be octal integer constants. Example of valid octal integer constants: 010, 0424, 0,0540
Hexadecimal Integer Constants
Hexadecimal integer constants are integer constants having sequence of digits preceded by 0x or
0X. They may also include alphabets from A to F representing numbers 10 to 15.
Example of valid hexadecimal integer constants: 0xD, 0X8d, 0X, 0xbD
It should be noted that, octal and hexadecimal integer constants are rarely used in programming.
Real Constants
The numbers having fractional parts are called real or floating point constants. These may be
represented in one of the two forms called fractional form or the exponent form and may also
have either + or – sign preceding it.
Example of valid real constants in fractional form or decimal notation
0.05, -0.905, 562.05, 0.015
Character constant:
A character constant is either a single alphabet, a single digit, or a single special symbol enclosed
within single quotes, e.g., 'x', and can be stored in a simple variable of char type. The value of a

14
character constant is stored within single quotes and has a maximum length of 1. For example, 'x'
is a valid character constant, but 'xy' is not a valid character constant.
String constant
A string constant is a sequence of characters enclosed in double quotes; the characters may be
letters, numbers, special characters, and blank space, etc. Examples of string constants include:
1. "COSC 206"
2. "Ali"
3. "+123"
4. "1-/a"
5. "good" // string constant
6. "" // null string constant
7. " " // string constant of six white spaces
8. "x" // string constant having a single character
9. "Earth is round\n" // prints a string with a newline

iv. Special Symbols

The following special symbols are used in C, each having a specific meaning, and therefore,
cannot be repurposed for other uses: [] () {} , ; : * … = #
Braces {}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
Parentheses (): These special symbols are employed to indicate function calls and function
parameters.
Brackets []: Opening and closing brackets are utilized as array element references. They indicate
single and multidimensional subscripts.

15
Lecture 1: Review Exercise
1. Briefly explain what C programming is and its primary applications.

2. Describe the origin of the C programming language, including key figures and milestones.

3. List at least five key features of C programming and explain how each contributes to its popularity.

4. Provide three reasons why learning C programming is beneficial for a programmer.

5. Identify and describe each section of a C program's structure.

6. Explain the purpose of the main() function in C programs.

7. Examine the provided example program that prints "Welcome to C Programming" and identify
each component, such as comments, preprocessor directives, and function calls.

8. Describe the purpose of printf() and scanf() functions in C, including the syntax and how they work
with format specifiers.

9. Outline the stages of C program compilation, including the roles of the preprocessor, compiler,
assembler, and linker.

10. List and explain the types of tokens in C programming.

11. Provide examples of each token type, including identifiers, keywords, constants, and operators.

16
COSC 206
Introduction to C Programming

LECTURE 2: VARIABLES AND DATA TYPES


Variables in C

Variable declaration

Variable initialization

C data types

Symbolic Constant

Variables in C
A variable is a named memory location in which data of a certain type can be stored. The contents of a
variable can change, thus the name. User defined variables must be declared before they can be used in a
program. It is during the declaration phase that the actual memory for the variable is reserved. All
variables in C must be declared before use.
Rules for naming variable in C
i. Variable naming rules in C include the following:
ii. Variable names can consist of letters, digits, and underscores (_).
iii. Variable names must commence with letters.
iv. Keywords, such as 'for' and 'while,' cannot be utilized as variable names.
v. Variable names are case-sensitive; for instance, 'int x;' and 'int X;' declare two distinct variables.
Examples of valid and invalid variable names are given below:
int money$owed; (incorrect: cannot contain $)
int total_count (correct)
int score2 (correct)
int 2ndscore (incorrect: must start with a letter)
int long (incorrect: cannot use keyword)
Variable Declaration in C

In C, variables have to be declared before they are used. Variable declaration is the process of
explicitly informing the compiler of the characteristics of the variable. It typically involves naming
a variable, specifying its data type and optionally assigning a value to the variable .

The basic format/syntax for declaring variables in C is:

17
data_type variable name;
Where
• data_type: Represents the type of data that the variable will hold (e.g., int, float, char).
• variable_name: Is the name given to the variable, allowing you to reference it in your program.
For example, in C, you might declare an integer variable named age as follows:
int age ;
This tells the compiler to set aside memory to store an integer value under the name age. After declaring a
variable, you can then assign a value to it, like:
age = 37; // stores the value 37 in the variable
Variable declaration only reserves some memory space for the variable, but doesn’t put any value in the
variable. Values get into the memory location of the variable through initialization or assignment.
C also allow the declaration of more one variable in a single statements. C uses the following syntax for
declaring more than one variable in a single statement.

data_type variable_name1, variable_name2, variable_name3, variable_namen;


Here the variable names are separated by commas. For example, in C, you might declare variables of
the same type in a single statement as shown below:

int i, j, k; // declaring 3 variables of type int


float length, height; // declaring 2 variables of type float
char x, y; // declaring 2 variables of type char
int x = 7; // declaring and initializing a variable

Example 1: Demonstrates Variable declaration and initialization


#include <stdio.h>
main () {
int sum=33;
float money=44.12;
char letter;
double pressure;
letter='E'; /* assign character value */
pressure=2.01e-10; /*assign double value */
printf("value of sum is %d\n",sum);
printf("value of money is %f\n",money);
printf("value of letter is %c\n",letter);
printf("value of pressure is %e\n",pressure);
}
Program sample Output

18
value of sum is 33
value of money is 44.119999
value of letter is E
value of pressure is 2.010000

C Data Types
An extensive system used for declaring variables or functions of different types. The type of a variable
determines how much space it occupies in storage and how the bit pattern stored is interpreted or how it
can be manipulated in a program.
C has the following 4 types of data types

1. Basic built-in data types: int, float, double, char


2. Enumeration data type: enum
3. Derived data type: pointer, array, structure, union
4. Void data type: void
Basic build-in data types in C: integer, float, double and char.
Integer: can be used to store integer numbers (values with no decimal places). The keyword
used to define integers in C is: int.
An example of an integer value is 32. An example of declaring an integer variable called age is:
int age;
float: can be used for storing floating-point numbers (values containing decimal places). The
keyword used to define float variables in C is: float.
Typical floating point values are 1.73 and 1.932e5 (1.932 x 105). An example of declaring a float
variable called x is:
float x;
double: the same as type float, only with roughly twice the precision. The keyword used to
define double variables in C is: double.
An example of declaring a double variable called voltage is:
double voltage;

char: can be used to store a single character, such as the letter ‘a’, the digit character ‘6’, or a
semicolon ‘;’. The keyword used to define character variables in C is: char.
An example of declaring a character variable called letter is:
char letter;
Example 2: Using basic data types
#include <stdio.h>
int main (void)
{

19
// declaration and initialization
int integerVar = 100;
float floatingVar = 331.79;
double doubleVar = 8.44e+11;
char charVar = 'W';
// printing the variables values
printf ("integerVar = %d\n , ",integerVar);
printf ("floatingVar = %f\n", floatingVar);
printf ("doubleVar = %e\n", doubleVar);
printf ("doubleVar = %g\n", doubleVar);
printf ("charVar = %c\n" , charVar);
return 0;
}
Data types Sizes and ranges
Every type has a size and range of values that its supports. This range is determined by the amount
of storage that is allocated to store a value belonging to that type of data. In general, that amount
of storage is not defined in the language. It typically depends on the computer you’re running, and
is, therefore, called implementation- or machine-dependent.
For example, an integer might take up 32 bits on your computer, or it might be stored in 64. You
should never write programs that make any assumptions about the size of your data types. The
language standards only guarantees that a minimum amount of storage will be set aside for each
basic data type. For example, it’s guaranteed that an integer value will be stored in a minimum of
32 bits of storage, which is the size of a “word” on many computers.
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in
bytes. The following is an example to get the size of int type on any machine:
Example 3: Determining the size of int data type on any machine

#include <stdio.h>
#include <limits.h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));

return 0;
}

20
When you compile and run the above program, it produces the following output
Program Sample output
size of int = 4

Example 4: Determining the size, range and precision of float data type on any machine
#include <stdio.h>
#include <float.h>
int main()
{
printf("Storage size for float : %d \n", sizeof(float));
printf("Minimum float positive value: %E\n", FLT_MIN );
printf("Maximum float positive value: %E\n", FLT_MAX );
printf("Precision value: %d\n", FLT_DIG );
return 0;
}
When you compile and run the above program, it produces the following output
Program sample output
size of float = 4
float min = 1.175494E-38
float max = 3.402823E+38
float precision = 6
The following table gives you details about the basic types with their storage sizes and
value ranges:

Basic data type Size (byte) Value Range


char 1 -128 to 127
unsigned char 1 0 to 255
int 2 or 4 -32768 to 32767 or -2147483648 to 2147483647
unsigned int 2 or 4 0 to 65535 or 0 to 4,294,967,295

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

long int 4 -2147483648 to 2147483647

21
unsigned long int 4 0 to 4294967295
float 4 -3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
Long double 10 3.4E-4932 to 1.1E+4932

Defining symbolic Constant


Symbolic constants represent constant values, from the set of constant types mentioned in lecture 1, by a
symbolic name. These constant are generally defined at the beginning of the program using the following
syntax:
#define identifier value
Here identifier is generally written in upper case for example,

#define MAX 10
#define CH ‘b’
#define HELLO “Hello World \n”
Wherever a symbolic constant appears in the code, it is equivalent to direct text-replacement with the
constant it defines. For example,
printf(HELLO);
prints the string Hello World. The reason for using symbolic constants rather than constant values directly,
is that it prevents the proliferation of “magic numbers”—numerical constants scattered throughout the code.
This is very important as magic numbers are error-prone and are the source of major difficulty when
attempting to make code-changes. Symbolic constants keep constants together in one place so that making
changes is easy and safe.
Example 5: Use of Symbolic Constant
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE ‘\n’
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
value of area : 50

22
Two ways to define constant in C
There are two methods for defining constants in C programming:
1. Using the C #define preprocessor, as illustrated above.
2. Utilizing the C const keyword.
When employing the C const keyword, constants in C programming can be defined by using the
const prefix along with a specific type in the following manner:
const type identifier = value;
For instance:
const float PI = 3.14;
the value of PI variable will remain the same throughout the program.
Example 6: demonstrates constant definition using the const keyword
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}

23
Lecture 2: Review Exercise
1. Define a variable in C programming and explain the rules for naming variables.

2. Provide examples of valid and invalid variable names and explain why some names are
not allowed

3. Describe the syntax for declaring a variable in C and explain the difference between
declaration and initialization.

4. Write a code snippet to declare and initialize three different types of variables.

5. List and describe the four main categories of data types in C.

6. Explain the significance of data type size and range and how they vary across different
systems.

7. Review the provided examples of data types (integer, float, double, char).

8. Write a short program using each basic data type to print values to the console.

9. Explain the purpose of constants in C and the two ways to define them.

10. Provide examples of defining constants using both #define and const.

11. Describe symbolic constants and discuss why they are preferable to using "magic
numbers" in code.

12. Write a program that uses symbolic constants for calculating and printing the area of a
rectangle.

13. Write a program that declares and initializes variables for a user's name, age, and height,
then prints these details in a formatted message.

24

You might also like