1 - Introduction To C Programming

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 76

INTRODUCTION TO COMPUTER PROGRAMMING

Instructor:
NICHOLAS KATENDE
email: katsnic@live.com
Tel:+250-783-933978
Overview
 Introduction to C programming Language.
 Structure of a C program.
 Operators, Expressions, and Statements.
 Control Structures (Branching).
 Iterative Structures (Loops).
 Functions.
 Arrays.
 Structures and pointers
 Implementation Using Borland Compiler .

2
Programming Languages
A programming language is a language that a computer can
understand and provides a programmer an environment to
write and execute programs in it. A number of programming
languages exist but the choice mainly depends on the nature
of the problem at hand and the programmer’s ability to use
the language.
There has been a great revolution in programming languages
right from the time when programming started. The first
generation of programming languages involved the use of
machine language, the second involved the use of assembly
language, the third generation involved highlevel
programming languages like C, C++, Java e.t.c, the forth
generation involved languages mainly used for database
manipulation like Structured Query Language (SQL) and the
3
fifth generation involved languages mainly used for artificial
Introduction to C Programming
What are Programming Languages ?
Programming Languages are used to specify, design, and build
software systems.
Programming languages evolve with the systems they are used
to construct. C is a good example of how this system takes
place.
C as a programming language
C has been standardized (ANSI C) and spawned new languages
(C++,Stroustrup,1986) that improve C. The basic characteristics
of C are:

 Small in size
 Structured (Extensive use of functions)
 Less error prone

4
Cont’d …
 Designed for systems programming (low level
programming of the type that is used in the implementation
of an operating system).
 C is high level than assembler but still close to hardware
and allows direct manipulation of many systems accepts:
pointers, memory allocation and bitwise manipulation.

 C programming language provides high


level construct (functions and data structures) that
facilitate programming without loosing too much
performance. Being a low level language, C gives a lot of
freedom to the programmer:

5
Cont’d…
 It has the advantage that good programmers can
implement very efficient programs in a compact
manner and it has the disadvantage that most of us
are not good programmers and the freedom C
grants is usually translated in error prone, messy
code.

6
Why learn C ?
 Compact, Fast and Powerful.
 Standard for program development (widely accepted).
 Its everywhere (Portable).
 Supports modular programming.
 Useful for all applications
 C is a native language for UNIX.
 Easy to interface with system devices/assembler routines.

7
C Compilation Model

8
Syntax, Semantics and Program
Errors
Syntax
Syntax of a programming language means the rules that
dictate how exactly the vocabulary elements of the
language can be combined to form statements. Each
programming language has its own unique syntax. For
example, in English we know that a sentence must end with
a question mark, a full stop or an exclamation mark. That is
the rule that must be obeyed
During compilation, all syntax rules are checked. If a
program is not syntactically correct, the compiler will issue
error messages. Such errors could be like attempt to add
two integers but the addition operator in not put between
9 them or forgetting to close a procedure/function.
CONT’
Semantics
The semantics of a statement in a programming
language define what will happen when that statement
is executed. In other words, semantics refer to the
meaning of the statement.
Programming languages are generally unambiguous,
which means the semantics are well defined. This
means there’s only one and only one interpretation of
each statement. Natural languages e.g. French and
English are full of ambiguities.

10
CONT’
 Program Errors
 You will encounter three types of errors as you develop programs
 Compile time errors. These are errors identified by the compiler when it is
compiling your program. They may include syntax errors and wrong data
types. A program will not execute until when a compile time error is
corrected.
 Runtime errors. These occur during the execution of a program and cause a
program to abort abnormally e.g. division by zero, infinite looping.
 Logical errors. The program compiles and runs normally but it produces
wrong results. A logical error may occur when:
A value is calculated incorrectly e.g instead of addition you subtract.
When a graphical button does not appear in the correct place.
 Logical errors are the most difficult to debug because they manifest
themselves in many ways when their root cause is different.
 Debugging is the process of finding and correcting errors/bugs in a program.

11
The figure below shows the basic program development process.
Program Development and the Top-Down Design
Approach
During the program development process, the following steps must be
followed;
Step1. Understand the problem
Step2. Analyzing the problem we're given
Step3. Dissect the problem into manageable pieces
Step4. Developing a solution technique (algorithm)
Step5. Documenting the program/technique
Step6. Translating (implementing) the technique into code
Step7. Compiling and running the program
Step8. Testing the results with appropriate data

