Unit-2 Com

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Unit II Notes

Computer System and Programming in c (CS-101)

Basic Input and Output in C

C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input and output.

scanf()

The scanf() method, in C, reads the value from the console as per the type specified.
Syntax:
scanf(“%X”, &variableOfXType); where %X is the format specifier in C. It is a way to tell
the compiler what type of data is in a variable and & is the address operator in C, which
tells the compiler to change the real value of this variable, stored at this address in the
memory.

printf()

The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf(“%X”, variableOfXType); where %X is the format specifier in C. It is a way to tell
the compiler what type of data is in a variable and & is the address operator in C, which
tells the compiler to change the real value of this variable, stored at this address in the
memory.

How to take input and output of basic types in C?

The basic type in C includes types like int, float, char, etc. Inorder to input or output the
specific type, the X in the above syntax is changed with the specific format specifier of that
type. The Syntax for input and output for these are:
 Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);

 Float:
Input: scanf("%f", &floatVariable);
Output: printf("%f", floatVariable);

 Character:
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);
Data Types
Each variable in C has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. It specifies the
type of data that the variable can store like integer, character, floating, double, etc. The data
type is a collection of data with values having fixed values, meaning as well as its
characteristics.
The data types in C can be classified as follows:
Types Description

Primitive Data Arithmetic types can be further classified into integer and floating data
Types types.

The data type has no value or operator and it does not provide a result
Void Types to its caller. But void comes under Primitive data types.

User Defined It is mainly used to assign names to integral constants, which make a
DataTypes program easy to read and maintain

The data types that are derived from the primitive or built-in datatypes
Derived types are referred to as Derived Data Types.
Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the memory
requirement and format specifiers on the 32-bit GCC compiler.

Memory Format
Data Type Range
(bytes) Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

-2,147,483,648 to
int 4 %d
2,147,483,647

-2,147,483,648 to
long int 4 %ld
2,147,483,647

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long 0 to


8 %llu
int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f


Memory Format
Data Type Range
(bytes) Specifier

double 8 1.7E-308 to 1.7E+308 %lf

long double 16 3.4E-4932 to 1.1E+4932 %Lf

Integer Types

The integer data type in C is used to store the whole numbers without decimal values. Octal
values, hexadecimal values, and decimal values can be stored in int data type in C. We can
determine the size of the int data type by using the sizeof operator in C. Unsigned int data
type in C is used to store the data values from zero to positive numbers but it can’t store
negative values like signed int. Unsigned int is larger in size than signed int and it uses “%u”
as a format specifier in C programming language. Below is the programming implementation
of the int data type in C.
 Range: -2,147,483,648 to 2,147,483,647
 Size: 2 bytes or 4 bytes
 Format Specifier: %d
Note: The size of an integer data type is compiler-dependent, when processors are 16-bit
systems, then it shows the output of int as 2 bytes. And when processors are 32-bit then it
shows 2 bytes as well as 4 bytes.

Character Types

Character data type allows its variable to store only a single character. The storage si ze of
the character is 1. It is the most basic data type in C. It stores a single character and requires
a single byte of memory in almost all compilers.
 Range: (-128 to 127) or (0 to 255)
 Size: 1 byte
 Format Specifier: %c

Floating-Point Types

In C programming float data type is used to store floating-point values. Float in C is used to
store decimal and exponential values. It is used to store decimal numbers (numbers with
floating point values) with single precision.
 Range: 1.2E-38 to 3.4E+38
 Size: 4 bytes
 Format Specifier: %f

Double Types

A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers with
decimal values in C. Double data type is basically a precision sort of data type that is capable
of holding 64 bits of decimal numbers or floating points. Since double has more precision as
compared to that float then it is much more obvious that it occupies twice the memory as
occupied by the floating-point type. It can easily accommodate about 16 to 17 digits after or
before a decimal point.
 Range: 1.7E-308 to 1.7E+308
 Size: 8 bytes
 Format Specifier: %lf

Void Data types

The void data type in C is used to specify that no value is present. It does not provide a result
value to its caller. It has no values and no operations. It is used to represent nothing. Void is
used in multiple ways as function return type, function arguments as void, and pointers to
void.
Syntax:
// function return type void

void exit(int check);

// Function without any parameter can accept void.

int print(void);

// memory allocation function which


// returns a pointer to void.
void *malloc( size_t size);

Storage Classes in C
Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility and life-time which help us to trace the existence of a
particular variable during the runtime of a program.
C language uses 4 storage classes, namely:

1. auto: This is the default storage class for all the variables declared inside a function or a
block. Hence, the keyword auto is rarely used while writing programs in C language.
Auto variables can be only accessed within the block/function they have been declared
and not outside them (which defines their scope). Of course, these can be accessed within
nested blocks within the parent block/function in which the auto variable was declared.
However, they can be accessed outside their scope as well using the concept of pointers
given here by pointing to the very exact memory location where the variables reside. They
are assigned a garbage value by default whenever they are declared.

2. extern: Extern storage class simply tells us that the variable is defined elsewhere and not
within the same block where it is used. Basically, the value is assigned to it in a different
block and this can be overwritten/changed in a different block as well. So an extern
variable is nothing but a global variable initialized with a legal value where it is declared
in order to be used elsewhere. It can be accessed within any function/block. Also, a
normal global variable can be made extern as well by placing the ‘extern’ keyword before
its declaration/definition in any function/block. This basically signifies that we are not
initializing a new variable but instead we are using/accessing the global variable only.
The main purpose of using extern variables is that they can be accessed between two
different files which are part of a large program. For more information on how extern
variables work, have a look at this link.
3. static: This storage class is used to declare static variables which are popularly used while
writing programs in C language. Static variables have the property of preserving their
value even after they are out of their scope! Hence, static variables preserve the value of
their last use in their scope. So we can say that they are initialized only once and exist till
the termination of the program. Thus, no new memory is allocated because they are not
re-declared. Their scope is local to the function to which they were defined. Global static
variables can be accessed anywhere in the program. By default, they are assigned the
value 0 by the compiler.

4. register: This storage class declares register variables that have the same functionality as
that of the auto variables. The only difference is that the compiler tries to store these
variables in the register of the microprocessor if a free registration is available. This
makes the use of register variables to be much faster than that of the variables stored in
the memory during the runtime of the program. If a free registration is not available, these
are then stored in the memory only. Usually few variables which are to be accessed very
frequently in a program are declared with the register keyword which improves the
running time of the program. An important and interesting point to be noted here is that
we cannot obtain the address of a register variable using pointers.

To specify the storage class for a variable, the following syntax is to be followed:
Syntax:
storage_class var_data_type var_name;
Functions follow the same syntax as given above for variables. Have a look at the following
C example for further clarification:

Operators in C

Operators are the foundation of any programming language. We can define operators as
symbols that help us to perform specific mathematical and logical computations on operands.
In other words, we can say that an operator operates the operands. For example, ‘+’ is an
operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.
The functionality of the C programming language is incomplete without the use of operators.
C has many built-in operators and can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators

The above operators have been discussed in detail:


1. Arithmetic Operators:
These operators are used to perform arithmetic/mathematical operations on operands.
Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:
a) Unary Operators:
Operators that operate or work with a single operand are unary operators. For example:
Increment(++) and Decrement(–) Operators
int val = 5;
++val; // 6
b) Binary Operators:
Operators that operate or work with two operands are binary operators. For example:
Addition(+), Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators:
These are used for the comparison of the values of two operands. For example, checking if
one operand is equal to the other operand or not, whether an operand is greater than the other
operand or not, etc. Some of the relational operators are (==, >= , <= )(See this article for
more reference).
int a = 3;
int b = 5;
a < b;
// operator to check if a is smaller than b
3. Logical Operators:
Logical Operators are used to combine two or more conditions/constraints or to complement
the evaluation of the original condition in consideration. The result of the operation of a
logical operator is a Boolean value either true or false.
For example, the logical AND represented as the ‘&&’ operator in C returns true when both
the conditions under consideration are satisfied. Otherwise, it returns false. Therefore, a &&
b returns true when both a and b are true (i.e. non-zero)(See this article for more reference).
(4 != 5) && (4 < 5); // true
4. Bitwise Operators:
The Bitwise operators are used to perform bit-level operations on the operands. The operators
are first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed
at the bit level for faster processing. For example, the bitwise AND operator represented
as ‘&’ in C takes two numbers as operands and does AND on every bit of two numbers. The
result of AND is 1 only if both bits are 1(True).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators:
Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data type as the variable on the lef t
side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
a) “=”
This is the simplest assignment operator. This operator is used to assign the value on the right
to the variable on the left.

Example:
a = 10;
b = 20;
ch = 'y';
b) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first adds the
current value of the variable on left to the value on the right and then assigns the result to the
variable on the left.

Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value
on the right from the current value of the variable on left and then assigns the result to the
variable on the left.

Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on the right and then assigns the result to the
variable on the left.

Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first divides the
current value of the variable on left by the value on the right and then assigns the result to
the variable on the left.

Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators:
Apart from the above operators, there are some other operators available in C used to perform
some specific tasks. Some of them are discussed here:
a. sizeof operator
 sizeof is much used in the C programming language.
 It is a compile-time unary operator which can be used to compute the size of its operand.
 The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
 Basically, the sizeof the operator is used to compute the size of the variable.
(See this article for reference)
b. Comma Operator
 The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
 The comma operator has the lowest precedence of any C operator.
 Comma acts as both operator and separator. (See this article for reference)
