You are on page 1of 27

FIRST C PROGRAM

Example program
 In style of “Hello, world!” .c file structure
 Syntax: comments, macros, basic declarations
 The main() function and function structure
 Expressions, order-of-operations
 Basic console I/O (printf(), scanf(), etc.)
 Example program:
 hello-0.c
 hello-1.c
 hello-3.c
Writing the first program
 Go back to the first set of slides Lec-00 to login to
Linux
 Shown on screen is hello-world.c
 Write the program using vi
 Compile the program using gcc
 Run the program
 Raise both hands after you finish
First program hello world
#include <stdio.h>
/* header file about standard input/ output*/
/* The main() function */
int main ( void )/*entry point, return will be integer */
{
/*write message to console*/
/* put indentation of the lines to indicate the */
/* part of of main */
printf ( "hello, DKP students\n" );
return (0); / ∗ exit (0 => success) ∗ /
}
Hello world explanation
 printf(): output text to console window (stdout)
and end the line (\n)
 String literal: written surrounded by double quotes
 return 0; exits the function, returning value 0 to
caller
Flow chart of program (1/2)
 Flow chart must have ‘Begin’ and ‘End’
 The above symbol is an oval
 Connection between symbols is using
line/ arrow
 The arrow indicates the flow off the
process
 The ‘Begin’ chart can have one output
only (arrow leaving the oval)
 The ‘End’ chart can have one input only
(arrow entering the oval)
Flow chart of program (2/2)
 There is an output to the screen
 Symbol of output is parallelogram (‘jajaran
genjang’)
 Parallelogram can have one input and one output
only
 Same symbol is used also for input
 Input or output is indicated inside the parallelogram
Flowchart for ‘hello_world.c’
Write your first program
 Duplicate the program hello_wold.c mentioned
before
 Check the output, you can also change the output
anyway you want
 After you finish and satisfied, raise both hands
Hello world again (variation)
 Alternatively, store the string in a variable first:
int main ( void )/ ∗ entry point ∗ /
{
const char msg[] = "hello, DKP students" ;
/ ∗ write message to console ∗ /
printf (“%s\n”, msg);
return (0);
}
 const keyword: qualifies variable as constant cannot be
modified during program execution
 char: data type representing a single character; written in
quotes: ’a’, ’3’, ’n’
 const char msg[]: a constant array of characters
String characters
 Strings stored as character array
 Null-terminated (last character in array is ’\0’ null)
 Not written explicitly in string literals
 Special characters specified using \ (escape
character):
 \\ – backslash, \’ – apostrophe, \” – quotation
mark
 \b, \t, \r, \n – backspace, tab, carriage
return, linefeed
 \ooo, \xhh – octal and hexadecimal ASCII
character codes, e.g. \x41 – ’A’, \060 – ’0’
Input – output (console or terminal)
 stdout, stdin: console output and input
streams
 printf(string): print string to stdout

 putchar(char): print character to stdout

 char = getchar(): return character from

stdin
 string = gets(string): read line from

stdin into string


 Many others -later this week
Preprosesor and macro
 Preprocessor macros begin with # character
 #include <stdio.h>
 #define msg "hello, DKP students" defines
msg as “hello, DKP students” throughout
source file
 many constants specified this way
 #define can take arguments and be treated
like a function
#define add3(x,y,z) ((x)+(y)+(z))
 parentheses ensure order of operations
 macro = collection of characters
Write your next programs
 Duplicate the program hello_wold.c, but use the
“const char msg[]” or any similar variable
 Check the output, you can also change the output
anyway you want
 After you finish and satisfied, raise both hands
 Duplicate the program hello_wold.c, but use the
“#define msg “..”” or any similar definition
 Check the output, you can also change the output
anyway you want
 After you finish and satisfied, raise both hands
Structure in C program
/* Begin with comments about file contents */
Insert #include statements and preprocessor definitions
Function prototypes and variable declarations
Define main() function
{
Function body
}
Define other function
{
Function body
}
.
.
.
Comments in C programs
 Comments: /* this is a simple comment */
 Can span multiple lines
/ * This comment
spans
multiple lines * /
 Completely ignored by compiler
 Can appear almost anywhere
 / * hello .c -- our first C program
written by Hartono Pranjoto * /
Include macro in C programs
 Header files: constants, functions, other declarations
#include <stdio.h> – read the contents of the
header file stdio.h
 stdio.h : standard I/O functions for console, files

/ * hello .c -- our first C program


written by Hartono Pranjoto * /
#include <stdio.h> / ∗ basic I/O
facilities ∗ /
A little more on macro
 A macro is a collection of characters
 stdio.h – part of the C Standard Library
 Other important header files: ctype.h, math.h,
stdlib.h, string.h, time.h
 For the ugly details: visit http://www.unix.org/
single_unix_specification/
(registration required)
 Included files must be on include path
 -Idirectory with gcc: specify additional include
directories
 Standard include directories assumed by default
 #include "stdio.h" – searches ./ for stdio.h
first
Variables
 Must declare variables before use
 Variable declaration:
 int a; - integer variable
 long b; - long integer variable
 short c; - short integer (16 bit)
 float d; - floating point
 double e; - double precision float
 char f; - character type

 Many other types (more next lecture. . . )


Initialize variables
 Uninitialized, variable assumes a default value
 Variables initialized via assignment operator:
n = 3;
 Can also initialize at declaration:
float phi = 1.6180339887;
 Can declare/initialize multiple variables at once:
int a, b, c =0, d=4;
Arithmetic operation
 x+y; /* addition, penjumlahan */
 x-y; /* subtraction, pengurangan */
 x*y; /* multiplication, perkalian */
 x/y; /* division, pembagian */
x%y; /* integer remainder of division,
sisa pembagian bilangan bulat */
 A simple statement: y = x+3∗x/(y-4);
 Numeric literals like 3 or 4 valid in expressions
 Semicolon ends statement (not newline)
 Example will follow…………
Arithmetic operation
Operator Example Same As
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
-- a-- a=a-1
++ a++ a=a+1
Order of operation
Assume x =2.0 and y =6.0.
Evaluate the statement float z = x+3∗x/(y−4);
1. Evaluate expression in parentheses
float z = x+3∗x/(y−4); → float z = x+3∗x/2.0;
2. Evaluate multiplies and divides, from left-to-right
float z = x+3∗x/2.0; → float z = x+6.0/2.0; →
float z = x+3.0;
3. Evaluate addition
float z = x+3.0; → float z = 5.0;
4. Perform initialization with assignment
Now, z =5.0.
How do I insert parentheses to get z =4.0?
float z = x+3∗x/y−4;
Function prototypes
 Functions must also be declared before use
 Declaration of function is called function prototype
 Function prototypes:
int factorial ( int ); or
int factorial (int n);
 Prototypes for many common functions in header files for C
Standard Library
 General form:
return_type function_name(arg1,arg2,...);
 Arguments: local variables, values passed from caller
 Return value: single value returned to caller when function exits
 void – signifies no return value/arguments int rand(void)
The main() function
 main(): entry point for C program
 Simplest version: no inputs, outputs 0 when
successful, and nonzero to signal some error
int main(void);
 Two-argument form of main(): access command-
line arguments
int main(int argc, char ∗∗argv);
 More on the char **argv notation later when we
talked about pointers and pointer to pointers …
Function declaration
Function declaration
{ declare variables;
program statements;
}
 Must match prototype (if there is one)
 variable names don’t have to match
 no semicolon at end

 Curly braces define a block – region of code


 Variables declared in a block exist only in that
block
 Variable declarations before any other statements
Another trial of C programming
#include <stdio.h>
#include <math.h>

/* try to work out some mathematical values*/

int main ( void )/*entry point, return will be integer */


{
float a, x, y, z; /* declaration of variables */
x = 2.0; /* value of variable x */
y = 6.0; /* value of variable y */
/* put in parenthesis so that value of z = 4.0 */
z = x+3∗x/y−4; /* how to get z = 4.0 */
a = log10(y);
printf (“Value of x - %f\n”, x);
printf (“Value of y - %f\n”, y);
printf (“Value of z - %f\n”, z);
printf (“Value of a - %10.8f\n”, a);
return (0); / ∗ exit (0 => success) ∗ /
}

You might also like