The above steps must be followed carefully. After step 8, if


there are logical errors (i.e. program running properly but
results are not correct), you must go back to step 6.
Top-Down Design Approach
Many problems are too large to immediately grasp
and solve all the details; top-down design approach
tries to address this issue.
Take a problem, divide it into smaller logical sub-
problems, and remember how they fit together
For each sub-problem, divide it into still smaller sub-
problems
Continue sub-dividing until each little problem is
small enough to be easily solved
Solving a collection of small problems thus allows

13
us to solve one much larger problem
Structure of a C Program
// my first program
#include <stdio.h>
main ()
{

printf (“Hello World\n”); // prints hello world

return 0;
}

C is case sensitive. All commands must be in lower


case.
14
Entering and Compiling welcome.c
1. Open Borland C++ compiler.
1. Then open a new blank page
2. Use the keyboard to type the welcome.c source code
exactly as shown above Press Enter at the end of
each line.
3. Save the source code. You should name the file
welcome.c

Muhirwe Jackson, Mak, FCIT


Entering and Compiling welcome.c
4. Verify that welcome.c is on disk by listing the files
in the directory or folder. You should see welcome.c
within this listing.
5. Compile and link welcome.c
6. Check the compiler messages. If you receive no
errors or warnings, everything should be okay.

Muhirwe Jackson, Mak, FCIT


Entering and Compiling welcome.c
7. If you made an error typing the program, the
compiler will catch it and display an error message.
For example, if you misspelled the word printf as
prntf, you would see a message similar to the
following:
1. Error: undefined symbols: _prntf in welcome.c
(welcome.obj)

Muhirwe Jackson, Mak, FCIT


Entering and Compiling welcome.c
8. Go back to step 2 if this or any other error
message is displayed. Open the welcome.c file in
your editor. Check your codes, make any
necessary corrections, and continue with step 3.
9. Your first C program should now be compiled
and ready to run. If you display a directory
listing of all files named welcome (with any
extension), you should see the following:
10. welcome.c, the source code file you created with
your editor welcmoe.obj or welcome.o, which
contains the object code for welcome.c

Muhirwe Jackson, Mak, FCIT


Entering and Compiling welcome.c
11. WELCOME.EXE, the executable program
created when you compiled and linked
WELCOME.C
12. 9. To execute, or run, WELCOME.EXE, simply
enter WELCOME. The message This is my first
C progam is displayed on-screen.

Muhirwe Jackson, Mak, FCIT


20
Cont’d…
The above program is the typical program that programmer
apprentices write for the first time, and its result is the printing on
screen of the "Hello World!" sentence. It is one of the simplest
programs that can be written in C, but it already contains the
fundamental components that every C program has. We are
going to look line by line at the code we have just written:

// my first program in C
This is a comment line. All lines beginning with two slash signs
(//) are considered comments and do not have any effect on the
behavior of the program. The programmer can use them to
include short explanations or observations within the source
code itself. In this case, the line is a brief description of what our
program is.

21
Cont’d…
#include <stdio.h>
Lines beginning with a hash sign (#) are directives for the
preprocessor. They are not regular code lines with expressions
but indications for the compiler's preprocessor. In this case the
directive #include<stdio.h> tells the preprocessor to include the
stdio.h standard file. This specific file (stdio.h) includes the
declarations of the basic standard input-output library in C, and it
is included because its functionality is going to be used later in
the program.
.h
The .h portion is a language extension which denotes and
includes header files and the < > characters around the name
stdio.h header file tells C to check in the system area for the file
called stdio.h

22
Cont’d…
{
This is a brace. As the name implies, braces come in packs of two,
i.e. for every open brace there must be a matching close. Braces
allow to lump pieces of a program together. Such a lump of program
is often called a block. A block can contain the declaration of
variables used within it, followed by a sequence of program
statements which are executed in order. In this case the braces
enclose the working parts of the function main (). When the
compiler sees the matching close brace at the end it knows that it
has reached the end of the function and can look for another (if
any). The effects of an un-paired brace are invariably fatal and can
lead to error in the program.
main()
The line corresponds to the beginning of definition of the main function.
The main function is the point by where all C programs start their
execution independent of its location within the source code. Hence
its essential for all C programs to have the main() function.

23
Cont’d…
printf (“Hello World\n”);
Instructs the computer to perform an action
 Specifically prints the string of characters within the (“ ”),
 Entire line is called a statement and all statements end with a
semicolon (;)
 Escape character (\)
 (\n) is the new line character.

Printf represents the standard output stream in C, and the meaning


of the entire statement is to insert a sequence of characters (in this
case the Hello World sequence of characters) into the standard
output stream (which usually is the screen).

Notice that the each statement in C ends with a semicolon character


(;). This character is used to mark the end of the statement and in
fact it must be included at the end of all expression statements in all
C programs (one of the most common syntax errors is indeed to
forget to include some semicolon after a statement).

24
Escape Sequences

\n new line


\t tab
\r carriage return
\a alert
\\ backslash
\” double quote
Cont’d…
return 0;
The return statement causes the main function to finish.
return may be followed by a return code (in our example is
followed by the return code 0). A return code of 0 for the
main function is generally interpreted as the program
worked as expected without any errors during its execution.
This is the most usual way to end a C console program.
comments
Comments are parts of the source code disregarded by the
compiler. They simply do nothing. Their purpose is only to
allow the programmer to insert notes or descriptions
embedded within the source code. C supports two ways to
insert comments:
// Line comment
/* Block comment */
26
Variables, Data types
In order to go a little further on and to become able to write
programs that perform useful tasks that really save us work we
need to introduce the concept of variable. Let us think that I ask
you to retain the number 5 in your mental memory, and then I
ask you to memorize also the number 2 at the same time. You
have just stored two different values in your memory. Now, if I
ask you to add 1 to the first number I said, you should be
retaining the numbers 6 (that is 5+1) and 2 in your memory.
Values that we could now for example subtract and obtain 4 as
result. The whole process that you have just done with your
mental memory is a simile of what a computer can do with two
variables. The same process can be expressed in C++ with the
following instruction set:
a=5;
b=2;
a=a+1;
result= a-b;

27
Cont’d…

Identifiers
A valid identifier is a sequence of one or more letters, digits or
underscore characters (_). Neither spaces nor punctuation
marks or symbols can be part of an identifier. Only letters, digits
and single underscore characters are valid. In addition, variable
identifiers always have to begin with a letter. They can also
begin with an underline character (_ ), but in some cases these
may be reserved for compiler specific keywords or external
identifiers, as
well as identifiers containing two successive underscore
characters anywhere. In no case they can begin with a digit.
Examples of identifiers; interest_rate, tax_rate, new_vat etc.

28
Fundamental data types
We store variables in our computer’s memory, but the computer
has to know what kind of data we want to store in them since its
going to occupy the same amount of memory to store a simple
number than a simple letter or a large number, and they are not
going to be interpreted the same way.

The memory in our computer is organized in bytes. A byte is the


minimum amount of memory we can manage in C. a byte can
store a relatively small amount of data: one single character or a
small integer (generally an integer between 0 and 255). In
addition the computer can manipulate more complex data type
that come from grouping several bytes, such as long number
and non-integer numbers.

29
Cont’d…

30
Description of each data type

31
Declaration of Variables
In order to use a variable in C, we must first declare it specifying
which data type we want it to be. The syntax to declare a new
variable is to write the specifier of the desired data type (like int,
bool, float...) followed by a valid variable identifier. For example:
int a;
float my_number; or float mynumber;

if you are going to declare more than one variable of the same
data type, we declare all of them in a single statement by
separating their identifiers with commas for example:

int a, b, c;

32
Cont’d…
This has exactly the same meaning as:
int a;
int b;
int c;
The integer data types char, short, long and int can be either
signed or unsigned depending on the range of number needed
to be represented. Signed types can represent both negative
and positive values, whereas unsigned types can only represent
positive values (and zero). This can be specified by using either
the specifier signed or the specifier unsigned before the type
name. For example:
unsigned short int NumberOfSisters;
signed int MyAccountBalance

33
Cont’d…
By default, if we do not specify either signed or unsigned most
compiler settings will assume the type to be signed hence
instead of the second declaration above we could have written
int MyAccountBalance;
with exactly the same meaning (with or without the keyword
signed).

An exception to this general rule is the char type, which exists


by itself and is considered a different fundamental data type from
signed char and unsigned char, thought to store characters. You
should use either signed or unsigned if you intend to store
numerical values in a char-sized variable.

34
Cont’d…
short and long can be used alone as type specifiers. In this case,
they refer to their respective integer fundamental types: short is
equivalent to short int and long is equivalent to long int. The
following two variable declarations are equivalent:
short year;
short int year;
Finally, signed and unsigned may also be used as standalone
type specifiers, meaning the same as signed int and unsigned int
respectively. The following two declarations are equivalent:
unsigned NextYear;
unsigned int NextYear;
To see what variable declarations look like in action within a
program, we are going to see the C code of the example about
your mental memory proposed at the beginning of this section:

35
Cont’d…
// operating with variables
#include <stdio.h>
main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
printf ( “Result = %d”, result);
// terminate the program:
return 0;
36 }
Scope of Variables

37
Cont’d…
A variable can be either of global or local scope. A global
variable is a variable declared in the main body of the source
code, outside all functions, while a local variable is one declared
within the body of a function or a block.
Note: Global variables can be referred from anywhere in the
code, even inside functions, whenever it is after its declaration.
The scope of local variables is limited to the block enclosed in
braces ({}) where they are declared. For example, if they are
declared at the beginning of the body of a function (like in
function main) their scope is between its declaration point and
the end of that function. In the example above, this means that if
another function existed in addition to main, the local variables
declared in main could not be accessed from the other function
and vice versa.

38
Initialization of Variables
When declaring a regular local variable, its value is by default
undetermined. But you may want a variable to store a concrete
value at the same moment that it is declared. In order to do that,
you can initialize the variable. There are two ways to do this in C:

1) type identifier = initial_value ; e.g. int a = 0;

2) type identifier (initial_value) ; e.g. int a(0);

