C Programming
C Programming
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
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
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
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.
-32,768 to 32,767 or -
Int 2 or 4 bytes 2,147,483,648 to
2,147,483,647
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;
// 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"
This above explains how to read values from the screen and how to print the result on the
screen.
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;
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
char str[100];
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
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;
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.
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
Writing a File
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 );
}
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...