0% found this document useful (0 votes)
24 views11 pages

Intro Programming C

This document contains code snippets and explanations related to various C programming concepts such as: 1) A simple "Hello World" program to introduce basic syntax and main function. 2) Demonstrates variables, arithmetic expressions, and formatting output using printf. Includes exercises to modify the loop order and conversion. 3) Covers input/output using getchar and putchar, redirecting input/output, and the value of EOF. 4) Examples of arrays, counting characters, and adding a counter. Includes an exercise to modify the program. 5) Introduction to functions including function prototypes, parameters, and recursion. Includes exercises about calling and modifying the power function.

Uploaded by

Koffi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
24 views11 pages

Intro Programming C

This document contains code snippets and explanations related to various C programming concepts such as: 1) A simple "Hello World" program to introduce basic syntax and main function. 2) Demonstrates variables, arithmetic expressions, and formatting output using printf. Includes exercises to modify the loop order and conversion. 3) Covers input/output using getchar and putchar, redirecting input/output, and the value of EOF. 4) Examples of arrays, counting characters, and adding a counter. Includes an exercise to modify the program. 5) Introduction to functions including function prototypes, parameters, and recursion. Includes exercises about calling and modifying the power function.

Uploaded by

Koffi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

1) Hello World!

hello.c
#include <stdio.h>

void main()
{
printf("hello, world!\n");
}

2) Variables and Arithmetic Expressions


temp.c
#include <stdio.h>

/* print Fahrenheit-Celsius table */


int main()
{
int fahr;
for (fahr = 0; fahr <= 300; fahr = fahr + 20)
printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32));

return 0;
}

Macros) Replace the "magic numbers" (0, 300, 20) with corresponding #define

Extra exercises:

Reverse loop) Modify the temperature conversion program to print the table in reverse order, that is,
from 300 degrees to 0.

Reverse Conversion) Write a program to print the corresponding Celsius to Fahrenheit table.

4) Input/Output (I/O)
[In general, we did not have much time for these exercises]

Copy.c
#include <stdio.h>

/* copy input to output; 1st version */


int main()
{
int c;

c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}

Use the "copy.c" source code as input of the compiled binary program (I.e. copy the source code)

(TIP: ./a.out < copy.c). Do you see the source code on screen? Now, use the binary file as input to itself,
what do you see?

You can also redirect the output to another file ./a.out < copy.c > output.c .
Do you expect that a copy of the executable to be also be executable? (If time allows: Try it!) YES/NO ?

=!) The relational operator != means "not equal to". What are the possible values of (c != EOF) ? (e.g.,
do a printf of the evaluated expression)

EOF) getchar returns a distinctive value when there is no more input, a value that cannot be confused
with any real character. This value is called EOF, for ``end of file''. EOF is an integer defined in <stdio.h>,
but the specific numeric value doesn't matter as long as it is not the same as any char value.

Write a program to print the value of EOF. What is the value of EOF?

4) Arrays
array_count.c
#include <stdio.h>

/* count digits, white space, others */


void main() {
int c, i, nwhite, nother;
int ndigit[10];

nwhite = nother = 0;

for (i = 0; i < 10; ++i)


ndigit[i] = 0;

while ((c = getchar()) != EOF)


if (c >= '0' && c <= '9')
++ndigit[c - '0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

for (i = 0; i < 10; ++i)


printf(" %d", ndigit[i]);

printf(", white space = %d, other = %d\n", nwhite, nother);


}

What is the output of this program on its source code? (There is no wrong answer) (Tip ./a.out < input.c)
9 3 0 0 0 0 0 0 0 1, white space = 122, other = 331

Extra) Add a counter for the letter “a” (whether it be uppercase or lowercase)

[work this exercise]

5) Functions
function_pow.c
#include <stdio.h>

/* power function prototype */


int power(int m, int n);

/* test power function */


int main()
{
int i;

for (i = 0; i < 10; ++i)


printf("%d %d %d\n", i, power(2, i), power(-3, i));

return 0;
}

/* power: raise base to n-th power; n >= 0 */


int power(int base, int n)
{
int i, p;

p = 1;
for (i = 1; i <= n; ++i)
p = p * base;
return p;
}
Run the program.

Q1) How many times (total at runtime) does main call the function power?

Q2.1) The definition of power before main is called a function prototype. See what happens if you erase
( or comment) that line: try to re-compile and run the program and write the result:

Q2.2) See what happens if you change one of the parameters to float instead of int.

6) Control Flow
[Not enough time to see this exercise. However, the switch is new for most students]

array_count_switch.c

Use the swich statement to write an equivalent program to array_count.c (count digits, white space -' ',
'\t', '\n'-, others), here some help (complete the program) :
#include <stdio.h>

int main() /* count digits, white space, others */


{
int c, i, nwhite, nother, ndigit[10];

nwhite = nother = 0;

for (i = 0; i < 10; i++)


ndigit[i] = 0;

while ((c = getchar()) != EOF) {


switch (c) {
case '0': case '1':
ndigit[c - '0']++;
break;
case ' ':
case '\t':
nwhite++;
break;
default:
break;
}
}

printf("digits =");
for (i = 0; i < 10; i++)
printf(" %d", ndigit[i]);

printf(", white space = %d, other = %d\n", nwhite, nother);


return 0;
}

Check that you get the same result as the program array_count.c (use same input for both) and write
the outputs:

7) Pointers
[This is a good exercise; we spend the needed time. First time many students handle pointers]

pointer_intro.c
#include <stdio.h>

void main()
{
int x = 1, y = 2, z[10];
int *ip; /* ip is a pointer to int */

ip = &x; /* ip now points to x */

y = *ip; /* y is now 1 */
*ip = 0; /* x is now 0 */

printf("x=%d ; y=%d\n", x, y);

/* Printing pointer address %p */


printf("ip=%p \n", ip);
ip = &z[0]; /* ip now points to z[0] */
printf("ip=%p \n", ip);

}
Run the code. And write the output:

x=0 ; y=1
ip=0x7ffd2becba40
ip=0x7ffd2becba50

A pointer holds the address in RAM of the object "it points to".

How many bytes (sizeof) do you expect a pointer to int on a 64-bit architecture to require (I.e., its size in
bytes)?

[Rephrase question]
We will validate or correct your answer with the sizeof(), function. (Note: The sizeof function returns a
variable of type long unsinged int, tip for printf formatter: %lu.).

Program and Run a code that prints the size of the ip pointer, and answer what is the size (in bytes) of a
pointer to integer in your architecture?

Do you expect the size of a pointes to char to be of what size? (Validate)

Check the size of an integer type on RAM using sizeof() function, and write its value:

How many more bytes (∆Bytes) do you expect to be the value of the address of the last element of the
array z[] as compared with the first element? [Rephrase question, put delta or something]

Validate by dereferencing the address of all the elements of z[],

Pointer arithmetic) with the help of a pointer to int and pointer arithmetic (++), use a for loop and a
validate that you get the same results as previous exercise

Pointer as functions parameters)


[Good exercise too. One student did it super fast: have extra exercise for the fast ones. In general they
have some problems to appropriate the concepts]

pointer_functions_swap.c
#include <stdio.h>

void swap (int x, int y);

void main()
{
int a = 1, b = 2;

printf("a=%d ; b=%d\n", a, b);

swap(a,b);
printf("a=%d ; b=%d\n", a, b);
}

void swap(int x, int y) /* WRONG */


{
int temp;
temp = x;

x = y;
y = temp;
}
This program will not work Since C passes arguments to functions by value, there is no direct way for the
called function to alter a variable in the calling function.
The way to obtain the desired effect is for the calling program to pass pointers to the values to be
changed: swap(&a, &b).

Write a proper version using pointer as swap arguments write the modified swap function here:

8) Structs
[PROFESSOR NOTE: See if I make them create a small struct. We saw the exercise too fast.

Good to handle the include math.h]

Struct.c
#include <stdio.h>

typedef struct point {


int x;
int y;
} point_t;

struct square {
struct point pt1;
struct point pt2;
};

int main()
{
struct point p = { .y = 2, .x = 1 };
printf("%d,%d\n", p.x, p.y);

point_t q = { 2, 3 };
struct point * pp;

pp = &p;
printf("%d,%d\n", pp->x, pp->y);
pp = &q;
printf("%d,%d\n", pp->x, pp->y);

//point_t r = makepoint( 100 , 100 );


//point_t s = substractpoint( p , q );
//printf("%f\n", distance(p,q));

return 0;
}

1) makepoint: make a point from x and y components


// struct point makepoint(int x, int y);

2) substractpoints: "substract" two points


// struct point substractpoint(struct point p1, struct point p2);

3) distance: euclidian distance between two points . TIP, use the function sqrt( double x ) , #include the
library <math.h>, and compile/link the program with the "-lm" flag (cc struct.c -lm).
//double distance(struct point p1, struct point p2);

On eclipse, you need to include the math.h library (-lm) in the Properties/C Build/Settingthings/Tool
Settings/GCC C Compliler/Includes + Add directory path: “m”.

3b) distance: euclidian distance between two points (pointer version)


//double distance(struct point * p1, struct point * p2);
4) diagonal: diagonal of a square (pointer version)
// double diagonal(struct square * sq);

Unions) Defina a union, and check that the members of a union share the same memory address space.

Appendix)
Pointers and Arrays) Write a pointer version of the function strcat strcat(s,t) copies the string t to the
end of s. This is the array version:
/* strcat: concatenate t to end of s; s must be big enough */
void strcat(char s[], char t[]) {
int i, j;

i = j = 0;
while (s[i] != '\0') /* find end of s */
i++;
while ((s[i++] = t[j++]) != '\0') /* copy t */
;
}

Multi-Dimensional Array)

appendix_arrays_multy_matrix_sum.c. See code:


/* C program to find the sum of two matrices of order 2*2 */

#include <stdio.h>

int main() {
float a[2][2], b[2][2], result[2][2];

/* Taking input using nested for loop */


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j) {
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

/* Taking input using nested for loop */


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j) {
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

/* adding corresponding elements of two arrays */


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j) {
result[i][j] = a[i][j] + b[i][j];
}

/* Displaying the sum */


printf("\nSum Of Matrix:\n");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j) {
printf("%.1f\t", result[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}

Implement matrix multiplication function, and add it to the main program. Use the following prototype

void mmult(float a[2][2], float b[2][2], result[2][2]);

Can you generalize it to square matrix of any size using arrays? What will you use? Write the function
prototype.
#include <stdio.h>

enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun };

int main() /* Example Program */

{
enum week day;
day = Wed;
printf("%d", day);
return 0;
}

Command-line Arguments)

appendix_echo.c)
#include <stdio.h>

/* echo command-line arguments; 1st version */


int main(int argc, char *argv[])

{
int i;

for (i = 1; i < argc; i++)


printf("%s%s", argv[i], (i < argc - 1) ? " " : "");
printf("\n");
return 0;
}

(Since argv is a pointer to an array of pointers, we can manipulate the pointer rather than index the
array. This next variant is based on incrementing argv, which is a pointer to pointer to char, while argc is
counted down K&R page 103)

Pointer to function) Just an example (From Wikipedia):


#include <stdio.h> /* for printf */
#include <string.h> /* for strchr */

double cm_to_inches(double cm) {


return cm / 2.54;
}

// "strchr" is part of the C string handling (i.e., no need for declaration)


// See https://en.wikipedia.org/wiki/C_string_handling#Functions

int main(void) {
double (*func1)(double) = cm_to_inches;
char * (*func2)(const char *, int) = strchr;

printf("%f %s", func1(15.0), func2("Wikipedia", 'p'));


/* prints "5.905512 pedia" */
return 0;
}

A lot of introductory exercises)

https://www.programiz.com/c-programming/c-decision-making-loops-examples

You might also like