c. Conditional Operator
 The conditional operator is of the form Expression1? Expression2: Expression3
 Here, Expression1 is the condition to be evaluated. If the condition (Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition (Expression1) is false then we will execute and return the result of Expression3.
 We may replace the use of if..else statements with conditional operators. (See this article
for reference)
d. dot (.) and arrow (->) Operators
 Member operators are used to reference individual members of classes, structures, and
unions.
 The dot operator is applied to the actual object. (See this article for reference)
 The arrow operator is used with a pointer to an object. (See this article for reference)
e. Cast Operator
 Casting operators convert one data type to another. For example, int(2.2000) would return
2.
 A cast is a special operator that forces one data type to be converted into another.
 The most general cast supported by most of the C compilers is as follows − [ (type)
expression ]. (See this article for reference)
f. &,* Operator
 Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
 Pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var. (See this article for reference
Below is the implementation of the above-mentioned operators:
Operator Precedence Chart
The below table describes the precedence order and associativity of operators in C. The
precedence of the operator decreases from top to bottom.

Precedence Operator Description Associativity

1 Parentheses (function call) left-to-right


()
Precedence Operator Description Associativity

Brackets (array subscript) left-to-right


[]

Member selection via object name left-to-right


.

Member selection via a pointer left-to-right


->

Postfix increment/decrement (a is a variable) left-to-right


a++/a–

Prefix increment/decrement (a is a variable) right-to-left


++a/–a

Unary plus/minus right-to-left


+/-

Logical negation/bitwise complement right-to-left


!~

Cast (convert value to temporary value of type) right-to-left


(type)

Dereference right-to-left
*

Address (of operand) right-to-left


&

2 Determine size in bytes on this implementation right-to-left


sizeof

3 Multiplication/division/modulus left-to-right
*,/,%

4 Addition/subtraction left-to-right
+/-

5 Bitwise shift left, Bitwise shift right left-to-right


<< , >>
Precedence Operator Description Associativity

Relational less than/less than or equal to left-to-right


< , <=

6 Relational greater than/greater than or equal to left-to-right


> , >=

7 Relational is equal to/is not equal to left-to-right


== , !=

8 Bitwise AND left-to-right


&

9 Bitwise exclusive OR left-to-right


^

10 Bitwise inclusive OR left-to-right


|

11 Logical AND left-to-right


&&

12 Logical OR left-to-right
||

13 Ternary conditional right-to-left


?:

Assignment right-to-left
=

Addition/subtraction assignment right-to-left


+= , -=

Multiplication/division assignment right-to-left


*= , /=

Modulus/bitwise AND assignment right-to-left


%= , &=

14 Bitwise exclusive/inclusive OR assignment right-to-left


^= , |=
Precedence Operator Description Associativity

Bitwise shift left/right assignment right-to-left


<>=

15 expression separator left-to-right


,

Strucutre of c Program

Most programming languages have a structure, including the C language. A C program is


divided into six sections: Documentation, Link, Definition, Global Declaration, Main()
Function, and Subprograms. While the main section is compulsory, the rest are optional in the
structure of the C program.

All human beings have a definite structure, i.e., head, neck, and four limbs connected to a torso.
Almost everything has a definite structure. Likewise, in the case of programming languages,
all of them have a definite structure. These structures have to be followed while writing the
code.

The structure of a C program can be mainly divided into six parts, each having its purpose. It
makes the program easy to read, easy to modify, easy to document, and makes it consistent in
format.

Basic Structure of the C Program

Section Description

Consists of the description of the program, programmer's name, and creation


Documentation
date. These are generally written in the form of comments.

All header files are included in this section which contains different functions
Link from the libraries. A copy of these header files is inserted into your code
before compilation.

Includes preprocessor directive, which contains symbolic constants.


Definition E.g.: #define allows us to use constants in our code. It replaces all the
constants with its value in the code.

Global Includes declaration of global variables, function declarations, static global


Declaration variables, and functions.
Section Description

For every C program, the execution starts from the main() function. It is
Main() Function
mandatory to include a main() function in every C program.

Includes all user-defined functions (functions the user provides). They can
Subprograms contain the inbuilt functions and the function definitions declared in the
Global Declaration section. These are called in the main() function.

Let's look at an example to understand the structure of a C program:

Example: Write a program to calculate our age.

In the following example, we'll calculate age concerning a year.

Algorithm

You've to subtract the current year from your birth year and get your age.

Let's implement this and check:

Code:

/** //Documentation
* file: age.c
* author: you
* description: program to find our age.
*/

#include <stdio.h> //Link

#define BORN 2000 //Definition

int age(int current); //Global Declaration

int main(void) //Main() Function


{
int current = 2021;
printf("Age: %d", age(current));
return 0;
}

int age(int current) { //Subprograms


return current - BORN;
}
Output
Age: 21

Different sections of the above code


(a)Documentation

In a C program, single-line comments can be written using two forward slashes i.e., //, and we
can create multi-line comments using /* */. Here, we've used multi-line comments.

/**
* file: age.c
* author: you
* description: program to find our age.
*/
(b) Link

All header files are included in this section.

A header file is a file that consists of C declarations that can be used between different files. It
helps us in using others' code in our files. A copy of these header files is inserted into your code
before compilation.

#include <stdio.h>
(c) Definition

A preprocessor directive in C is any statement that begins with the "#" symbol. The #define is
a preprocessor compiler directive used to create constants. In simple terms, #define basically
allows the macro definition, which allows the use of constants in our code.

#define BORN 2000

We've created a constant BORN which is assigned a value of 2000. Generally, uppercase letters
are preferred for defining the constants. The above constant BORN will be replaced by 2000
throughout our code wherever used.

#define is typically used to make a source program easy to modify and compile in different
execution environments.

The define statement does not ends with a semicolon.


(d) Global Declaration

This section includes all global variables, function declarations, and static variables. The
variables declared in this section can be used anywhere in the program. They're accessible to
all the functions of the program. Hence, they are called global variables.

int age(int current);

We've declared our age function, which takes one integer argument and returns an integer.

(e) Main() Function

In the structure of a C program, this section contains the main function of the code. The
compiler starts execution from the main() function. It can use global variables, static variables,
inbuilt functions, and user-defined functions. The return type of the main() function can be
void and also not necessarily int.

int main(void)
{
int current = 2021;
printf("Age: %d", age(current));
return 0;
}

Here, we've declared a variable named current and assigned the value as 2021. Then we've
called the printf() function, with calls the age() function, which takes only one parameter.

(f) Subprograms

This includes the user-defined functions called in the main() function. User-defined functions
are generally written after the main() function irrespective of their order.

When the user-defined function is called from the main() function, the control of the program
shifts to the called function, and when it encounters a return statement, it returns to the main()
function. In this case, we've defined the age() function, which takes one parameter, i.e., the
current year.

int age(int current) {


return current - BORN;
}

This function is called in the main function. It returns an integer to the main function.

Writing and Executing the First C Program


In this tutorial, we will learn to create the first C program and then will understand its structure.
First of all, let's have a look at how to write a simple and most basic Hello World program in
C language. Let's get started.

Here is the program for printing "Hello World" in C language.

#include <stdio.h>

int main()

printf("Hello World");

return 0;

Hello, World

Run Code →

To run the above code on your local machine, you will have to install a C language compiler
on your Computer/Laptop. We will learn how to do that in the next tutorial - Compile and Run
C Code.

If you do not want to install the C compiler on your computer, don't worry. You can use
our Online Compiler to run C programs and Practice. Click on the Run Program
button above to open the compiler.

Understanding Structure of the C Program

Given below are some of the different parts of a C Program:

 Pre-processor
 Header file
 main() function
 Variables in C
 Statements & expressions in C
All these are essential parts of a C language program. Don't worry about all this, we will learn
about everything one by one and will clear all your confusion.

Let's start with a basic introduction of various code statements that we used in the above Hello
World program.

1. Pre-processor

The #include is the first statement of any C program. It is known as a pre-processor. The task
of a pre-processor is to initialize the environment of the program, i.e. to link the program with
the header files required.

As its name suggests, this line of code is responsible for doing pre-processing, before the
actual code (logic) is executed.

So, when we say #include<stdio.h>, it is to inform the compiler to include the stdio.h header
file which is the standard I/O library into the program before executing the program.

The standard I/O library lets you read input from the keyboard(i.e standard in) and then write
the output to the console screen (i.e. standard out) and it is an extremely useful library.

By Console screen, we mean CMD or command prompt in case of Windows OS


and Terminal in case you use Linux/Ubuntu/macOS.

Similarly, we can include any number of header files.

The #include is not the only pre-processor. Whenever you see any piece of code starting with
a # symbol, that means it's a pre-processor in the C language. We will learn about pre-
processors in detail later.

2. Header file

A Header file is a set or collection of built-in(readymade) functions, which we can directly


use in our program.

Header files contain definitions of the functions which can be used in any C program by using
pre-processor #include statement along with the name of the header file.

There are some standard header files that come along with default C installation,
like stdio.h header file. There are many other such files, we will learn about them later.
With time, you will have a clear picture of what header files are, as of now consider them as a
readymade collection of functions that comes packaged with the C language and you can use
them without worrying about how they work, all you have to do is include the header file in
your program.

To use any of the standard library functions, the appropriate header file must be included. This
is done at the beginning of the C source code.

For example, to use the printf() function in a C program, which is used to display anything on
the console screen, the line #include <stdio.h> is required, because the header
file stdio.h contains the printf() function definition.

All header files will have .h extension.

3. The main() Function

The main() function is a function that must be there in every C program.

Everything inside this function in a C program will be executed, hence the actual logic or the
code is always written inside the main() function.

As the name suggests, this is the main(of prime importance or center of attraction) function.

#include <stdio.h>

int main()

printf("Hello World");

return 0;

In the Hello World code example above, there was int written before the main() function,
remember? Well, that is the return type of the main() function. we will discuss it in detail
later.
The curly braces { } just after the main() function enclose the body of the main() function.

We will learn what functions in C language are in upcoming tutorials.

4. The printf() Function

The printf() is a function that is used to print(show) anything on the console as output. This
function is defined in the stdio.h header file, which we have included in our C program.

We will cover how to take input and show output in one of the next tutorials.

5. Return Statement

A return statement is used to return a response to the caller function. It is generally the last
statement of any C language function. Do not worry about this too, we will cover this statement
when we learn about functions in the C language.

6. Semicolon

It is important to note that every statement in C should end with a semicolon(;). If you miss
adding any semicolon, the compiler will give an error.

Components of C Program
The following sections describe the various components of the preceding sample program. Line
numbers are included so that you can easily identify the program parts discussed.

(a) The main() Function (Lines 9 Through 23)


The only component required in every executable C program is the main() function. In its
simplest form, the main() function consists of the name main followed by a pair of parentheses
containing the word void ((void)) and a pair of braces ({}). You can leave the word void out
and the program still works with most compilers. The ANSI Standard states that you should
include the word void so that you know there is nothing sent to the main function.
Within the braces are statements that make up the main body of the program. Under normal
circumstances, program execution starts at the first statement in main() and terminates at the
last statement in main(). Per the ANSI Standard, the only statement that you need to include in
this example is the return statement on line 22.
(b) The #include and #define Directives (Lines 2 and 3)
The #include directive instructs the C compiler to add the contents of an include file into your
program during compilation. An include file is a separate disk file that contains information
that can be used by your program or the compiler. Several of these files (sometimes
called header files) are supplied with your compiler. You rarely need to modify the information
in these files; that’s why they’re kept separate from your source code. Include files should all
have an .h extension (for example, stdio.h).
You use the #include directive to instruct the compiler to add a specific include file to your
program during compilation. In Listing 2.1, the #include directive is interpreted to mean “Add
the contents of the file stdio.h.” You will almost always include one or more include files in
your C programs. Lesson 22, “Advanced Compiler Use” presents more information about
include files.
The #define directive instructs the C compiler to replace a specific term with its assigned value
throughout your program. By setting a variable at the top of your program and then using the
term throughout the code, you can more easily change a term if needed by changing the
single #define line as opposed to every place throughout the code. For example, if you wrote a
payroll program that used a specific deduction for health insurance and the insurance rate
changed, tweaking a variable created with #define named HEALTH_INSURANCE at the top
of your program (or in a header file) would be so much easier than searching through lines and
lines of code looking for every instance that had the information. Lesson 3, “Storing
Information: Variables and Constants” covers the #define directive.
(c) The Variable Definition (Line 5)
A variable is a name assigned to a location in memory used to store information. Your program
uses variables to store various kinds of information during program execution. In C, a variable
must be defined before it can be used. A variable definition informs the compiler of the
variable’s name and the type of information the variable is to hold. In the sample program, the
definition on line 4, int year1, year2;, defines two variables—named year1 and year2—that
each hold an integer value. Lesson 3 presents more information about variables and variable
definitions.
(d) The Function Prototype (Line 7)
A function prototype provides the C compiler with the name and arguments of the functions
contained in the program. It appears before the function is used. A function prototype is distinct
from a function definition, which contains the actual statements that make up the function.
(Function definitions are discussed in more detail in “The Function Definition” section.)

(e) Program Statements (Lines 12, 13, 14, 17, 19, 20, 22, and 28)
The real work of a C program is done by its statements. C statements display information
onscreen, read keyboard input, perform mathematical operations, call functions, read disk files,
and all the other operations that a program needs to perform. Most of this book is devoted to
teaching you the various C statements. For now, remember that in your source code, C
statements are generally written one per line and always end with a semicolon. The statements
in bigyear.c are explained briefly in the following sections.

 The printf() Statement


The printf() statement (lines 12, 13, 19, and 20) is a library function that displays information
onscreen. The printf() statement can display a simple text message (as in lines 12 and 13) or a
message mixed with the value of one or more program variables (as in lines 19-20).
 The scanf() Statement
The scanf() statement (line 14) is another library function. It reads data from the keyboard and
assigns that data to one or more program variables.
The program statement on line 17 calls the function named calcYear(). In other words, it
executes the program statements contained in the function calcYear(). It also sends the
argument year1 to the function. After the statements in calcYear() are
completed, calcYear() returns a value to the program. This value is stored in the variable
named year2.
 The return Statement
Lines 22 and 28 contain return statements. The return statement on line 28 is part of the
function calcYear(). It calculates the year a person would be a specific age by adding
the #define constant TARGET_AGE to the variable year1 and returns the result to the program
that called calcYear(). The return statement on line 22 returns a value of 0 to the operating
system just before the program ends.
(f) The Function Definition (Lines 26 Through 29)
When defining functions before presenting the program bigyear.c, two types of functions—
library functions and user-defined functions—were mentioned.
The printf() and scanf() statements are examples of the first category, and the function
named calcYear(), on lines 26 through 29, is a user-defined function. As the name implies,
user-defined functions are written by the programmer during program development. This
function adds the value of a created constant to a year and returns the answer (a different year)
to the program that called it. In Lesson 5, “Packaging Code in Functions,” you learn that the
proper use of functions is an important part of good C programming practice.
Note that in a real C program, you probably wouldn’t use a function for a task as simple as
adding two numbers. It has been done here for demonstration purposes only.

(g) Program Comments (Lines 1, 11, 16, and 25)


Any part of your program that starts with /* and ends with */ or any single line that begins with
// is called a comment. The compiler ignores all comments, so they have absolutely no effect
on how a program works. You can put anything you want into a comment, and it won’t modify
the way your program operates. The first type of comment can span part of a line, an entire
line, or multiple lines. Here are three examples:

/* A single-line comment */

int a,b,c; /* A partial-line comment */

/* a comment
spanning

multiple lines */

You should not use nested comments. A nested comment is a comment that has been put into
another comment. Most compilers will not accept the following:

/*

/* Nested comment */

*/

Some compilers do allow nested comments. Although this feature might be tempting to use,
you should avoid doing so. Because one of the benefits of C is portability, using a feature such
as nested comments might limit the portability of your code. Nested comments also might lead
to hard-to-find problems.

The second style of comment, the ones beginning with two consecutive forward slashes (//),
are only for single-line comments. The two forward slashes tell the compiler to ignore
everything that follows to the end of the line.

// This entire line is a comment

int x; // Comment starts with slashes

Many beginning programmers view program comments as unnecessary and a waste of time.
This is a mistake! The operation of your program might be quite clear when you write the code;
however, as your programs become larger and more complex, or when you need to modify a
program you wrote 6 months ago, comments are invaluable. Now is the time to develop the
habit of using comments liberally to document all your programming structures and operations.
You can use either style of comments you prefer. Both are used throughout the programs in the
book.
/* The following prints Hello

World! on the screen */

printf("Hello World!);

might be going a little too far, at least when you’re completely comfortable with
the printf() function and how it works.
Using Braces (Lines 10, 23, 27, and 29)
You use braces {} to enclose the program lines that make up every C function—including
the main() function. A group of one or more statements enclosed within braces is called a block.
As you see in later lessons, C has many uses for blocks.
Running the Program
Take the time to enter, compile, and run Helloworld.c. It provides additional practice in using
your editor and compiler. Recall these steps from Lesson 1, “Getting Started with C”:

1. Make your programming directory current.


2. Start your editor.
3. Enter the source code for Helloworld.c exactly, but be sure to omit the line numbers and
colons.
4. Save the program file.
5. Compile and link the program by entering the appropriate command(s) for your compiler.
If no error messages display, you can run the program by clicking the appropriate button
in your C environment.
6. If any error messages display, return to step 2 and correct the errors.

You might also like