0% found this document useful (0 votes)
29 views13 pages

C Programming

SUmmarised notes on clanguage

Uploaded by

my.portifolio1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
29 views13 pages

C Programming

SUmmarised notes on clanguage

Uploaded by

my.portifolio1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

Lecture Notes: STRUCTURED PROGRAMMING LANGUAGE:

Module contents:
1. Objectives
2. Structured programming language
3. C-syntax
4. Data types
5. Constants
6. Variables
7. Input and output statements
1.0 Objectives:
i) The objective of this module is to ensure that at the end of this each student should be able to: -
ii) Write the syntax of c program

iii) Explain the different kinds of data types

2.0: What is Structured Programming Language


Structured programming is a subset or sub discipline of procedural programming, one of the
major programming paradigms. It demonstrates that any computer program can be written
with just three structures, that is, decisions, sequences and loops. It is most famous for
removing or reducing reliance on the GOTO statement.
In programing languages that use the Structured programming paradigm, writes functions
(sometimes called: procedures, sub routines, methods) to perform certain tasks within the
program.

OR we can also define structured programming as;

Structured programming can also be defined as a programming paradigm or procedure aimed


at improving the clarity, quality, and development time of a computer program by making use
of the structured control flow constructs of selection (if/then/else) and block structures (while
and for). This contains a series of procedures to be taken any time during program execution

2.1: Why C Is Called Structured Programming Language


In C Programming when writing a program, we add preprocessor directive #include
<filename>, then functions like main (), then opening of braces { }, inside the braces there
are two parts declaration of variables and execution of statements which is a step by step
process and well-structured so anyone can understand what codes are doing and in which
section.
It also allows the program to be split into multiple blocks of execution. That is, you can split
the program into such named blocks called functions. That is why it is called a structured
programming language.
2.2: Features of C Programming Language
1. Low Level Language Support
2. Program Portability
3. Powerful
4. Manipulation
5. High Level Features
6. Modular Language
7. Efficient Use of Pointers
8. It is case sensitive, meaning it cannot differentiate between Printf and PRINTF which are
two different identifiers.
2.3: Advantages of C Programming
i) C Programs are efficient, fast and Highly Portable.
It can be written in one computer and can be runned in another one without any modification.
Ii) It’s easy for debugging, error finding, testing and maintenance because of the structured
programming.
3.0. Syntax:
A Syntax of a computer language is the set of rules that defines the combinations of symbols
that are considered to be correctly structured statements or expressions in that language.
Which implies both to programming languages, where the document represents source code,
and to markup languages, where the document represents data.
3.1: C Syntax;
The syntax of the C programming language is the set of rules governing the writing of
program in the C language.

3.2: Tokens;
Token is a smallest individual unit in c program.
C tokens-
C program consists of various tokens which are either a keyword(while), an identifier(main),
a constant (100, -15), a strings (“ABC”, Year”), operators (*, +-), or a symbol ([],{}).
For example;
Printf (“Hello, World! \n”); Hence this statement has five tokens which are;
Printf
(
“Hello, World! \n”
)
;
Semicolons:
In a C program, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.
Printf (“Hello, World! \n”);
return 0 ();

Comments:
Comments are like helping text in a C program and they are ignored by the compiler. They
start with /* and terminate with the characters */ .
Example;
/* my first program in c * /

3.3: Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item.
An identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more
letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers.It is case
sensitive programming language.Example; Manpower and manpower are two different
identifiers in C.
3.4: Keywords
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names.
All keywords have fixed meanings and cannot be changed.
All keywords must be written in lowercase

Auto else long switch

Break enum register typedef

Case extern return union

Char float short unsigned

Const for signed void

Continue goto sizeof volatile

Default if static while

Do int struct _Packed

Double
Whitespace in C

A line containing only whitespace, possibly with a comment, is known as a blank line, and a
C compiler totally ignores it.
Example;
Int age; in this statement there must be at least one whitespace character (usually a space)
between int and age for the compiler to be able to distinguish them.
4.0: Data types;
Data types in c refer to a 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.
These include;
1. Primary data types
2. Derived data types
3. User-defined data types
NOTE: The compiler supports five primary data types which are;
I) Integer (int)
II) Character (char)
III) Floating point (float)
IV) Double precision floating point (double)
V) Void

Sr.No. Types & Description

1
Primary data types
They are arithmetic types and are further classified into: (a) integer types and (b) floating-
point types.

2
User-defined data types
They are again arithmetic types and they are used to define variables that can only assign
certain discrete integer values throughout the program.

3
The type void
The type specifier void indicates that no value is available.
4
Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e)
Function types.

Integer Types:
Integer numbers are whole numbers (16-32 bits), the size of integer can be stored depending
on the computer that will be -32768 to +32767.

Type Storage size Value range

Char 1 byte -128 to 127 or 0 to 255

signed char 1 byte -128 to 127

-32,768 to 32,767 or -
Int 2 or 4 bytes 2,147,483,648 to
2,147,483,647

Short 2 bytes(16 bits) -32,768 to 32,767

unsigned int 2 bytes(16 bits) 0 to 65,535

Signed long int 8 bytes or (4bytes for 32 bit OS) -9223372036854775808 to


9223372036854775807

unsigned long int 8 bytes 0 to


18446744073709551615

 C has a three types of integer classes namely, short int, int, and long int in both signed
and unsigned forms.
 That means short int represents fairly small integer values and require small storage.
 long and unsigned integers are used to increase range of values.
 Unsigned integers are always positive.
Floating point data types:
Floating point or real numbers are stored in 32 bits, and defined by the keyword float. When
the amount provided by float is not sufficient then type double can be used to define the
number. A double datatype uses 64 bits, which is the double amount of float but with greater
precision
To extend precision we use long double which uses 80 bits.
Below is illustration of the floating types relationship;

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Example: #include <stdio.h>


#include <float.h> the header file float allows to use binary representation of real
numbers in the program.
Void Types:
The Void type has no values, used to specify of function. A type of function is said to be void
if it does not return any value to the calling function. Example; void exit (int status) this a
function with no return value has the return type void.
Character Types:
A single character can be defined as character(char) type data and are usually stored in 8
bits
5.0: Variables:
 A variable is a data name that maybe used to store data value.
 A variable may take different values at different times during execution and also a
variable name can be chosen by the programmer in a meaningful way to reflect its
function
 It composes of letters, digits, and the underscore character and must begin with either
a letter or an underscore. Upper and lowercase letters are distinct because C is case-
sensitive.
 It should be a keyword.
 White space is not allowed
Examples of valid variables; John, mark, value, sum1, xl and invalid variables such as
%,25th.
Variable Declaration in C:
Example we want to initialize a value in their declaration this will involve an equal sign
followed by constant expression, that is type variable_name = value;
 Declaration tells the compiler what the variable name is.
 It specifies what type of data the variable will hold.
 Thus the declaration must be done before the variables are used in the program.
 Declaration statement must end with a semicolon
 Variables are separated by commas.
Example declaration of variables storing data types value;
data-type v1, v2,……vn; v1,v2…..vn are the variables names.
Example2: variable declaration
#include <stdio.h>

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {

/* variable definition: */
int a, b;
int c;
float f;

/* actual initialization */
a = 10;
b = 20;

c = a + b;
printf("value of c : %d \n", c);

f = 70.0/3.0;
printf("value of f : %f \n", f);

return 0;
}
When the above code is compiled and executed, it produces the following output: -
value of c : 30
value of f : 23.333334
6.0: Constants
Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
Constants can be of any basic data types like
1. Integer constant,
2. Floating constant or real constraints.
3. Character constant,
4. String literal.
Constants are treated just like regular variables except that their values cannot be modified
after their definition.
Integer constant;
An integer constant can be a decimal, octal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
Floating constants:
A floating-point constant has an integer part, a decimal point, a fractional part, and an exponent
part. You can represent floating point literals either in decimal form or exponential form.
While representing decimal form, you must include the decimal point, the exponent, or both;
and while representing exponential form, you must include the integer part, the fractional part,
or both. The signed exponent is introduced by e or E.
Character constant:
 Character constant are enclosed in single quotes, e.g., 'x' can be stored in a simple
variable of char type.
 A character constant can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'),
or a universal character (e.g., '\u02C0').
 There are certain characters in C that represent special meaning when preceded by a
backslash for example, newline (\n) or tab (\t).
Example;
#include <stdio.h>

int main() {
printf("Hello\tWorld\n\n");

return 0;
}
When the above code is compiled and executed, it produces the following result: -
Hello World

String constants:
These are the same as character constants plain characters, escape sequences, and universal
characters.
You can break a long line into multiple lines using string literals and separating them using
white spaces.
Examples of string literals. All the three forms are identical strings.
"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"


8.0: STANDARD INPUT AND OUTPUT STATEMENTS:
Input means to feed some data into a program.
An input can be given in the form of a file or from the command line.
Output means to display some data on screen, printer, or in any file.
C programming provides a set of built-in functions to output the data on the computer screen
as well as to save it in text or binary files.

Standard File File Pointer Device

Standard input Stdin Keyboard

Standard output Stdout Screen

Standard error Stderr Your screen

This above explains how to read values from the screen and how to print the result on the
screen.

8.1: The getchar () and putchar () Functions

The int getchar(void) function reads the next available character from the screen and returns
it as an integer. This function reads only single character at a time. You can use this method
in the loop in case you want to read more than one character from the screen.
The int putchar (int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time. You can use this method in the
loop in case you want to display more than one character on the screen.
Check the following example: -
#include <stdio.h>
int main() {

int c;

printf( "Enter a value :");


c = getchar( );

printf( "\nYou entered: ");


putchar( c );

return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you
enter a text and press enter, then the program proceeds and reads only a single character and
displays it as follows;
Enter a value : this is test
You entered: t

The gets() and puts() Functions


The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until
either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout.
#include <stdio.h>
int main( ) {

char str[100];

printf( "Enter a value :");


gets( str );

printf( "\nYou entered: ");


puts( str );

return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you
enter a text and press enter, then the program proceeds and reads the complete line till end,
and displays it as follows −
Enter a value : this is test
You entered: this is test

8.2: The scanf () and printf () Functions

The int scanf(const char *format, ...) function reads the input from the standard input
stream stdin and scans that input according to the format provided.
The int printf(const char *format, ...) function writes the output to the standard output
stream stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print
or read strings, integer, character or float respectively.
Below is a simple example
#include <stdio.h>
int main( ) {

char str[100];
int i;

printf( "Enter a value :");


scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);

return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you
enter a text and press enter, then program proceeds and reads the input and displays it as
follows −
Enter a value : seven 7
You entered: seven 7
Note that scanf() expects input in the same format as you provided %s and %d, which means
you have to provide valid inputs like "string integer".
Secondly, while reading a string, scanf() stops reading as soon as it encounters a space, so "this
is test" are three strings for scanf().
FILE I/O(Input/Output);
A file represents a sequence of bytes, regardless of it being a text file or a binary file.
C provides levels of file management and these include;
i) Opening a file
ii) Closing a file
iii) Writing a file
iv) Reading a file

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file. This call
will initialize an object of the type FILE, which contains all the information necessary to
control the stream.

Sr.No. Mode & Description

1
R
Opens an existing text file for reading purpose.

2
W
Opens a text file for writing. If it does not exist, then a new file is created. Here your
program will start writing content from the beginning of the file.
3
A
Opens a text file for writing in appending mode. If it does not exist, then a new file
is created. Here your program will start appending content in the existing file
content.

4
r+
Opens a text file for both reading and writing.

5
w+
Opens a text file for both reading and writing. It first truncates the file to zero length
if it exists, otherwise creates a file if it does not exist.

6
a+
Opens a text file for both reading and writing. It creates the file if it does not exist.
The reading will start from the beginning but writing can only be appended.

Closing a File

To close a file, use the fclose() function.


The fclose(-) function returns zero on success, or EOF if there is an error in closing the file.
This function actually flushes any data still pending in the buffer to the file, closes the file,
and releases any memory used for the file. The EOF is a constant defined in the header
file stdio.h.

Writing a File

Following is the simplest function to write individual characters to a stream −


int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream
referenced by fp. It returns the written character written on success otherwise EOF if there is
an error. You can use the following functions to write a null-terminated string to a stream −

Reading a File

The fgetc() function reads a character from the input file referenced by fp. The return value is
the character read, or in case of any error, it returns EOF.
Example;
#include <stdio.h>

main() {
FILE *fp;
char buff[255];

fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("3: %s\n", buff );
fclose(fp);

}
When the above code is compiled and executed, it reads the file created in the previous section
and produces the following result: -
1: This is testing for fprintf...

3: This is testing for fputs...

You might also like