Both ways are valid and equivalent in C programming.

39
Cont’d…
// initialization of variables
#include <stdio.h>
main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value undetermined
a = a + 3;
result = a - b;
printf (“Result = %d”, result)
return 0;
}

40
Scanf ();
Now that we have mastered the intricacies of printf
you should find scanf very easy. The scanf function
works in much the same way as the printf. That is it
has the general form:
scanf (control string,variable,variable,...)
In this case the control string specifies how strings of
characters, usually typed on the keyboard, should be
converted into values and stored in the listed variables.
However there are a number of important differences
as well as similarities between scanf and printf.
The most obvious is that scanf has to change the
values stored in the parts of computers memory that is
41
associated with parameters (variables).
scanf("%d,&a);
#include<stdio.h>
main()
{
int a , b , c;
printf("\n The first number is");
scanf("% d ",&a );
printf("The second number is");
scanf("% d",&b);
c= a+b;
printf ("The answer is %d \n", c);
}
42
Cont.
The first instruction declares three integer variables: a,
b and c. The first two printf statements simply display
message on the screen asking the user for the values.
The scanf functions then read in the values from the
keyboard into a and b. These are added together and
the result in c is displayed on the screen with a suitable
message. Notice the way that you can include a
message in the printf statement along with the value.

43
OPERATORS & EXPRESSIONS
1) Assignment Operators
2) Arithmetic operators.
3) Compound Assignment.
4) Increase and Decrease.
5) Relational and equality operators.
6) Logical Operators.
7) Conditional.
8) Comma.
9) SizeOf () *.
10) Precedence of Operators.
11) Basic Input-Output

44
Cont’d…
Operators
Once we know of the existence of variables and
constants, we can begin to operate with them. For
that purpose, C integrates operators. Unlike other
languages whose operators are mainly keywords,
operators in C are mostly made of signs that are not
part of the alphabet but are available in all keyboards.
This makes C code shorter and more international,
since it relies less on English words, but requires a
little of learning effort in the beginning.

45
The Fundamental C-Operators
1) Assignment Operator (=)
The assignment operator assign a value to a variable.
a=5;
This statement assigns a value 5 to the variable a the part at the
left of the assignment (=) operator is called the left value and the
right one is called the right value.
Other valid assignment expressions include;
a) a=b;
b) b=5; a=2+b;
c) a=b=c=5; Same as
d) a=2+(b=5);

