SWIN BUR · NE . SWINBURNE UNIVERSITY OF TECHNOLOGY COS10008 - Foundations of Technical Programming Lab exercises 2 Getting Started C programming The only way to learn a new programming language is by writing programs in it. The first program to write is the same for all languages: Print the words: Hello, My Name is Peter In C, the program to print "Hello, My Name is Peter" is 1 #include <stdio.h> 2 3 4 - { 5 printf("Hello, My Name is Peter\n"); int main() 6 7 8 } return 0; Just how to run this program depends on the system you are using. As a specific example, on the UNIX operating system you must create the program in a file whose name ends in ".c", such as mytest1.c, then compile it with the command using MinGw. gcc mytest.c If you haven't botched anything, such as omitting a character or misspelling something, the compilation will proceed silently, and make an executable file called a.out. Second option is you can give the name of the output file as follows: Gcc -o mytest1.out mytest1.c If you run mytest1.out by typing the command. mytest1.out It will print: Hello, My Name is Peter Now, you should examine what is the purpose of writing In in your printf command. - In represents the newline character. You can see the difference typing and executing the following programs. Save this program as mytest2.c and output file as mytest2.out 1 #include <stdio.h> 2 3 int main() 4 - { printf("Hello, My Name is Peter"); 5 6 printf("Hello, I am from Japan"); 7 return 0; 8 } @Copyright: 2021 Swinburne University of Technology Week 2 Lab Activity 2 Version 1 CRICOS: 0011D 03/10/2021 Page 1 of 7
SWIN BUR . NE . SWINBURNE UNIVERSITY OF TECHNOLOGY COS10008 - Foundations of Technical Programming Now run the output: mytest2.out Output: Save the following program as mytest3.c and output file as mytest3.out 1 #include <stdio.h> 2 3 int main() 4 - { 5 printf("Hello, My Name is Peter\n");| printf("Hello, I am from Japan\n"); 6 7 return 0; 8 } Now run the output: mytest3.out Output: printf never supplies a newline character automatically, so several calls may be used to build up an output line in stages. Our first program could just as well have been written as follows: Save this program as mytest4.c and output file as mytest4.out #include <stdio.h> int main() { printf("Hello World\n"); printf("I am Gamunu"); return 0; Now run the output: mytest4.out Output: Here is a very basic example of a C program: Save this program as mytest5.c and output file as mytest5.out 1 #include <stdio.h> 2 int main() 3 - { 4 /* My first C program */ 5 printf("I can program in C! \n"); 6 return 0; 7 } @Copyright: 2021 Swinburne University of Technology Week 2 Lab Activity 2 Version 1 CRICOS: 0011D 03/10/2021 Page 2 of 7
SWIN BUR . NE . SWINBURNE UNIVERSITY OF TECHNOLOGY COS10008 - Foundations of Technical Programming Now run the output: