Professional Documents
Culture Documents
Programming
How to Write and Compile
C Programs
C, C++ and Java
Compilers: Microsoft Visual C++, GCC, Borland
C
Since we will be working on PCs:
Microsoft Visual C++
Open new Win32 Console Application
Name it (in “project name”)
Click “a hello world application”
Go to file view, source files, then the name of your
project.cpp
Some Things About C
Case matters, white space does not
Comments go between /* and */
Each statement is followed by a semicolon
Execution begins in the main function:
int main(int argc, char* argv[]) { /* ignore this */
/* start here */
return 0; /*end here */
}
What are C libraries?
C is a lightweight language. Most of its intelligence is
compartmentalized in libraries.
Almost all c programs use the “stdio” or standard
input/output library. Many also use the “math” library.
To use a library, include the header file (I.e., “stdio.h”)
at the top of the file.
For most special purpose libraries (I.e., math) you need
to include the library on the link line. In Visual C++,
go to project->settings->object/module libraries.
C Variable Types
The most common types are: char, int, float, and double.
Strings are arrays of characters (we’ll cover arrays later).
Declare a variable before you use it:
int x; /* declares an integer called x. Its value is not assigned. */
float y, z = 3.14159; /* declares two floating point numbers. z is set
equal to pi */
z = 4; /* now z is equal to 4 */
myVal = 2; /* This would be an error, because myVal was not yet
declared */
Logical Operators
C defines these logical operators: <, >, <=,
>= and == (the equivalence operator)
You can compare any variable. Characters
are compared based on their ASCII values.
All answers will be true (not zero) or false
(0)
You can extend the logic with && (and), ~
(not) and || (or).
The If Statement
Syntax: if (expression) statement;
If the expression is true (not zero), the statement is
executed. If the expression is false, it is not
executed.
You can group multiple expressions together with
braces:
if (expression) {
statement 1;
statement 2;
statement 3;
}
The If/Else Statement
Syntax: if (expression) statement_1; else
statement_2;
If the expression is true, statement_1 will
be executed, otherwise, statement_2 will
be.
Counter = 0;
Counter = 1;
Counter = 2;
Functions
Any non-trivial program will have multiple functions
C functions look like methods in Java
Functions have return types
int, float, void, etc.
Functions have unique names
Functions have parameters passed into them
Before a function can be used, it must be declared and/or
defined
a function declaration alone is called a prototype
prototypes can be in a separate header file or included in the file
their definition appears in
Function Example
#include <stdio.h>
#define PI 3.14
int main() {
float radius, area;
int totals[5];
int i;
for(i=0; i<5; i++)
totals[i] = 0;
char line[MAX_LINE];
scanf(“%s”, line);
Illegal initialization
int scores[5];
scores = { 2, -3, 10, 0, 4 };
More on Arrays
Accessing arrays
no .length parameter in array
remember, no bounds checking
#define NUM_STUDENTS 70
int main() {
int grades[NUM_STUDENTS];
setNums(grades, NUM_STUDENTS);
return 0;
}
Strings
In C, strings are just an array of characters
Because strings are so common, C provides a
standard library for dealing with them
to use this library, include the following:
#include <string.h>
This library provides means of copying strings,
counting characters in string, concatenate strings,
compare strings, etc.
By convention, all strings are terminated by the
null character ( \0 )
regardless of the size of the character array holding
the string
Common String Mistakes
C does not allow standard operators to be
used on strings
str1 < str2 does not compare the two strings
it does compare the starting address of each string
str1 == str2 does not return true if the two
strings are equal
it only returns true if the starting address of each
string is the same
str3 = str1 + str2 does not combine the two
strings and store them in the third
it adds the starting addresses of each string
Common String Functions
int strlen(char str[]);
counts the number of characters up to (but not counting) the null
character and returns this number
int strcpy(char strTo[], char strFrom[]);
copies the string in strFrom to the string in strTo
make sure strTo is at least as big as strFrom
int strcat(char strTo[], char strFrom);
copies the string in strFrom to the end of strTo
again, make sure strTo is large enough to hold additional chars
int strcmp(char str1[], char str2[]);
compares string 1 to string 2
return values are as follows
less than 0 if str1 is lexicographically less than str2
0 if str1 is identical to str2
greater than 0 if str1 is lexicographically greater than str2
Structures
C does not have classes
However, C programmers can create their
own data types
called structures
Structures allow a programmer to place a
group of related variables into one place
Creating a Structure
Use the keyword struct to create a structure
Example of creating a structure
struct foo {
char student[30];
int grades[7];
float endingGrade;
};
Variables can now be created of the type struct foo
Example of creating a structure variable
int main() {
struct foo myStruct;
…
Notice that the struct keyword is part of the new data type
name
Using Structures
To access any of the member variables
inside the structure:
use the structure variable name, a period, and
the member variable name
When passed to a function, a structure is
passed by value
just like any other data type
Example Using Structures
int main() {
struct foo myStruct;
24
Pointer Variable Definitions and Initialization
Pointer variables
Contain memory addresses as their values
Normal variables contain a specific value
(direct reference)
Pointers contain address of a variable that has
a specific value (indirect reference)
Indirection – referencing a pointer value
25
Simple Pointers
Pointer is a value that points to a location in the memory
Pointer is associated with a type
int number ; 23
int * ptr_to_num ;
number
number = 23; 003F45A8
ptr_to_num = & number;
ptr_to_num
printf("Value is %d \n", (*ptr_to_num) );
26
More Pointers
int number ;
int * p1, * p2; number
p1 = & number ; p1 p2
number = 23;
p2 = & number ;
printf(" *p1 = %d *p2 = %d ", *p1, *p2);
/* Output ?? */
27
Pointers and Arrays
char str[32];
char *ptr;
ptr = str ;
28
Pointers and Arrays
int table [8]; 94
int *ptr ; table
ptr = table ;
ptr
table [ 4 ] = 94;
*( ptr + 4 ) = 94;
( ptr + 4 )
How about
ptr = & table[0]?? vs. ptr=table;??
29
Pointer operations
Can add and subtract numbers (like array indices)
Can increment and decrement!
30
NULL pointer
A way to tell that pointer points to nothing
void main()
{
char *msg = NULL;
MyPrint( msg );
}
31
Command
/* MyProg.c */ Line Arguments
int main ( int argc , char *argv[] )
{ ...
> myProg one two three
argc = 4
argv[0] = "myProg"
argv[1] = "one"
argv[2] = "two"
argv[3] = "three“
argv[4] = NULL
32
7.3 Pointer Operators
& (address operator)
Returns address of operand
int y = 5;
int *yPtr;
yPtr = &y; /* yPtr gets
address of y */
yPtr “points to” y
33
Fig. 7.2 | Graphical representation of a pointer pointing to an integer variable in memory.
34
Fig. 7.3 | Representation of y and yPtr in memory.
35
File Handling in C
Introduction
Files are places where data can be stored
permanently.
Some programs expect the same set of data to be
fed as input every time it is run.
Cumbersome.
Better if the data are kept in a file, and the
program reads from the file.
Programs generating large volumes of output.
Difficult to view on the screen.
Better to store them in a file for later viewing/
processing
w - open a file in write-mode, set the pointer to the beginning of the file.
a - open a file in write-mode, set the pointer to the end of the file.
rb - open a binary-file in read-mode, set the pointer to the beginning of the file.
wb - open a binary-file in write-mode, set the pointer to the beginning of the file.
ab - open a binary-file in write-mode, set the pointer to the end of the file.
r+ - open a file in read/write-mode, if the file does not exist, it will not be created.
w+ - open a file in read/write-mode, set the pointer to the beginning of the file.
r+b - open a binary-file in read/write-mode, if the file does not exist, it will not be created.
w+b - open a binary-file in read/write-mode, set the pointer to the beginning of the file.
FILE *empl ;
char filename[25];
scanf (“%s”, filename);
empl = fopen (filename, “r”) ;
Jaypee Institute of Information
Technology University, Noida
Closing a File
After all operations on a file have been completed, it
must be closed.
Ensures that all file data stored in memory buffers are
properly written to the file.
General format: fclose (file_pointer) ;
FILE *xyz ;
xyz = fopen (“test.txt”, “w”) ;
…….
fclose (xyz) ;
putc
Writes one character to a file
Takes a FILE pointer and a character to write as an
argument
fputc( 'a', stdout ) equivalent to
putchar( 'a' )
scanf / fprintf
File processing equivalents of scanf and printf
Jaypee Institute of Information
Technology University, Noida
Read/Write Operations on Files
The simplest file input-output (I/O) function are getc and putc.
getc is used to read a character from a file and return it.
char ch; FILE *fp;
…..
ch = getc (fp) ;
getc will return an end-of-file marker EOF, when the end of the file
has been reached.
putc is used to write a character to a file.
char ch; FILE *fp;
……
putc (ch, fp) ;
main() {
FILE *in, *out ;
char c ;
#include <stdio.h>
int main()
{ FILE *fileA, /* first input file */
*fileB, /* second input file */
*fileC; /* output file to be created */
int num1, /* number to be read from first file */
num2; /* number to be read from second file */
int f1, f2;
/* close files */
fclose(fileA);
fclose(fileB);
fclose(fileC);
return 0;
} /* end of main */ Jaypee Institute of Information
Technology University, Noida