46
Cont’d…
2) Arithmetic Operators (+, -, /, %, *).
a=11%3;

3) Compound Assignment (+=, -=, %=, /=, *=, &=, ^=, |


=)
Syntax:- Value += increase [value= value + increase]
a+=b; is the same as: a=a+b;
a-=5; …… a=a-5;
a/=b; …… a=a/b;
price*= unit +1;…. price= price*(unit+1);

47
Example of using compound assignment operators
// compound assignment operators
#include <stdio.h>
#include <conio.h>
main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
printf (“a= %d”, a);
return 0;
}

48
Cont’d…
4) increase and decrease (++, --)
Examples:
a++; a=a+1;
b--; b=b-1;

Given the following expressions determine the final values of a & b:


b=3; b=3;
a=++b; a=b++;
a=4,b=4 a=3, b=4

Find out how this come about????

49
Cont’d…
5) Relational and equality operators (==, !=, >, <, >=, <=)
Some examples
(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false

50
Cont’d…
6) Logical Operators
C has the following logical operators, they
compare or evaluate logical and relational
expressions.

Operator Meaning
&& Logical AND

|| Logical OR

! Logical NOT
51
Cont’d…
Examples
Logical AND (&&)

a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the
whole expression is true only if both expressions are true i.e., if a is
greater than b and x is equal to 10.

Logical OR (||)
The logical OR is used to combine 2 expressions or the condition
evaluates to true if any one of the 2 expressions is true.
Example

a < m || a < n
The expression evaluates to true if any one of them is true or if both
of them are true. It evaluates to true if a is less than either m or n
and when a is less than both m and n.

52
Cont’d…
Logical NOT (!)
The logical not operator takes single expression and
evaluates to true if the expression is false and
evaluates to false if the expression is true. In other
words it just reverses the value of the expression.

For example

! (x >= y) the NOT expression evaluates to true only if


the value of x is neither greater than or equal to y.

53
Cont’d…
7) Conditional operators (?)
The conditional operator evaluates an expression returning a
value if that expression is true and a different one if an
expression is evaluated as false. Its format is:

condition? result1 : result2


If condition is true the expression will return result1, if it is not it
will return result2. Examples,

 7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.


 7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
 5>3 ? a : b // returns the value of a, since 5 is greater than 3.
 a>b ? a : b // returns whichever is greater, a or b.

54
Example

// conditional operator
#include <stdio.h>
#include <conio.h>
main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
printf (“c =%d”, c);
return 0;
}

55
Cont’d…
In this example a was 2 and b was 7, so the expression being
evaluated (a>b) was not true, thus the first value specified after
the question mark was discarded in favor of the second value
(the one after the colon) which was b, with a value of 7.

8) Comma operator ( , )
The comma operator (,) is used to separate two or more
expressions that are included where only one expression is
expected. When the set of expressions has to be evaluated for a
value, only the rightmost expression is considered.
For example, the following code: a = (b=3, b+2);

56
Precedence of Operators

57
Cont’d…
Grouping defines the precedence order in which operators are
evaluated in the case that there are several operators of the
same level in an expression.
All these precedence levels for operators can be manipulated or
become more legible by removing possible ambiguities using
parentheses signs ( and ), as in this example:
a=5 + 7 % 2; may be written either as:

a= 5 + (7%2);

OR
a= (5+7)%2; depending on the operation we want to perform.

58
Basic Input / Output
Using the standard input and output library, we will
be able to interact with the user by printing
messages on the screen and getting the user's
input from the keyboard.
C uses a convenient abstraction called stream to
perform input and output operations in sequential
media such as the screen or the keyboard. A
stream is an object where a program can either
insert or extract characters to/from it. We do not
really need to care about many specifications about
the physical media associated with the stream - we
only need to know it will accept or provide
characters sequentially.

