Programming Concepts & Logics - Part II

Programming Concepts & Logics - Part II

Nepal, HSEB, Class - XI, Chapter 5

This blog is for Class XI, Computer Science Students, in Nepal. The blog is the second part of Chapter 5, of the computer science book by Kriti's Publication. Please read the book for details.

This is the second part of this blog where we'll dive into more detail about C programming. Find the first part here.

Introduction

C programming is a procedural programming language. There are three building blocks in any programming language. They are: The way data is stored, How it is processed with I/O, and The operator programming language.

Features

Some of the features of C programming languages are:

  1. It is small, faster, and more efficient than other programming languages.

  2. It is a strong structural language with powerful data definition methods.

  3. It has a low-level programming language available.

find more on the book

Pros and Cons of Using C

Like any other programming language, C is not perfect and has its benefits and flaws.

Advantages:

  • Fast and Efficient

  • Only has 32 keywords to remember.

  • Easy for debugging, testing, and maintaining

  • User friendly

Some disadvantages are:

  • No running time checking

  • Case sensitive

  • No concept of constructor and deconstructor.

  • No concept of polymorphism, inheritance, etc.

Structure of C Program

Structured Programming Language is a type of programming that generally converts large or complex programs into more manageable and small pieces of code**.** Like any other programming language, the C program has predefined rules called syntax. All programs must contain the main() function.

Typical C Program has:

  1. Header, a section that starts #include. It is how you import files and modules.

  2. The main function is the first function called when the program is run. It is a reserved keyword so it cannot be used to name a variable.

  3. Starting and Ending of the main function, a curly brackets "{}".

  4. Functions body inside the curly bracket.

  5. Every expression must end with a semicolon(;)

  6. C program files have an extension of ".c". For instance, test.c, prime_numbers.c, etc.

// Header
#include <stdio.h>

// The must have main function
int main(){ // func starting curly bracket
// this is function body
int primeNumber = 7; // THis is an expression that must end with semicolon
}// func ending curly bracket

In the above sample code, int & main are reserved keywords.

Compiling

C Compilation Process Breakdown

Image Source

C progam is a source code. It must be compiled into an object program before execution. The compiler won't translate unless the program is error-free. The compilation process can be divided into four steps:

  1. Preprocessing

  2. Compilation

  3. Assembly

  4. Linking

C-processors and Header Files

C preprocessors

C Preprocessor is just a text substitution tool. It is a step before compilation. It preps the compiler for compilation. All preprocessor commands begin with directives ( symbol starting with hash,#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column.

A directive is a language construct that specifies how a compiler should process its input. They are not part of the grammar of a programming language and may vary from compiler to compiler.

  • File Inclusion directive is the main preprocessor. It starts as #include. It is used to import files into the current program. For instance, #include <stdio.h>.

  • Macro Define directive, starts as #define. It is used to define variables within the program. For instance, we can define the mathematical symbol Pi as #define Pi 3.14.

  • A conditional Inclusion directive is the same as a conditional if/else statement in a program. It's rarely used in a program, and used often to implement programs by computer types.

Header Files

The header files are files to be included in the program. They are defined at the beginning of a program using the #include directive. They have an extension of ".h". For instance, #include <stdio.h> . If the program gets long and difficult to browse you can separate a program into multiple files and use include to merge them by necessity.

Check out the book for a list of prebuilt files and their usage in C.

Character Set Used in C

The alphabet, digits, and special symbols used to write the C program are called character sets. The keywords, identifiers, and variable names are constructed with a combination of characters.

Comments

Comments are plain English sentences used in a program. They are used to write pseudocode, the purpose of the program and functions, etc. In C you can write both single and multiple lines comments as follows.

// I am single line comment. I can only be writter in single line.

/*
I am multiple line comment. 
I can be written in multiple lines.
*/

Identifiers, Keywords, and Tokens

Identifier

An identifier is a name given to variables, constants, functions, etc. They should always be unique within that program. The identifiers also have other rules:

  • Should consist of digits, letters, and underscores(_) only.

  • The first character must always be an alphabet or an underscore(_).

  • Reserved keywords can't be used as identifiers.

  • Due to case sensitivity, the same identifier but with upper and lower cases are both allowed.

  • Only one special identifier can be used. For instance int c; int _prime;

Keywords

In a programming language, a reserved word (also known as a reserved identifier) is a word that cannot be used as an identifier, such as the name of a variable, function, or label – it is "reserved from use". This is a syntax-related thing, so, the reserved word may have no user-defined meaning. For instance, int, char, float, for, while, do etc, are all reserved keywords.

Tokens

Tokens are the smallest elements of a program, which are meaningful to the compiler. The following are the types of tokens: Keywords, Identifiers, Constant(const/#define), Strings("string"), Operators(=, / ), etc.

Basic Data Types in C

Data is stored in a computer concerning their data types. Some data can be numbers while others can be strings. Defining data by their types can help in their manipulation quickly. In C, there are two types of data types. They are Primary Data Types and Secondary Data Types.

Primary Data Types

The basic fundamental unit of C is primary data. For instance, int, short int, long int, char, float, double, etc. Data types vary with compilers. In the Dev-cc compiler, the data types are void, char, int, and float.

  • Char: It is a string or character.

  • Void: It represents nothing and has 0-byte storage.

  • int: They are natural numbers like 0,1 2, etc.

  • float: Decimal/Fractional values are represented using floats/doubles.

Find the difference between float and double.

Secondary Data Types

They are formed with a collection of primary data types. They can hold different types of data combinations. Examples of secondary data types are pointer, array, structure, union, etc.

Constants and Variables

Constant

A constant is a variable in c with a fixed value. i.e it cannot be changed once assigned and should always be initialized when declared.

The syntax to declare constant is const data-type variable-name = value; for instance, const int rollNumber = 23;

Variables

A Variable is a named location in the memory of a computer. It's called a variable because its value can be changed during execution. Variable is an identifier as well. So, the rules for naming variables are the same as identifiers.

The variables can be declared with or without initialization, unlike constants. The syntax for declaring variables are:

data-type variable-name;

Or,

data-type variable-name = value;

For instance:

int rollNumber;

int rollNumber = 12;

There are three different types of variables:

  • Local Variables

  • Global Variables

  • Static Variables

Local Variable

A local variable is declared inside a code block like a function. It is not accessible from outside the block, hence, the name local.

Global Variable

These are variables declared outside of the scope(range) of any function and are accessible from everywhere within that program.

Static Variable

Static variables are the variables that once declared, get destroyed only after the program execution. They have the property of retaining their previous scope value if they are already declared once in the program.

They are different from normal variables because they do not retain their previous value. Normal variables get destroyed once they go out of scope. But when static variables are initialized, they get destroyed only after the whole program gets executed.

Const Vs Static

const is equivalent to #define but only for value statements(e.g. #define myvalue = 2). The value declared replaces the name of the variable before compilation.

static is a variable. The value can change, but the variable will persist throughout the execution of the program even if the variable is declared in a function. It is equivalent to a global variable whose usage scope is the scope of the block they have been declared in, but its value's scope is global.

Source

Specifiers

In C specifiers are used for generating and formatting the input and output data in specific patterns. Mostly used specifiers are escape sequence(/) and format specifiers like %d,%f, etc.

The Escape sequence uses a backslash (\) to escape non-printable characters in the output. For instance, printf("\"Hello World!\"") prints "Hello World" with double quotes.

Format specifiers use the "%" token to input or output variables in C. For instance, printf("%d", variable_name) , prints the value of the given integer variable.

Check out the details in the book.

Simple and Compound Statements

The smallest executable entity in a program code is called a statement. It is a building block of a code. They consist of keywords, constants, variables, operators, data types, etc.

Simple Statement

It is the simplest part of the program and a single-line expression to carry out, for instance, an assignment.

// these all are simple statement
float pi, a; 
pi =3.14;
a= 4.5;

Compound Statement

If a single instruction or assignment is consist of two or more lines then it's a compound statement. Compound statements are enclosed in curly braces "{}" such as the if/else statements.

float pi, a; 
pi =3.14;
a= 4.5;
// if satement which is compund statement
if(a> pi){
printf("Area is greater than pi");
}

Operators and Expressions

Operators

An operator is a sign or symbol that performs an operation or evaluation. An operand is a value or variable declared within a program. For instance, in the expression 4+5 4 and 5 are operands while + is a operator.

1. Arithmetic Operator

The operators that are used to perform mathematical calculations. For instance, +, -, /, *, and %.

2. Relational Operator

They are operators used to compare two values and/or variables. Such as ==, <=,>=, !=, etc

3. Logical Operator

These are operators used to evaluate two or more expressions whether they are true or false. Such as &&, || and ! etc. The ! returns true if expressions are not equal, else 0.

4. Bitwise Operator

Bitwise operators are characters that represent actions (bitwise operations) to be performed on single bits. They operate at the binary level and perform operations on bit patterns that involve the manipulation of individual bits

Check out other operators like assignment, and shorthand operators in your book. Also, check the precedence of operators.

Expressions

An expression is a logical combination of operators and operands that evaluate a value. An expression is a combination of constants, variables, and operators written in C language syntax.

Input/Output (I/O) Functions

Any data given to a program is the input and the result produced by the program is the output. The I/O functions are categorized into Formatted and Unformatted I/O functions.

The print() and scanf() are formatted I/O functions.

The getch(), putch() are some examples of unformatted I/O functions.

Note from Author

The blog is alive and will have more sections added in the future. Since the second terminal examination is close, I'm sharing this blog for students to access.

KCL

Thanks for reading. It is Nibesh Khadka from Khadka's Coding Lounge. Find more of my blogs @ kcl.hashnode.dev.

Find out more blogs in this series here.