59
#include <stdio.h> Cont’d…
void main() {
int min, x = 0;
while(x <= 0){
printf("Input number : "); //input
scanf("%d", &x);
min = x; // we assume first given number is the smallest
}
while (x != 0) {
printf("Input number : "); // input
scanf("%d", &x);
if(x > 0 && x < min )
min = x;
}
printf("Smallest given number is: %d\n", min); // output
}
60
.
#include <stdio.h>
Cont’d…
void main() {
int min=0, x=1;
// in first iteration x=1
while (x != 0) {
printf("Input number : ");
scanf("%d", &x); //after first iteration x becomes != 1
if (x > 0) {
if ((min==0) || (x < min)) min = x;
}
}
printf("Smallest given number is: %d\n", min);
}
61
Program to add two numbers:
#include<stdio.h>
int main()
{
int a,b,c;
printf (“Enter first value:”);
scanf(“%d”,&a);
printf (“\n Enter second value:”);
scanf(“%d”,&b);
c=a + b;
printf(“%d + %d = %d” ,a ,b, c);
return 0;
}

62
Program for arithmetic operators:
#include<stdio.h>
#include<conio.h>
void main()
{
float a, b;
printf(“Enter value for a :\n”);
scanf(“%f”, &a);
printf(“Enter value for b :\n”);
scanf(“%f”, &b);
printf(“Addition of a and b =%f\n”, a+b);
printf(“Subtraction of a and b =%f\n”, a-b);
printf(“Multiplication of a and b =%f\n”, a*b);
printf(“Division of a and b =%f\n”, a/b);
getch();
}

63
Assignment
Write a program to solve a quadratic equation say, X2-2x+3=0 ,
your program should include the following conditions:

1) if (b2-4ac) =0, Real and Equal Roots


2) if (b2-4ac) <0, Complex Roots.
3) if (b2-4ac) > 0 Real Roots

64
Constants
C allows you to declare constants. When you declare a constant it
is a bit like a variable declaration except the value cannot be
changed. The const keyword is to declare a constant, as shown
below:
int const a = 1;

const int a =2;


Note :
1) You can declare a value before or after the type. Choose one and
stick to it.
2) It is usual to initialize a const with a value as it cannot get a value
any other way.

65
Example 1
#include <stdio.h>
#define TAXRATE 0.10
main()
{
float balance, tax;
balance = 72.10;
tax = balance * TAXRATE;
printf(“The tax on %.2 is %.2\n”, balance,tax);
}

Output:- The tax on 72.10 is 7.21

66
67
68
Example 2
#include <stdio.h>
#define MAGIC 10 // define MAGIC = 10
int main(void) // void specifies return type of main i.e. nothing
should be returned to the operating system.
{
int i, fact, quotient;
while (i++ < 3) {
printf(”Guess a factor of MAGIC larger than 1: ");
scanf("%d”, &fact);
quotient = MAGIC % fact;
if (0 == quotient)
printf(”You got it!\n”);
else
printf(”Sorry, You missed it!\n”);
}
return 0;
}
69
C Language Keywords
The following names are reserved by the C language. Their
meaning is already defined, and they cannot be re-defined
to mean anything else. Other than these names, you can
choose any names of reasonable length for variables,
functions etc. The names must begin with a letter or
underscore (letters are better), and then can contain letters,
numbers and underscores.

70
Introduction to Strings
A string is a sequence of characters. Any sequence or set of
characters defined within double quotation symbols is a constant
string. In C it is required to do some meaningful operations on
strings they are:
 Reading string, displaying strings
 Combining or concatenating strings
 Copying one string to another.
 Comparing string & checking whether they are equal.
 Extraction of a portion of a string .

Strings are stored in memory as ASCII codes of characters that


make up the string appended with ‘\0’(ASCII value of null).
Normally each character is stored in one byte, successive
characters are stored in successive bytes.
71
Initialization of Strings.
The initialization of a string must the following form which is
simpler to one dimension array.

char month1[ ]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’};

Then the string month is initializing to January. This is perfectly


valid but C offers a special way to initialize strings. The above
string can be initialized char month1[]=”January”; The characters
of the string are enclosed within a part of double quotes. The
compiler takes care of string enclosed within a pair of a double
quotes. The compiler takes care of storing the ASCII codes of
characters of the string in the memory and also stores the null
terminator in the end.
Example

#include < stdio.h >


#include<string.h>
main()
{
char month[15];
printf (“Enter the string”);
gets (month);
printf (“The string entered is %s”, month);
}

Note: More about Strings and Functions used will be


covered in the course.

73
Cont’d…
Readings:
Read about how flow chart diagrams are used to
model computer programs and all the various
symbols used in modeling.

References
1) C by example By K. Noel.

74
75
****END****

76

You might also like